elasticsearch - 在 ElasticSearch 中查找完全匹配的短语

标签 elasticsearch

所以我有以下 ElasticSearch 查询:

"query": {
"bool": {
  "must": [
    {
      "nested": {
        "path": "specs",
        "query": {
          "bool": {
            "must": [
              {
                "match": {
                  "specs.battery": "2 hours"
                }
              }
            ],
            "minimum_should_match": 1
          }
        }
      }
    },
    {
      "terms": {
        "category_ids": [
          16405
        ]
      }
    }
  ]
}
}

目前,它返回在 specs.battery 值中具有 2hours 的所有文档。我如何修改此查询,以便它只返回在 specs.battery 字段中具有精确短语 2 hours 的文档?另外,我希望能够拥有多个短语(2 小时、2 小时、3 小时等)。这可以实现吗?

最佳答案

当您索引时,elasticsearch 中的数据默认被标记化。这意味着对表达式“2 小时”进行索引的结果将是映射到同一文档的 2 个标记。 但是,不会有一个 token “2 小时”,因此,如果您使用过滤查询,它将搜索 2 或小时,甚至找不到它。

要让 Elasticseach 将“2 小时”视为一个表达式,您需要在映射中将 specs.battery 定义为 not_analyze,如下所示:

curl -XPOST localhost:9200/your_index -d '{
    "mappings" : {
        "your_index_type" : {
            "properties" : {
                ...
                "battery" : { "type" : "string", "index":"not_analyzed" }
                ...
            }
        }
    }
}'

然后您可以使用过滤后的查询进行精确匹配,如下所示:

curl -XGET 'http://localhost:9200/_all/_search?pretty=true' -d '
{
    "query": {
        "filtered" : {
            "filter" : {        
                "term": {
                    "battery": "2 hours"
        }
       }
     }
    }
}'

然后您将获得完全匹配。

更多详情请访问:https://www.elastic.co/guide/en/elasticsearch/guide/current/_finding_exact_values.html

另一方面,如果您绝对需要分析您的字段或使用无法更改的现有索引,您仍然可以通过使用运算符“and”来解决问题,如下所示:

curl -XGET localhost:9200/your_index'  -d '
{
    "query": {
        "match": {
           "battery": {
            "query": "2 hours",
            "operator": "and"
        }
    }
  }
}'

在最后一个选项中,您可能已经了解,如果您有一个包含“2 小时和其他内容”的文档,该文档仍将被匹配,因此这不如“not_analyzed”字段那么精确。

有关最后一个主题的更多详细信息,请访问:

https://www.elastic.co/guide/en/elasticsearch/guide/current/match-multi-word.html

关于elasticsearch - 在 ElasticSearch 中查找完全匹配的短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31699178/

相关文章:

elasticsearch - 部分更新ElasticSearch索引中的嵌套记录

elasticsearch - 如何在 Elasticsearch 索引中检索所有文档(大小大于 10000)

c# - ElasticSearch简单示例不起作用C#

elasticsearch - Elasticsearch 中的 PIT 成本如何?

elasticsearch - 无法建立新连接,Docker-Compose Django + Haystack + Mysql + ElasticSearch

c# - 无法从Elasticsearch获取带有NEST的任何文档

python - 加快读取python中的url响应

elasticsearch - 将DSL查询转换为NEST查询

search - Elasticsearch 从搜索的响应正文中删除默认字段

elasticsearch - Elasticsearch 错误-[前缀]查询不支持[前缀]