1

I'm building a leaderboard with elasticsearch. I'd like to query all documents who have points greater than a given amount using the following query:

{
"constant_score" : {
    "filter" : {
        "range" : {
            "totalPoints" : {
                "gt": 242
            }
        }
    }
}

This works perfectly -- elasticsearch appropriately returns all documents with points greater than 242. However, all I really need is the count of elements matching this query. Since I'm sending the result over the network, it would be helpful if the query simply returned the count, as opposed to all of the documents matching the filter.

How do I get elasticsearch to only report the count of documents matching the filter?

EDIT: I've learned that what I'm looking for is setting search_type to count. However, I'm not sure how to do this with elastic.js. Any noders willing to pitch in their advice?

Dany Joumaa
  • 2,030
  • 6
  • 30
  • 45

1 Answers1

1

You can use the query type count for exactly that purpose:

http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-search-type.html#count

This is an example that should help you:

GET /mymusic/itunes/_search?search_type=count
{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "range": {
          "year": {
            "gt": 2000
          }
        }
      }
    }
  }
}
Jettro Coenradie
  • 4,735
  • 23
  • 31
  • Hi Jettro! I saw that document, but I'm not sure how to use it with a range filter. Would you mind providing an example? – Dany Joumaa Apr 25 '14 at 15:36
  • A little more clarification: I'm using an elasticsearch adapter that only gives me control of the query JSON that is passed to elasticsearch. Is there a way to pass `search_type` in the JSON query? – Dany Joumaa Apr 25 '14 at 16:04
  • Thanks for your example Jettro. Is passing `search_type` in the URL the only way to do this? I'm using elasticsearchclient for node and it'd be awesome if I could just pass in `search_type` in the query JSON. – Dany Joumaa Apr 25 '14 at 18:34
  • No, this is coming from the elasticsearch manual: Out of the above, the search_type is the one that can not be passed within the search request body, and in order to set it, it must be passed as a request REST parameter. – Jettro Coenradie Apr 25 '14 at 22:26
  • I see. Is there a way to pass it programmatically with elastic.js? I am retagging my question in hopes a node programmer can see this. – Dany Joumaa Apr 25 '14 at 22:54