ElasticSearch 搜索查询不区分大小写

ElasticSearch Search query is not case sensitive

我正在尝试搜索查询,它可以很好地进行精确搜索,但是如果用户输入小写或大写,它就不起作用,因为 ElasticSearch 不区分大小写。

例子

{
    "query" : {
        "bool" : { 
            "should" : {
                "match_all" : {} 
            },
            "filter" : {
                "term" : { 
                    "city" : "pune"
                }
            }
        }
    }
}

当城市正好是 "pune" 时它工作正常,如果我们将文本更改为 "PUNE" 它不起作用。

Elasticsearch 将分析文本字段小写,除非您定义自定义映射。

Exact values (like numbers, dates, and keywords) have the exact value specified in the field added to the inverted index in order to make them searchable.

However, text fields are analyzed. This means that their values are first passed through an analyzer to produce a list of terms, which are then added to the inverted index. There are many ways to analyze text: the default standard analyzer drops most punctuation, breaks up text into individual words, and lower cases them.

参见:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html

所以如果你想用term查询 —— analyze the term在查询前自己使用。或者在这种情况下将术语小写。

ElasticSearch is case insensitive.

"Elasticsearch" 不区分大小写。 JSON 字符串 属性 将被映射为 text datatype by default (with a keyword datatype sub or multi field,稍后我将对此进行解释。

text 数据类型具有与之关联的分析概念;在索引时间,字符串输入通过 an analysis chain, and the resulting terms are stored in an inverted index data structure for fast full-text search. With a text datatype where you haven't specified an analyzer, the default analyzer will be used, which is the Standard Analyzer. One of the components of the Standard Analyzer is the Lowercase token filter 馈送,它会小写标记 (terms).

当谈到通过搜索 API 查询 Elasticsearch 时,有许多不同类型的查询可供使用,几乎可以满足任何用例。 matchmulti_match 查询等一类查询是全文查询。这些类型的查询在搜索时对查询输入进行分析,并将生成的术语与存储在倒排索引中的术语进行比较。默认使用的分析器也将是标准分析器。

另一系列查询,例如 termtermsprefix 查询,是术语级查询。这些类型的查询不分析查询输入,因此将按原样将查询输入与存储在倒排索引中的术语进行比较。

在您的示例中,您对 "city" 字段的 term 查询在大写时未找到任何匹配项,因为它搜索的是 text 字段,其输入在索引时进行了分析。使用默认映射,这是 keyword sub 字段可以提供帮助的地方。 keyword 数据类型不进行分析(好吧,它具有 normalizers 的分析类型),因此可用于 精确 匹配以及排序和聚合。要使用它,您只需要定位 "city.keyword" 字段。另一种方法也可以是将 "city" 字段使用的分析器更改为不使用小写标记过滤器的分析器;采用这种方法需要您重新索引索引中的所有文档。

为了解决这个问题,我创建了自定义规范化和更新映射以添加,

在我们必须删除索引并重新添加之前

先删除索引

删除放置 http://localhost:9200/users

现在重新创建索引

放置http://localhost:9200/users

{
  "settings": {
    "analysis": {
      "normalizer": {
        "lowercase_normalizer": {
          "type": "custom",
          "char_filter": [],
          "filter": ["lowercase", "asciifolding"]
        }
      }
    }
  },
  "mappings": {
    "user": {
      "properties": {
        "city": {
          "type": "keyword",
          "normalizer": "lowercase_normalizer"
        }
      }
    }
  }
}