Elasticsearch:在数组中查找完全匹配 [英] Elasticsearch: find exact match in array

查看:55
本文介绍了Elasticsearch:在数组中查找完全匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文件:

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

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

How can I search for "xxx" if I would like to retrieve only the first document?

我尝试过:

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

但是它与两个文档一起返回.

But it returned with both documents.

推荐答案

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

Your basic problem is, you haven't defined an explicit mapping, so the default mapping will come into play. Assuming you are working on the latest version 5 or 6.

在标签字段中搜索的是经过分析的文本,因此它将为 xxx yyy 创建与您的搜索也匹配的令牌 xxx yyy

Searching in the tags field is analyzed text, thus it will create for xxx yyythe tokens xxxand yyywhich matches also your search.

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

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

You could query for the multi-field tags.keyword that will give you an exact match (field value is not analyzed). For instance:

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

或者另一种可能性,并且从一开始就直接使用关键字类型.标签通常倾向于是 keyword 类型或未经分析.

Or another possibility, and doing it right from the start, use the keyword type only. tags tend in general to be of type keyword or not analyzed.

定义映射

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"
  ]
}

使用上面的映射,您可以搜索标签.

Using the above mapping, you can search for tags then.

这篇关于Elasticsearch:在数组中查找完全匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆