首页 > 解决方案 > 在elasticsearch中搜索字符串数组中的确切字段

问题描述

弹性搜索版本:7.1.1

嗨,我尝试了很多,但在我的索引中找不到任何解决方案,我有一个包含字符串的字段。

因此,例如,我有两个文档在位置数组中包含不同的值。

文件 1:

"doc" : {
            "locations" : [
              "Cloppenburg",
              "Berlin"
           ]
       }

文件 2:

"doc" : {
                "locations" : [
                  "Landkreis Cloppenburg",
                  "Berlin"
                ]
              }

用户请求搜索术语Cloppenburg 并且我只想返回那些包含术语Cloppenburg 而不是Landkreis Cloppenburg的文档。结果应仅包含Document-1。但我的查询返回两个文件。

我正在使用以下查询并取回两个文档。有人可以帮我解决这个问题。

GET /my_index/_search
     {
        "query": {
            "bool": {
                "must": [
                    {
                        "match": {
                            "doc.locations": {
                                "query": "cloppenburg",
                                "operator": "and"
                            }
                        }
                    }
                ]
            }
        }
    }

标签: arrayselasticsearchtext

解决方案


问题是由于您正在使用该text字段和match查询。

匹配查询被分析并使用在索引时使用的相同搜索词分析器,这是字段情况下的标准分析器。text在您的情况下,它会在空格上打断文本,这Landkreis Cloppenburg将创建两个标记landkreis以及cloppenburg索引和搜索时间,甚至cloppenburg会匹配文档。

解决方案:使用keyword field.

索引定义

{
    "mappings": {
        "properties": {
            "location": {
                "type": "keyword"
            }
        }
    }
}

索引您的两个文档,然后使用相同的搜索查询

{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "location": {
                            "query": "Cloppenburg"
                        }
                    }
                }
            ]
        }
    }

}

结果

 "hits": [
            {
                "_index": "location",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.6931471,
                "_source": {
                    "location": "Cloppenburg"
                }
            }
        ]

推荐阅读