能否在Elasticsearch Percolate查询中使用match_phrase_prefix与slop特性?
Elasticsearch Percolate查询与match_phrase_prefix、slop的兼容性
结论:match_phrase_prefix和slop都可以与Elasticsearch的Percolate查询搭配使用
1. match_phrase_prefix在Percolate查询中的用法
Percolate查询的核心是用传入的文档匹配预存在索引中的查询条件,因此你完全可以在预存的查询里使用match_phrase_prefix实现前缀短语匹配。
示例代码:
// 1. 创建包含percolator字段的索引 PUT /my_percolate_index { "mappings": { "properties": { "saved_query": { "type": "percolator" }, "doc_content": { "type": "text" } } } } // 2. 存储一条带match_phrase_prefix的查询到percolator字段 PUT /my_percolate_index/_doc/query_1 { "saved_query": { "match_phrase_prefix": { "doc_content": { "query": "elastic se", "max_expansions": 15 } } } } // 3. 用文档执行Percolate查询,匹配预存的查询 GET /my_percolate_index/_search { "query": { "percolate": { "field": "saved_query", "document": { "doc_content": "Elasticsearch is a distributed search and analytics engine" } } } }
上述查询会成功匹配到query_1,因为文档中的"Elasticsearch"满足"elastic se"的前缀短语匹配规则。
2. slop在Percolate查询中的用法
slop是match_phrase或match_phrase_prefix的参数,用来放宽短语中词的位置限制(允许词序调换或间隔一定数量的词),它同样可以在Percolate预存的查询中使用。
示例1:slop搭配match_phrase
// 存储带slop的match_phrase查询 PUT /my_percolate_index/_doc/query_2 { "saved_query": { "match_phrase": { "doc_content": { "query": "engine distributed", "slop": 3 } } } } // 执行Percolate查询 GET /my_percolate_index/_search { "query": { "percolate": { "field": "saved_query", "document": { "doc_content": "Elasticsearch is a distributed search and analytics engine" } } } }
这里slop=3允许"engine"和"distributed"之间最多间隔3个词,且词序调换,所以能匹配成功。
示例2:slop搭配match_phrase_prefix
// 存储带slop的match_phrase_prefix查询 PUT /my_percolate_index/_doc/query_3 { "saved_query": { "match_phrase_prefix": { "doc_content": { "query": "engine dist", "slop": 3, "max_expansions": 10 } } } }
这个查询同样能匹配上述文档,因为前缀"dist"会匹配"distributed",且slop允许两者的位置间隔。
注意事项
- 必须确保存储查询的字段映射类型为
percolator,否则无法正常使用Percolate功能 slop值不宜设置过大,否则会降低匹配精度,同时增加查询性能开销match_phrase_prefix的max_expansions建议根据实际需求设置,避免过多的前缀扩展导致性能问题
内容的提问来源于stack exchange,提问作者Ans
相关产品推荐
相关产品推荐

