Elasticsearch 7 track_total_hits 如何提高查询速度?

Ben*_*n M 5 internals elasticsearch elasticsearch-7

我最近从 Elasticsearch 6 升级到 7,偶然发现了 10000 次点击限制。

Changelog, Documentation, and I also found a single blog post from a company that tried this new feature and measured their performance gains.

But I'm still not sure how and why this feature works. Or does it only improve performance under special circumstances?

Especially when sorting is involved, I can't get my head around it. Because (at least in my world) when sorting a collection you have to visit every document, and that's exactly what they are trying to avoid according to the Documentation: "Generally the total hit count can’t be computed accurately without visiting all matches, which is costly for queries that match lots of documents."

Hopefully someone can explain how things work under the hood and which important point I am missing.

Val*_*Val 5

至少有两种不同的上下文不需要对所有文档进行排序:

A.配置索引排序时,文档已按排序顺序存储在索引段文件中。因此,每当查询指定与索引预先排序的排序相同的排序时,则只需要访问和返回每个段文件的前 N ​​个文档。所以在这种情况下,如果你只对前 N 个结果感兴趣,而不关心总命中数,你可以简单地设置track_total_hits为 false。这是一个很大的优化,因为不需要访问索引的所有文档。

B. 在过滤上下文中查询时(即bool/filter),因为不会计算分数。索引只是检查与是/否问题匹配的文档,并且该过程通常非常快。由于没有评分,每个分片只返回前 N 个匹配的文档。

如果track_total_hits设置为 false(因为您不关心匹配文档的确切数量),则根本不需要计算文档,因此不需要访问所有文档。

如果track_total_hits设置为 N(因为你只关心是否至少有 N 个匹配的文档),那么每个分片 N 个文档后计数将停止。

相关链接:

  • 您需要了解的是,“track_total_hits”只是非常特定情况下的一种优化。它不是一个可以应用于广泛案例的功能,认为它会加速各种查询。例如,一旦有了聚合,“track_total_hits”就不起作用(仅对点击数有影响),因为无论如何都必须访问所有匹配的文档才能计算聚合 (2认同)