Elasticsearch 查询没有给出完全匹配

Elasticsearch query not giving exact match

我正在使用以下匹配查询搜索 elasticsearch,它没有给我精确匹配,而是还提供了一些更不相关的匹配。

我正在使用 elasticsearch 6.2.3

请在下面找到我的查询

get items/_search
{
   "query" : {
      "match" : {
         "code" : "7000-8900"
      }
   }
}

请查找正在从 match 查询

中获得的响应
7000-8900
7000-8002-WK
7000-8002-W

您必须使用 term 查询而不是 match,如文档所述:

The term query finds documents that contain the exact term specified in the inverted index

因此您必须按如下方式更改您的查询:

get items/_search
{
   "query" : {
      "term" : {
         "code.keyword" : "7000-8900"
      }
   }
}

如果没有得到任何结果,有两种可能:

  • 搜索到的字词与您想象的不一样(例如未修剪)
  • 索引没有显式映射,自动映射未将字段代码识别为字符串。

注意:如果映射正确且代码是术语字段,则可以使用 "code"。如果映射是自动的并且映射将其识别为文本,则您需要使用 "code.keyword"

你可以试试这个method.This查询return精确匹配记录。

import json
from elasticsearch import Elasticsearch

es = Elasticsearch('http://localhost:9200')
res = es.search(index="test_index", doc_type="test_doc", body=json.dumps({"query": {"match_phrase": {"name": "Jhon"}}})))

我在比赛中遇到了同样的问题,所以我尝试使用术语。但这是一种不好的做法。 ES 说,我们不应该使用 term 来进行字符串匹配。

如果您将字段指定为关键字,则匹配无论如何都会进行完全匹配。

如果您还没有将字段定义为关键字,您仍然可以这样查询:

get items/_search
{
   "query" : {
      "match" : {
         "code.keyword" : "7000-8900"
      }
   }
}