Riccardo
Riccardo

Reputation: 299

Python: How to get the total number of hits of a elasticsearch query

I'm having fun doing some experiments using Elasticsearch with the Enron email dataset. I did a query to get something that's not important for my actual question. I obtained a total hits of 4 and I'd like to print this number as:

The total number of hits is: 4

My question is: How can I get the total number of hits?

This is my query:

s = Search(using=client, index="enron_test").query('range', date={'gte': query_date_1, 'lte': query_date_2, "format": "dd/MM/yyyy||dd/MM/yyyy"})

and this is the result of the query taken from Sense:

{
   "took": 6,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 4,
       ...

Upvotes: 1

Views: 6088

Answers (2)

pcaceres
pcaceres

Reputation: 135

This worked for me

es=Elasticsearch([{'host':'url','port':'9200','timeout':60}])
res = es.count(index='your index', doc_type='your doc_type', body={'query': your query })["count"]

If it helps you, here are good examples of count with Python:

https://python.hotexamples.com/examples/elasticsearch/Elasticsearch/count/python-elasticsearch-count-method-examples.html

Upvotes: 1

arun_munagala
arun_munagala

Reputation: 65

You can try the following:

es=Elasticsearch([{'host':'url','port':'9200','timeout':60}])
result=es.search(index='your index',doc_type='your doc_type',body={'query':your query})
print(result['hits']['total'])

Upvotes: 1

Related Questions