Search code examples
elasticsearchelasticsearch-dslelasticsearch-query

retrieve only a specific _index documents in the hits of elasticsearch when querying on multiple indices


I am querying on two indices in one query of elasticsearch so I can aggregate on both of them at once. The problem is that I want only one of the indices documents to be in the hits and not both of them. Hence I would like to filter on the _index field in the query.

Query

http://localhost:9200/products,stores/_search

{
    query: {
        match_all: {}
    },
    aggs = {
        stores : { terms: { field: 'store_name' } }
    }
}

Sample Output

{"hits" :[{"_index": "products",
 "_type": "_doc",
 "_id": "PFS0OTD5UE",
 "_score": 123.057205,
 "_source": {}},

{"_index": "stores",
 "_type": "_doc",
 "_id": "SXBT3ER",
 "_score": 53.057205,
 "_source": {}}]}

I want to only retrieve the product index.


Solution

  • It is definitely possible by using post_filter:

    POST products,stores/_search
    {
      "query": {
        "match_all": {}
      },
      "aggs": {
        "stores": {
          "terms": {
            "field": "store_name"
          }
        }
      },
      "post_filter": {
        "term": {
          "_index": "products"
        }
      }
    }
    

    The aggregation will run on all documents from both indexes, but only the documents from products will be returned in the hits.