《Elastic Stack 实战手册》——三、产品能力——3.4.入门篇——3.4.2.Elasticsearch基础应用——3.4.2.17.Text analysis, settings 及 mappings——3.4.2.17.3.全文搜索/精确搜索(7) https://developer.aliyun.com/article/1229936
3.7 prefix
Prefix 查询用于对某一字段查询特定开头的词项。
使用方法:
# 创建测试数据 PUT my-index-000001/ { "settings": { "number_of_replicas": 1, "number_of_shards": 1 }, "mappings": { "properties": { "user.id": { "type": "keyword" } } } } PUT my-index-000001/_doc/21 {"user.id":"kind"} PUT my-index-000001/_doc/22 {"user.id":"kimy"} PUT my-index-000001/_doc/23 {"user.id":"ki1212121"} # 进行查询 GET my-index-000001/_search { "query": { "prefix": { "user.id": { "value": "ki" } } } }
这里代表查询 user.id 字段词项符合 ki 开头的文档。
注意:
l 加速查询:可以在创建 mapping 时使用 index_prefixes 参数加速前缀查询。如果启用,
l ES 将索引前缀在 2 到 5 个字符到一个单独的字段。这让 ES 以更大的索引为代价更有效地运行前缀查询。
l 需要打开 search.allow_expensive_queries 设置。
3.8 regexp
Regexp 查询是使用正则表达式进行匹配的查询方式。
关于正则匹配支持的操作,可以见相关详细列表:https://www.elastic.co/guide/en/elasticsearch/reference/7.14/regexp-syntax.html
使用方法:
GET term-query/_search { "query": { "regexp": { "user.id": { "value": "k.*y", "flags": "ALL", "case_insensitive": true, "max_determinized_states": 10000, } } } }
以上查询代表使用正则表达式 "k.*y" 去匹配相关符合条件的文档。
相关参数:
l flags:为正则表达式启用可选操作符。
l case_insensitive:当设置为 true 时,允许正则表达式值与索引字段值进行不区分大小写的匹配。默认值为 false,这意味着匹配的大小写敏感性取决于底层字段的映射。
l max_determinized_states:查询所需的匹配词项的最大数目。默认是 10000。 ES 在内部使用 Apache Lucene 解析正则表达式。 Lucene 将每个正则表达式转换为包含若干确定状态的有限词项。可以使用此参数防止转换无意中消耗过多资源。为了运行复杂的正则表达式,需要增加这个限制。
3.9 ids Ids 查询是直接查询 _id 字段的一种较为便捷的查询方式。 使用方法:
GET /_search { "query": { "ids" : { "values" : ["1", "4", "100"] } } }
3.10 exists
Exists 查询用于查询一个字段内容是否为空,若不为空则返回。Exists 可以与 must_not 布尔查询一起使用查找字段没有值的文档。
由于下列原因,文档字段值可能不存在:
1、源 JSON 中的字段为 null 或 []
2、该字段在mapping中有 "index":false 设置
3、字段值的长度超过了映射中的 ignore_above 设置
4、该字段值是畸形的,并且在 mapping 中定义了 ignore_malformed
使用方法:
GET term-query/_search { "query": { "exists": { "field": "user.id" } } }
注意:当出现下列情况时,字段还是存在的:
1、空字符串,如" "或"-"
2、包含 null 和另一个值的数组,例如 [ null, "foo"]
3、在字段 mapping 中定义的自定义空值
《Elastic Stack 实战手册》——三、产品能力——3.4.入门篇——3.4.2.Elasticsearch基础应用——3.4.2.17.Text analysis, settings 及 mappings——3.4.2.17.3.全文搜索/精确搜索(9) https://developer.aliyun.com/article/1229932