在Clickhouse中更改数组结构的更快方法

时间:2019-01-04 16:36:29

标签: clickhouse

我想知道下面是否有更快的方法来做我想做的事情-基本上,取消嵌套数组并创建具有不同列的groupArray。

-- create table

CREATE TABLE default.t15 ( product String,  indx Array(UInt8),  col1 String,  col2 Array(UInt8)) ENGINE = Memory ;

--insert values

INSERT into t15 values ('p',[1,2,3],'a',[10,20,30]),('p',[1,2,3],'b',[40,50,60]),('p',[1,2,3],'c',[70,80,90]);

-- select values
    SELECT * from t15;

┌─product─┬─indx────┬─col1─┬─col2───────┐
│ p       │ [1,2,3] │ a    │ [10,20,30] │
│ p       │ [1,2,3] │ b    │ [40,50,60] │
│ p       │ [1,2,3] │ c    │ [70,80,90] │
└─────────┴─────────┴──────┴────────────┘

期望的输出

┌─product─┬─indx_list─┬─col1_arr──────┬─col2_arr───┐
│ p       │         1 │ ['a','b','c'] │ [10,40,70] │
│ p       │         2 │ ['a','b','c'] │ [20,50,80] │
│ p       │         3 │ ['a','b','c'] │ [30,60,90] │
└─────────┴───────────┴───────────────┴────────────┘

我的工作方式-> [对于我需要的东西有点慢]

SELECT   product, 
         indx_list, 
         groupArray(col1)      col1_arr, 
         groupArray(col2_list) col2_arr 
FROM     ( 
                  SELECT   product, 
                           indx_list, 
                           col1, 
                           col2_list 
                  FROM     t15 
                  ARRAY JOIN
                           indx AS indx_list, 
                           col2 AS col2_list 
                  ORDER BY indx_list, 
                           col1
          )x 
GROUP BY product, 
         indx_list;

基本上,我要取消嵌套数组,然后将它们重新分组。 有没有更好,更快的方法来做到这一点。

谢谢!

2 个答案:

答案 0 :(得分:1)

如果要使其更快,可以避免使用subselect和其中的全局ORDER BY。像这样:

SELECT 
    product, 
    indx_list, 
    groupArray(col1) AS col1_arr, 
    groupArray(col2_list) AS col2_arr
FROM t15 
ARRAY JOIN 
    indx AS indx_list, 
    col2 AS col2_list
GROUP BY 
    product, 
    indx_list

如果需要对数组进行排序,通常最好使用 arraySort 在每个组中对其进行排序。

答案 1 :(得分:0)

我将使查询变得简单一些,以将数组连接的数量减少到一个,这可能会提高性能:

SELECT
    product,
    index as indx_list,
    groupArray(col1) as col1_arr,
    groupArray(element) as col2_arr
FROM
(
    SELECT
        product,
        arrayJoin(indx) AS index,
        col1,
        col2[index] AS element
    FROM default.t15
)
GROUP BY
    product,
    index;

更改表结构以摆脱任何数组也许很有意义。我建议采用平面模式:

CREATE TABLE default.t15 ( 
  product String,  
  valueId UInt8,  /* indx */
  col1 String, /* col1 */
  value UInt8) /* col2 */
  ENGINE = Memory ;
相关问题