3
votes

I am using fuzzy and want elasticsearch to return the searched word not just the hit. When i am searching for the word dogo and my fuzzy search finds the word dog i want to know that it was dogo who found it.

data:

{ "index": { "_id":1 }}
{ "title": "The quick brown fox", "price":5 }
{ "index": { "_id":2 }}
{ "title": "The quick blue dog", "price":7 }
{ "index": { "_id":3 }}
{ "title": "The slow brown dog", "price":5 }

query:

{
  "query": {
    "bool": {
    "should": [
        {
          "fuzzy": {
                  "title": "dogo"
                      }

          },
        {
          "fuzzy": {
                  "title": "fox"
                      }
          }
        ]
    }

  },
  "highlight" : {
      "fields" : {
          "title":{
              "pre_tags": [
                "===>"
              ],
              "post_tags": [
                "<==="
              ],
              "fragment_size": 200,
              "number_of_fragments": 100
          }
      }
   }  
}

This query will return ===>dog<=== but don't know if dogo found it.

Does anyone know how to do this or an idea? I want my output to be something like dog : dogo.

2

2 Answers

5
votes

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. dogo and fox below).

{
  "query": {
    "bool": {
      "should": [
        {
          "fuzzy": {
            "name": {
              "value": "dogo",
              "_name": "dogo"
            }
          }
        },
        {
          "fuzzy": {
            "name": {
              "value": "fox",
              "_name": "fox"
            }
          }
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "title": {
        "pre_tags": [
          "===>"
        ],
        "post_tags": [
          "<==="
        ],
        "fragment_size": 200,
        "number_of_fragments": 100
      }
    }
  }
}
1
votes

Named queries is the right choice to understand your query name in results. You could also try suggestion if you want to know the possible corrected terms for your query term.

{
  "query": {
    "bool": {
    "should": [
        {
          "fuzzy": {
                  "title": "dogo"
                      }

          },
        {
          "fuzzy": {
                  "title": "fox"
                      }
          }
        ]
    }

  },
  "highlight" : {
      "fields" : {
          "title":{
              "pre_tags": [
                "===>"
              ],
              "post_tags": [
                "<==="
              ],
              "fragment_size": 200,
              "number_of_fragments": 100
          }
      }
   }  ,
 "suggest" : {
    "title_suggestion" : {
      "text" : "fox dogo",
      "term" : {
        "field" : "title"
      }
    }
  }
}