首页 > 解决方案 > 分布式引擎上的 TopK 函数在 clickhouse 中仅返回 10 条记录

问题描述

我正在运行以下查询 select topK(30)(Country) from distributed_table

注意:distributed_table 的引擎是分布式的。

即使有超过 100 个可能的“国家”值,查询也只返回 10 个。

此外,当我在 local table 上运行它时,我得到了 10 多个结果。

我错过了一些关键的配置吗?

标签: olapclickhouse

解决方案


当分片的中间结果与最终结果相结合时,似乎会出现问题。

让我们检查每个分片的结果(将使用Distributed_group_by_no_merge -setting 来禁用合并每个分片的中间结果):

select any(_shard_num), topK(30)(Country) 
from distributed_table
SETTINGS distributed_group_by_no_merge = 1

在每个分片上,topK函数都可以正常工作,因此作为一种解决方法,您可以手动组合所有中间结果:

SELECT arrayDistinct(
  arrayMap(x -> x.1, 
    /* sort values by frequency */
    arraySort(x -> x.2, 
      /* converts an array of arrays to a flat array */
      flatten(
        /* group results from shards to one array */
        groupArray(
          /* assign each value the index number */
          arrayMap((x, index) -> (x, index), shard_result, arrayEnumerate(shard_result))))))) ordered_value
FROM (
  select topK(30)(Country) AS shard_result
  from distributed_table
  SETTINGS distributed_group_by_no_merge = 1)

推荐阅读