Search code examples
performanceelasticsearchtypeslimit

Elasticsearch search index limit by type


I am new to elasticsearch and I am trying to use elasticsearch, search api.

My index structure consists of tree types. Say foo, bar and baz. All tree types have the same 'name' key with string values and what I am trying to achieve is to search all types but just retrieve max 5 items of each type.

I think I succeed with Multi Search API however; I wonder if I could maintain the same functionality with a single query instead (for better performance).

I searched the internet as much as I can. However, I couldn't find a better way. There is an answer in stackoverflow with a similar question which also offers multi search api; but is two years old and with an issue attached to it. I thought It is meaningful to ask again.

Here is the msearch I am using at the moment:

{"type" : "foo"}
{"query" : {"match": {"name": "bar"}}, "terminate_after": 5}
{"type" : "bar"}
{"query" : {"match": {"name": "bar"}}, "terminate_after": 5}
{"type" : "baz"}
{"query" : {"match": {"name": "bar"}}, "terminate_after": 5}

I think that will check all storage 3 times if I write a query with max 4 results.

Any help appreciated.


Solution

  • Aggregation using _type and then find top 5 from each:

    GET /index/_search 
    {
    "size": 0,
    "query": {
      "match": {
         "name": "bar"
       }
    },
    "aggs": {
      "group_by_type": {
         "terms": {
            "field": "_type"
         },
         "aggs": {
            "top_5_aggregation": {
                "top_hits":{
                    "size" :5
                 }
              }
           }
         }
      }  
    }