clickhouse处理jsonArray类型字符串

最近在处理一些clickhouse数据,其实感觉和mysql大差不差,但有几点遇到的问题记录一下。

一、准备工作

  1. 新建表
    create table product(
    	_id                          String,
    	productInfo                  String,
    	dt                           Date
    ) engine = ReplacingMergeTree PARTITION BY dt
      PRIMARY KEY (_id, dt)
      ORDER BY (_id, dt)
      SETTINGS index_granularity = 8192;
    
    注:productInfo字段类型为必填!
  2. 添加数据
 INSERT INTO product (_id,productInfo,dt) VALUES
 ('1','[{''productCode'': ''1'', ''productName'': ''羽绒服''}, {''productCode'': ''2'', ''productName'': ''棉袄''}, {''productCode'': ''3'', ''productName'': ''牛仔裤''}, {''productCode'': ''4'', ''productName'': ''衬衣''}, {''productCode'': ''5'', ''productName'': ''帽子''}]','2023-11-12'),
 ('1','[{''productCode'': ''2'', ''productName'': ''棉袄''}, {''productCode'': ''3'', ''productName'': ''牛仔裤''}, {''productCode'': ''4'', ''productName'': ''衬衣''}, {''productCode'': ''5'', ''productName'': ''帽子''}]','2023-11-13'),
 ('2','[{''productCode'': ''1'', ''productName'': ''羽绒服''}, {''productCode'': ''2'', ''productName'': ''棉袄''}, {''productCode'': ''3'', ''productName'': ''牛仔裤''}, {''productCode'': ''5'', ''productName'': ''帽子''}]','2023-11-13'),
 ('3','[{''productCode'': ''2'', ''productName'': ''棉袄''}, {''productCode'': ''4'', ''productName'': ''衬衣''}, {''productCode'': ''5'', ''productName'': ''帽子''}]','2023-11-13'),
 ('4','[{''productCode'': ''3'', ''productName'': ''牛仔裤''}, {''productCode'': ''4'', ''productName'': ''衬衣''}, {''productCode'': ''5'', ''productName'': ''帽子''}]','2023-11-13'),
 ('5','[{''productCode'': ''1'', ''productName'': ''羽绒服''}, {''productCode'': ''5'', ''productName'': ''帽子''}]','2023-11-13');

二、数据去重

使用argMax()函数

select
	_id,
	argMax(productInfo, dt),
	Max(dt)
from
	product
group by _id
order by _id;

返回结果:
在这里插入图片描述
可以看到结果是取得dt最新4条数据。

三、处理JSONArray字符串

此时我们想要查询结果中包含商品编号为1或3的数据,sql如下:

select 
	_id,
	productInfo,
    replace(productInfo, '\'', '\"') as new,
    JSONExtractArrayRaw(new) as arr,
    arrayJoin(arr) as json,
    visitParamExtractString(json, 'productCode') as productCode,
    dt
from product
where productCode  in ('1', '3');

通过这一系列操作可以得到包含商品编号为1,3的数据为(1,2,4,5)
在这里插入图片描述
再结合上述去重代码

select
	_id,
	argMax(productInfo, dt),
	MAX(dt) 
from
	product
	where visitParamExtractString(arrayJoin(JSONExtractArrayRaw(replace(productInfo, '\'', '\"'))), 'productCode') in ('1', '3')
group by _id
order by _id;

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开始摆烂ing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值