python-3.x 将字符串添加到数组,而不在Clickhouse表中创建新行

r55awzrz  于 2023-02-20  发布在  Python
关注(0)|答案(1)|浏览(130)

我刚开始学习clickhouse!我使用python和clickhouse_connect库。无法添加新字符串到Array(String)
我尝试创建新的字符串到数组我的代码:

import clickhouse_connect

ch_client = clickhouse_connect.get_client(host=ch_host, user=ch_user, password=ch_pass, database=ch_datebase)
ch_client.command(f'CREATE TABLE IF NOT EXISTS {ch_table} (key String, strings Array(String)) ENGINE MergeTree ORDER BY key')
insert_data = [['123', ['string1']]]
ch_client.insert(ch_table, insert_data, column_names=['key', 'strings'])
insert_data = [['123', ['string2']]]
ch_client.insert(ch_table, insert_data, column_names=['key', 'strings'])

如果已经有这样的键,是否有一种简单的方法可以在列表中插入新行,如果没有这样的键,则创建一个新行?x1c 0d1x

nnsrf1az

nnsrf1az1#

您可以只插入行,然后编写一个查询来获得所需的内容:

SELECT 
    key,
    groupArrayArray(strings)
FROM ch_table
GROUP BY key;

如果可以,您可以通过以下查询创建实体化视图:

CREATE MATERIALIZED VIEW ch_table_view
ENGINE = AggregatingMergeTree
ORDER BY key
POPULATE AS
     SELECT 
        key,
        groupArrayArrayState(strings) AS strings_merged
    FROM ch_table
    GROUP BY key;

注意这里使用了-State聚合组合子,它保存了字符串数组的“运行总数”,要读取这一列,需要使用相应的-Merge组合子:

SELECT
    key,
    groupArrayArrayMerge(strings_merged)
FROM ch_table_view 
GROUP BY key;

相关问题