Search code examples
elasticsearch

elastic search, apply specific filter on multiple index search


Let's say I have this query that applies over multiple indexes:

POST index1,index2/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "company": {
              "value": "ORGUNITID",
              "boost": 1
            }
          }
        }
      ],
      "should": [
        {
          "match_phrase_prefix": {
            "name": {
              "query": "es"
            }
          }
        },
        {
          "match_phrase_prefix": {
            "synonyms": {
              "query": "es"
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "minimum_should_match": "1",
      "boost": 1
    }
  }
}

Now I wish to add 2 things:

  1. specify the 1st should query for index1 and and 2nd should query for index2. Even if I can't do this, query will still work so it's not that trouble
  2. specify the index for the filter term. In this case, this is very important, otherwise query won't work for the other index

Can I do that ?


Solution

  • For the thing number 1, you can add additional term searches for the _index field. I don't understand what you want for 2, please clarify your question.

    POST index1,index2/_search
    {
      "query": {
        "bool": {
          "filter": [
            {
              "term": {
                "company": {
                  "value": "MT-COMPANY-FRANCE-ORGUNITID",
                  "boost": 1
                }
              }
            }
          ],
          "should": [
            {
              "bool": {
                "must": [
                  {
                    "term": {
                      "_index": {
                        "value": "index1"
                      }
                    }
                  },
                  {
                    "match_phrase_prefix": {
                      "name": {
                        "query": "es"
                      }
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "must": [
                  {
                    "term": {
                      "_index": {
                        "value": "index2"
                      }
                    }
                  },
                  {
                    "match_phrase_prefix": {
                      "synonyms": {
                        "query": "es"
                      }
                    }
                  }
                ]
              }
            }
          ],
          "adjust_pure_negative": true,
          "minimum_should_match": "1",
          "boost": 1
        }
      }
    }