I am using python elastic search client to query an elastic search instance and following an example on how to use it. I ran the code below and got nothing back for the query I'm trying to run.
In the for
loop below, how can I check the count or what kind of response I'm getting back from elasticsearch, while iterating over results['hits']['hits']
? Is there a way to convert this to a JSON array?
newResults= []
results = es_client(index="sampleindex", doc_type="sampledoc",
body={"query": {"match": {"text":sometext}}})
for i, hit in enumerate(results['hits']['hits']):
newResults.append(hit[i][_id])
print("%s) %s" % (doc['_id'], doc['_source']['content']))
results
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 122,
"max_score": 1.0,
"hits": [{
"_index": "someindex",
"_type": "doc",
"_id": "1",
"_score": 1.0,
"_source": {
"Name": "amazon"
}
},
{
"_index": "someindex",
"_type": "doc",
"_id": "2",
"_score": 1.0,
"_source": {
"Name": "alibaba"
}
}
]
}
}
Essentially, a JSON array is a dictionary which include a list of pair matching a key to a value. To do a conversion to a JSON array, think of it like converting to a list of paired elements.
Here are one JSON example:
{ "student": {name : "Chris", email: "chris@email.net"} }
Student would be the key. And the rest of the information would be the value, which in turn is a list of key-value pair.
Below is code showing how to use the built-in json
module to convert the data in the results
string into a Python data structure and then display some of its contents.
import json
#results = es_client(index="sampleindex", doc_type="sampledoc",
# body={"query": {"match": {"text":sometext}}})
results = '''
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 122,
"max_score": 1.0,
"hits": [{
"_index": "someindex",
"_type": "doc",
"_id": "1",
"_score": 1.0,
"_source": {
"Name": "amazon"
}
},
{
"_index": "someindex",
"_type": "doc",
"_id": "2",
"_score": 1.0,
"_source": {
"Name": "alibaba"
}
}
]
}
}
'''
results = json.loads(results) # Deserialize results into Python object.
print(f"There were {len(results['hits']['hits'])} hits:")
print()
for i, hit in enumerate(results['hits']['hits']):
print(f'hit[{i}]: {json.dumps(hit, indent=4)}')
Output:
There were 2 hits:
hit[0]: {
"_index": "someindex",
"_type": "doc",
"_id": "1",
"_score": 1.0,
"_source": {
"Name": "amazon"
}
}
hit[1]: {
"_index": "someindex",
"_type": "doc",
"_id": "2",
"_score": 1.0,
"_source": {
"Name": "alibaba"
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.