首页 > 解决方案 > Elasticsearch:在数组中找到完全匹配

问题描述

我有以下文件:

{
    ...
    _source: {
        id: 1, 
        tags: [
            "xxx"
        ]
    }
},
{
     ...
     _source: {
         id: 2, 
         tags: [
             "xxx yyy"
         ]
     }
}

"xxx"如果我只想检索第一个文档,我该如何搜索?

我试过这个:

"query" : {
    "filter" : {
        "term" : { 
           "tags" : "xxx"
        }
    }
}

但它与两份文件一起返回。

标签: elasticsearch

解决方案


您的基本问题是,您尚未定义显式映射,因此默认映射将发挥作用。假设您正在使用最新版本 5 或 6。

在标签字段中搜索是分析文本,因此它将为xxx yyy标记创建xxx并且yyy也与您的搜索匹配。

GET _analyze
{
  "text": "xxx yyy"
}

您可以查询tags.keyword将为您提供完全匹配的多字段(不分析字段值)。例如:

GET _search
{
  "query": {
    "constant_score": {
      "filter": {
        "term": {
          "tags.keyword": "xxx"
        }
      }
    }
  }
}

或者另一种可能性,从一开始就这样做,只使用关键字类型。tags一般倾向于类型keyword或不分析。

定义映射

PUT test
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
  "mappings": {
    "doc": {
      "properties": {
        "tags": {
          "type": "keyword"
        }
      }
    }
  }
}

PUT test/doc/1
{
  "tags": [
    "xxx"
  ]
}
PUT test/doc/2
{
  "tags": [
    "xxx yyy"
  ]
}

使用上面的映射,你可以搜索tagsthen。


推荐阅读