Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing unmatched word in elasticsearch results

I want to display which words are not matched by a multi-word query for returned documents. Is there a query type, or parameter to achieve this?

Normally, such unmatched words are shown to the users in strikethrough typeface:

Missing word


Example query after I got the answer:

POST /posts/_search
{
   "query": {
      "bool": {
         "should": [
            {"match": {"name": {"query": "jogging rain"}}},
            {"match": {"name": {"query": "jogging", "_name": "jogging"}}},
            {"match": {"name": {"query": "rain", "_name": "rain"}}}
         ]
      }
   }
}

Now if we find a document with the word jogging but not rain, we'd get a result like this:

{
    "_source": {
        "name": "jogging"
    },
    "matched_queries": [
        "jogging"
    ]
}

Then in the next step I subtract the contents of matched_queries, i.e. "jogging" from the initial search, i.e. "jogging rain" and the result: "rain" is what I want.

Thanks @Val for the idea on how to solve this!

like image 641
paweloque Avatar asked Feb 22 '16 14:02

paweloque


1 Answers

You could use named queries for this, by giving a name to each of your queries. In the results, each hit will feature a matched_queries array containing the names of the queries that matched (e.g. unmatched_query and strikethrough_query below). You can then use that info on the client-side to build a strikethrough list of words which didn't match.

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "content": {
              "query": "unmatched",
              "_name": "unmatched_query"
            }
          }
        },
        {
          "match": {
            "content": {
              "query": "strikethrough",
              "_name": "strikethrough_query"
            }
          }
        }
      ]
    }
  }
}
like image 85
Val Avatar answered Sep 24 '22 14:09

Val