Skip to content Skip to sidebar Skip to footer

Identify Which Query Matched In Bool Query Elasticsearch

I'm querying my elasticsearch index with a bool query. The query itself has a structure similar to this { 'query': { 'bool': { 'sho

Solution 1:

You can use named queries and then in the results you'll get the name of the query that matched.

{
        "query": {
            "bool": {
                "should": [
                    {"multi_match": {
                        "fields": ["field1", "field2"],
                        "query": self.cleaned_stemmed_phrase,
                        "type": "phrase",
                        "fuzziness":"AUTO",
   add name --->"_name": "query1"
                                    }},
                    {"multi_match": {
                        "fields": ["field3"],
                        "query": self.cleaned_stemmed_phrase,
                        "fuzziness":"AUTO",
                        "boost": 4,
   add name --->"_name": "query2"
                                    }},
                    {"multi_match": {
                        "fields": ["field4"],
                        "query": self.cleaned_stemmed_phrase,
                        "fuzziness":"AUTO",
   add name --->"_name": "query3"
                                    }},
                    {"multi_match": {
                        "fields": ["field5", "filed6"],
                        "query": self.spaces_removed,
                        "fuzziness":"AUTO",
   add name --->"_name": "query4"
                                    }},
                    {"multi_match": {
                        "fields": ["field7", "field8"],
                        "query": self.no_space_stems,
                        "fuzziness":"AUTO",
   add name --->"_name": "query5"
                                    }}
                    ]
         }
    }
}

Then in the results you'll get a matched_queries array with the name of the query/ies that matched the document.

"_source": {
    ...
},
"matched_queries": [
    "title_query"
],

Post a Comment for "Identify Which Query Matched In Bool Query Elasticsearch"