首页 > 解决方案 > 在 Elasticsearch 中,为什么我的查询字符串过度匹配?

问题描述

我插入我的数据如下:

PUT my_index2/doc/1
{
  "key": "party",
  "str_val": "THE TWITTER INC"
}

PUT my_index2/doc/2
{
  "key": "party",
  "str_val": "twitter inc"
}

这个查询:

POST my_index2/_search
{
  "query": {
    "query_string": {
      "default_field": "str_val",
      "query": "*twitter*"
    }
  }
}

正确返回两个结果。如果我将查询稍微更改为:

POST my_index2/_search
{
  "query": {
    "query_string": {
      "default_field": "str_val",
      "query": "*the twitter*"
    }
  }
}

我只期待一个结果,因为*the twitter*应该只匹配“THE TWITTER INC”而不是“twitter inc”。但是会返回两个结果。

为什么我的搜索返回的匹配项太多?

标签: elasticsearch

解决方案


那是因为default_operatorfor query_stringOR. 您始终可以使用explain:true来了解结果是如何返回的。如下所示:

POST my_index2/_search
{
  "query": {
    "query_string": {
      "default_field": "str_val",
      "query": "*the twitter*"
    }
  },
  "explain": true
}

对于您的情况,您需要明确提及AND仅返回两个术语匹配的文档,即theANDtwitter

 POST my_index2/_search
    {
      "query": {
        "query_string": {
          "default_field": "str_val",
          "query": "*the twitter*",
           "default_operator": "AND"
        }
      }
    }

推荐阅读