es如何像sql那样使用like查询,即要查询包含某个词,但搜索只是这个词的一部分

先删除my_index,再初始化mapping:

{
    "mappings": {
        "address": {
            "properties": {
                "postcode": {
                    "type":  "keyword"
                }
            }
        }
    }
}

索引一些文档:

PUT /my_index/address/1
{ "postcode": "W1V 3DG" }

PUT /my_index/address/2
{ "postcode": "W2F 8HW" }

PUT /my_index/address/3
{ "postcode": "W1F 7HW" }

PUT /my_index/address/4
{ "postcode": "WC1N 1LZ" }

PUT /my_index/address/5
{ "postcode": "SW5 0BE" }

prefix 前缀查询

查询关键词不需要是完整的:

elasticsearch先实践再理论 五 部分匹配

prefix是如何查询的呢?倒排索引的词项是排序的,es先找到第一个w1开头的词项,顺序查找知道开头不是w1.

通配符查找

使用wildcard,?代表一个任意字符,*代表一个或多个字符:

 

elasticsearch先实践再理论 五 部分匹配

也可以使用正则查询:

{
    "query": {
        "regexp": {
            "postcode": "W[0-9].+" 
        }
    }
}

 为避免扫描所有词项,不要使用*anyword这种,和sql类似,like不要使用%anyword

另外,若查询的字段是text(非keyword),那么很有可能查询不到,比方说包含 “Quick brown fox” (快速的棕色狐狸)的 title 字段会生成词: quick 、 brown 和 fox 。

下面两个查询时查不到结果的

{ "regexp": { "title": "Qu.*" }} 
{ "regexp": { "title": "quick br*" }}

 

输入即搜索

 

相关文章:

  • 2022-12-23
  • 2021-12-16
  • 2022-02-07
  • 2022-12-23
  • 2021-09-08
  • 2021-06-29
  • 2021-11-09
  • 2022-01-03
猜你喜欢
  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
  • 2021-11-24
  • 2021-11-26
相关资源
相似解决方案