Elasticsearch “match_phrase” query and “fuzzy” query - can both be used in conjunction

↘锁芯ラ 提交于 2019-12-25 00:05:46

问题


I need a query using match_phrase along with fuzzy matching. However I'm not able to find any documentation to construct such a query. Also, when I try combining the queries(one within another), it throws errors. Is it possible to construct such a query?


回答1:


You would need to make use of Span Queries.

The below query would perform phrase match+fuzzy query for champions league say for e.g. on a sample field name which is of type text

If you'd want multiple fields, then add another must clause.

Notice I've mentioned slop:0 and in_order:true which would do exact phrase match, while you achieve fuzzy behaviour using fuzzy queries inside match query.

Sample Documents

POST span-index/mydocs/1
{
  "name": "chmpions leage"
}

POST span-index/mydocs/2
{
  "name": "champions league"
}

POST span-index/mydocs/3
{
  "name": "chompions leugue"
}

Span Query:

POST span-index/_search
{  
   "query":{  
      "bool":{  
         "must":[  
            {  
               "span_near":{  
                  "clauses":[  
                     {  
                        "span_multi":{  
                           "match":{  
                              "fuzzy":{  
                                 "testField":"champions"
                              }
                           }
                        }
                     },
                     {  
                        "span_multi":{  
                           "match":{  
                              "fuzzy":{  
                                 "testField":"league"
                              }
                           }
                        }
                     }
                  ],
                  "slop":0,
                  "in_order":true
               }
            }
         ]
      }
   }
}

Response:

{
  "took": 19,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 3,
    "max_score": 0.5753642,
    "hits": [
      {
        "_index": "span-index",
        "_type": "mydocs",
        "_id": "2",
        "_score": 0.5753642,
        "_source": {
          "name": "champions league"
        }
      },
      {
        "_index": "span-index",
        "_type": "mydocs",
        "_id": "1",
        "_score": 0.5753642,
        "_source": {
          "name": "chmpions leage"
        }
      },
      {
        "_index": "span-index",
        "_type": "mydocs",
        "_id": "3",
        "_score": 0.5753642,
        "_source": {
          "name": "chompions leugue"
        }
      }
    ]
  }
}

Let me know if this helps!



来源:https://stackoverflow.com/questions/53541053/elasticsearch-match-phrase-query-and-fuzzy-query-can-both-be-used-in-conju

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!