【问题标题】:Find exact match phrase in ElasticSearch在 ElasticSearch 中查找完全匹配的短语
【发布时间】:2015-07-29 11:28:14
【问题描述】:

所以我有以下 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 小时等)。这可以实现吗?

【问题讨论】:

  • specs.battery 是否定义为“not_analyzed”?

标签: elasticsearch


【解决方案1】:

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

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

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 hours and something else”,该文档仍将被匹配,因此这不像“not_analyzed”字段那样精确。

关于上一个主题的更多详细信息:

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

【讨论】: