Elasticsearch filter context 的实践案例

知识背景
在 ES 查询优化的建议里,很多时候为了避免算分逻辑和利用缓存逻辑,Elastic 会建议大家使用 filter 条件。
filter 的使用条件和原理具体可以参照之前写的博文《Elasticsearch filter context 的使用原理》
这里我们来研究 2 个实用案例,具体的感受一下 filter context 的使用效果。
普通案例
第一个案例,我们选择一个 range date 的条件进行测试环境测试,将其中 must 条件改成 filter 条件,测试 5 次以上,观测其缓存数据。
可以看到 query_cache 的 size/count 始终为 0,也就是并没有利用到缓存。

查询的耗时也维持在 900-1100ms 左右。

再测试 filter 条件
在重复的查询过程中,查询速度有明显的加快。

多次查询之后

查看 query_cache size/count 有明显的使用。

使用误区
那是不是所有的 filter 就会加速呢?再看下面这个查询
must 方法

filter 方法

可以看到 2 个查询条件多次查询后,查询耗时差别不大。
并且都产生了 query cache 的使用。
must 条件

filter 条件

难道这两个查询都成了 filter context 查询?既然 filter context 的判断依据之一是查询条件是否算分,就可以使用 "explain": true 进行进一步分析。
must 方法

filter 方法

可以看到查询方法在 ES 这里做了隐性的转换。这两个查询对应的底层查询方法为 ConstantScore,而 ConstantScore 也是可以被认为是 filter context 的一种。因此这里的 must 查询也达到 filter 查询使用 querycache 的优势。
校验思路

cache 数据
也可以通过简单安装一个 INFINI Console(https://docs.infinilabs.com/console/main/docs/getting-started/install/) 进行图表监控(在监控图表-索引-advance 中)

查询使用的算分方法利用 explain API 判断查询语句是否转换成符合 filter context 的类型,比如是否转换成了 constant score,或者算分规则被消除了,等等
作者:金多安,极限科技搜索运维专家,Elastic 认证专家,搜索客社区日报责任编辑。一直从事与搜索运维相关的工作,日常会去挖掘 ES / Lucene 方向的搜索技术原理,保持搜索相关技术发展的关注。
原文:https://infinilabs.cn/blog/2024/elasticsearch-filter-context-practice/
版权声明: 本文为 InfoQ 作者【极限实验室】的原创文章。
原文链接:【http://xie.infoq.cn/article/455374775f97caab7a077e584】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。
评论