Search code examples
elasticsearchnest

Limit the size per index when searching multiple index in Elastic


I have been following the guidelines from this post. I can get the desired output but in the same DSL how can I limit the size of results for each index ?

Full text Search with Multiple index in Elastic Search using NEST C#

POST http://localhost:9200/componenttypeindex%2Cprojecttypeindex/Componenttype%2CProjecttype/_search?pretty=true&typed_keys=true     
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": {
                    "value": "componenttypeindex"
                  }
                }
              }
            ],
            "must": [
              {
                "multi_match": {
                  "fields": [
                    "Componentname",
                    "Summary^1.1"
                  ],
                  "operator": "or",
                  "query": "test"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": {
                    "value": "projecttypeindex"
                  }
                }
              }
            ],
            "must": [
              {
                "multi_match": {
                  "fields": [
                    "Projectname",
                    "Summary^0.3"
                  ],
                  "operator": "or",
                  "query": "test"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Solution

  • With your given query, you could use aggregations to group and limit number of hits per index (in this case, limiting to 5):

    {
      "size": 0,
      "query": {
        ... Same query as above ...
      },
      "aggs": {
        "index_agg": {
          "terms": {
            "field": "_index",
            "size": 20
          },
          "aggs": {
            "hits_per_index": {
              "top_hits": {
                "size": 5
              }
            }
          }
        }
      }
    }