Search code examples
javascriptnode.jselasticsearchquerydsl

How to reference particular fields in the individual indices when searching through alias in elasticsearch?


const elasticsearch = new Client({ node: `http://localhost:9200` })

const response = await elasticsearch.search({
  index: companyIndex,
  body: {
    query:{
      query_string: {
        query: queryText,
        fields: ['name', 'insuredName', 'instigator']
      }
   }
  }
});

Here companyIndex is the alias of the three indices company-events, company-insureds, company-files. This search will only search through the most primary fields across three indices. There fields include:

company index:

  • insuredName
  • instigator

company insureds index:

  • name

company files index:

  • name

In the above code, I just made query fields for the three indices. I want to split across three indices.


Solution

  • There is one way of doing this if you have _index field in your document.

    {
      "query":{
        "bool":{
          "should": [{
            "terms":{
              "_index":["company_insureds"]
            }},
            {
             "term":{
              "name":"nameValue"
            }
          }
          ]
        }
      }
    }
    

    To achieve the things with other fields, you can refer multi-bool clause

    If you don't have _index in you index, there is no way of doing this.