如何在弹性搜索中使用标准分析器搜索文本

How to search on Text with Standard Analyser in Elastic Search

我在 ES 映射中有一个索引为文本的键值对。

{key:myKey, value:MY_VALUE}

无论我做什么,当我尝试查询值时,让它成为术语、匹配、它在 ES 中没有命中的术语

因此:MY_VALUE 将转换为 [my, value]

的条款

如果您使用 match query 而不做任何修改,那么它会使用与索引字段相同的分析器,即为您的搜索词生成相同类型的标记,并且应该为您提供搜索结果。

根据 Elasticsearch 匹配查询文档:

The provided text is analyzed before matching.

The match query is the standard query for performing a full-text search

由于您没有提供任何样本,让我用我的样本数据展示一下:

索引定义

{
  "mappings" :{
    "properties" :{
        "title" :{
            "type" : "text" --> default standard analyzer would be used.
        }
    }
  }
}

索引示例文档

{
    "title": "foo bar"
}

{
    "title": "hello world"
}

搜索 foo

{
    "query" :{
        "match" :{
            "title" :"foo"
        }
    }
}

结果

 "hits": [
            {
                "_index": "standard",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.4700036,
                "_source": {
                    "title": "foo bar"
                }
            }
        ]

搜索 foo 栏

{
    "query" :{
        "match" :{
            "title" :"foo bar"
        }
    }
}

结果

"hits": [
            {
                "_index": "standard",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.9400072,
                "_source": {
                    "title": "foo bar"
                }
            }
        ]

注意:搜索 foofoo bar 都匹配为标准标记,将标记拆分为空格,您可以使用 analyze API 进行检查,如下所示:

{
  "text" : "foo bar",
  "analyzer" : "standard"
}

{
    "tokens": [
        {
            "token": "foo",
            "start_offset": 0,
            "end_offset": 3,
            "type": "<ALPHANUM>",
            "position": 0
        },
        {
            "token": "bar",
            "start_offset": 4,
            "end_offset": 7,
            "type": "<ALPHANUM>",
            "position": 1
        }
    ]
}

编辑:基于 OP(@AKASH GUPTA) 的评论

现在Elastic为text field提供了一个默认的keyword field,但是那只是针对动态映射的,而不是针对静态映射的,而且在最新版本中也是如此。请参考this 博客 post 如果您使用的是静态映射,则可以定义自己对应的 keyword 字段。

移动评论回答:"It seems Elastic Search by default provides keyword for text fields. In this case it can be used as "title.keyword".

参考:https://www.elastic.co/blog/strings-are-dead-long-live-strings (部分:新默认值。)

如果您遇到 "analyzed" 文本问题,并且想要一个未经分析的字符串,您可以将“.keyword”附加到您的密钥。 在此之前检查映射是否存在类似于:

"yourKey": {
     "type": "text",
     "fields": {
           "keyword": {
                "type": "keyword",
                "ignore_above": 256
           }
      }
}

如果它不存在,更新与上面类似的映射。