所以我有以下 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
值中具有 2
或 hours
的所有文档。我如何修改此查询,以便它只返回在 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/