How can I refine the query to return only number of hits


(Curt Hu) #1

I want to write a query to return only number of hits for a specific query,
seemed that _count API doesn't work. is there any solution for this?


(Zhibin) #2

Are you querying through REST API or JAVA API?

If using Java, On the SearchRequestBuilder
-setSize(0)
-setSearchType(SearchType.COUNT)

To get the number of hits, use response.hits().getTotalHits(), assuming
response is your SearchResponse

Regards,
Zhibin

On Wednesday, 4 July 2012 13:08:23 UTC+8, Curt wrote:

I want to write a query to return only number of hits for a specific
query, seemed that _count API doesn't work. is there any solution for this?


(Curt Hu) #3

Hi, Thanks for reply. How about using REST API?

On Wednesday, July 4, 2012 1:35:28 PM UTC+8, Zhibin wrote:

Are you querying through REST API or JAVA API?

If using Java, On the SearchRequestBuilder
-setSize(0)
-setSearchType(SearchType.COUNT)

To get the number of hits, use response.hits().getTotalHits(), assuming
response is your SearchResponse

Regards,
Zhibin

On Wednesday, 4 July 2012 13:08:23 UTC+8, Curt wrote:

I want to write a query to return only number of hits for a specific
query, seemed that _count API doesn't work. is there any solution for this?


(Radu Gheorghe) #4

Hi Curt,

You need to add "size" : 0.

For example, this should work:
$ curl -XPOST localhost:9200/_search?pretty=true -d '{"query" : {
"match_all" : {}}, "size" : 0}'

On Wednesday, July 4, 2012 9:21:59 AM UTC+3, Curt wrote:

Hi, Thanks for reply. How about using REST API?

On Wednesday, July 4, 2012 1:35:28 PM UTC+8, Zhibin wrote:

Are you querying through REST API or JAVA API?

If using Java, On the SearchRequestBuilder
-setSize(0)
-setSearchType(SearchType.COUNT)

To get the number of hits, use response.hits().getTotalHits(), assuming
response is your SearchResponse

Regards,
Zhibin

On Wednesday, 4 July 2012 13:08:23 UTC+8, Curt wrote:

I want to write a query to return only number of hits for a specific
query, seemed that _count API doesn't work. is there any solution for this?


(Clinton Gormley) #5

Or with search_type:

$ curl -XPOST 'localhost:9200/_search?search_type=count&pretty=true' -d '
{"query" : { "match_all" : {}}}
'

clint


(Shaun Farrell) #6

You can do the Match_All and then set the size to 0. They you will
just have to grab the "total hits" variable from the result set.

Shaun Farrell

On Thu, Jul 5, 2012 at 4:03 AM, Clinton Gormley clint@traveljury.com wrote:

Or with search_type:

$ curl -XPOST 'localhost:9200/_search?search_type=count&pretty=true' -d '
{"query" : { "match_all" : {}}}
'

clint


(system) #7