Search code examples
elasticsearchelastic-stackdslelasticsearch-5elasticsearch-dsl

Elasticsearch - Merge multiple match phrases


I have the below query, and it's working fine. But my requirement states that I could have multiple phrases which I need to match in the OR condition, Is there any way I can shorten the query.

{
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "primaryTags": {
              "query": "Audience1",
              "boost": 2
            }
          }
        },
        {
          "match_phrase": {
            "secondaryTags": {
              "query": "Audience1",
              "boost": 3
            }
          }
        },
        {
          "match_phrase": {
            "primaryTags": {
              "query": "Audience2",
              "boost": 2
            }
          }
        },
        {
          "match_phrase": {
            "secondaryTags": {
              "query": "Audience2",
              "boost": 3
            }
          }
        }
      ],
      "minimum_should_match": "1",
      "boost": 1
    }
  }
}

I would have to keep adding two match phrases primary and secondary with every new phrase coming in. Is there a way to have all the phrases for primary and secondary in one condition respectively?


Solution

  • You can use multi_match query with type phrase. Try out the below search query:

    {
        "query": {
            "bool": {
                "should": [
                    {
                        "multi_match": {
                            "query": "Audience1",
                            "fields": [
                                "primaryTags^2",
                                "secondaryTags^3"
                            ],
                            "type": "phrase"
                        }
                    },
                    {
                        "multi_match": {
                            "query": "Audience2",
                            "fields": [
                                "primaryTags^2",
                                "secondaryTags^3"
                            ],
                            "type": "phrase"
                        }
                    }
                ]
            }
        }
    }