弹性搜索如何使query_string匹配精确短语

时间:2019-04-12 07:32:20

标签: elasticsearch

我需要query_string仅在完全相同时才匹配。

根据弹性documentation  在查询字符串查询:

不将空格视为运算符,这意味着纽约市将“按原样”传递给为该字段配置的分析器。如果该字段是关键字字段,则分析器将创建一个术语纽约市,查询构建器将在查询中使用该术语。如果您要分别查询每个术语,则需要在这些术语周围添加显式运算符(例如new AND york AND city)。

我创建了一个索引 testingindex 并添加了随机数据:

  • banna af
  • cd测试af
  • 测试CD
  • af电视
  • 测试ab

帖子:

POST testingindex/_doc/5
{
  "name":"banna af" 
}

搜索:

GET testingindex/_search?explain
{
  "size": 10,
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fuzziness": 0, 
            "phrase_slop": 0, 
            "default_operator": "OR", 
            "minimum_should_match": "99%", 
            "fields": [
              "name"
            ],
            "query":"(testing af) OR (banna af)"
          }
        }
      ]
    }
  }
}

结果:

"hits" : [
      {
        "_index" : "testingindex",
        "_type" : "_doc",
        "_id" : "6",
        "_score" : 2.0794415,
        "_source" : {
          "name" : "banna af"
        }
      },
      {
        "_index" : "testingindex",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : 0.8630463,
        "_source" : {
          "name" : "cd testing af"
        }
      },
      {
        "_index" : "testingindex",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 0.6931472,
        "_source" : {
          "name" : "testing cd"
        }
      },
      {
        "_index" : "testingindex",
        "_type" : "_doc",
        "_id" : "5",
        "_score" : 0.5753642,
        "_source" : {
          "name" : "af television"
        }
      },
      {
        "_index" : "testingindex",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.2876821,
        "_source" : {
          "name" : "testing ab"
        }
      }
    ]

如果我将运算符更改为:

"default_operator": "AND",

我得到正确的结果。

但是如果我将查询更改为:

    "query":"(testing af) OR (banna af) OR (badfadfaf)"

我没有结果,我仍然需要返回匹配的结果。

如何让 cd测试af banna af 成为返回的唯一结果?

1 个答案:

答案 0 :(得分:0)

只需将术语本身用双引号引起来(必须转义)即可完全匹配,然后删除minimum_should_match属性-简化的查询如下所示:

GET testingindex/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fields": [
              "name"
            ],
            "query":"(\"testing af\") OR (\"banna af\") OR (\"badfadfaf\")"
          }
        }
      ]
    }
  }
}

屈服:

"hits" : {
    "total" : 2,
    "max_score" : 1.3862944,
    "hits" : [
      {
        "_index" : "testingindex",
        "_type" : "_doc",
        "_id" : "qmD-EWoBqkB-aMRpwfuE",
        "_score" : 1.3862944,
        "_source" : {
          "name" : "banna af"
        }
      },
      {
        "_index" : "testingindex",
        "_type" : "_doc",
        "_id" : "q2D_EWoBqkB-aMRpFPtX",
        "_score" : 0.5753642,
        "_source" : {
          "name" : "cd testing af"
        }
      }
    ]
  }