Search requests using Python

All the queries that we have discussed can be performed with the Elasticsearch Python client using the search function. To do this, first store the query inside a variable that is query in the following example:

query = {
     "query": {
        "match_all": {}
     },
   }

Call the search function with all the parameters including the index name, document type, and query. The size parameter used in the following search request can also be included inside the query itself:

response = es.search(index='twitter', doc_type='tweets', body=query, size=2, request_timeout=20)

Note

To search against more than one index, instead of using a string value, you need to use a list of index names. The same applies for document types too.

The response data comes in the following format:

{
 "hits": {
   "hits": [
     {
       "_score": 1,
       "_type": "tweets",
       "_id": "649956033515773953",
       "_source": {
         "contributors": null,
         "truncated": false,
         "text": "RT @lexcanroar: "No mass shootings in the past 30 years have been stopped by an armed civilian.""
         .
         .
       },
    {
    ...
    }
       "_index": "twitter"
     }
   ],
   "total": 124,
   "max_score": 1
 },
 "_shards": {
   "successful": 5,
   "failed": 0,
   "total": 5
 },
 "took": 5,
 "timed_out": false
}

The response contains an object hit that has an array of hits containing all the documents. Further, each hit inside an array of hits contains the following fields in it:

  • _score: The document score with respect to the query
  • _index: The index name to which the document belongs
  • _type: The document type to which the document belongs
  • _id: The unique ID of the document
  • _source: This contains all the fields and values

The documents inside _source can be accessed with the following code:

for hit in response['hits']['hits']:
       print hit.get('_source')
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.186.125