如何在any_match中为JSON数组字段添加字符串模糊匹配以过滤行?
解决方案
要实现模糊匹配(判断test字段值包含a或d),可以将原代码的精确匹配逻辑替换为字符串包含判断,以下是适配不同SQL引擎的两种方案:
方案1:使用contains函数(适用于Presto/Trino等)
any_match(col, x -> contains(json_extract_scalar(x, '$.test'), 'a') OR contains(json_extract_scalar(x, '$.test'), 'd'))
方案2:使用LIKE通配符(适用于Hive、Spark SQL等)
any_match(col, x -> json_extract_scalar(x, '$.test') LIKE '%a%' OR json_extract_scalar(x, '$.test') LIKE '%d%')
逻辑说明
any_match(col, x -> ...):遍历col数组中的每个JSON元素,只要有一个元素满足条件,该行就会被保留json_extract_scalar(x, '$.test'):提取每个JSON对象中test字段的字符串值contains(str, substr)/str LIKE '%substr%':判断提取出的字符串是否包含目标子串a或d
验证结果
用修改后的条件筛选示例数据,会得到期望输出:
id col 1 ["{test: a_b}", "{test: c_d}"] 2 ["{test: c_d}", "{test: e_f}"]
内容的提问来源于stack exchange,提问作者madst
相关产品推荐
相关产品推荐

