sql - Hive 爆炸并从字符串中提取值
问题描述
伙计们,我正在尝试从配置单元中的字符串(列名:人员)下方提取“状态”的值。问题是,该列既不是完整的 JSON,也不是存储为数组。
我试图通过将 '=' 替换为 ':' 来使其看起来像 JSON,但这没有帮助。
[{name=abc, org=true, self=true, status=accepted, email=abc@gmail.com}, {name=cab abc, org=false, self=false, status=needsAction, email=cab@google.com}]
以下是我使用的查询:
SELECT
str.name,
str.org,
str.status
FROM table
LATERAL VIEW EXPLODE (TRANSLATE(people,'=',':')) exploded as str;
但我得到以下错误:
FAILED: UDFArgumentException explode() takes an array or a map as a parameter
需要这样的输出:
name | org | status
-------- ------- ------------
abc | true | accepted
cab abc | false | needsAction
注意:已经有一个表,数据类型是字符串,我无法更改表架构。
解决方案
Hive 的解决方案。它可能可以优化。阅读代码中的注释:
with your_table as ( --your data example, you select from your table instead
select "[{name=abc, org=true, self=true, status=accepted, email=abc@gmail.com}, {name=cab abc, org=false, self=false, status=needsAction, email=cab@google.com}]" str
)
select --get map values
m['org'] as org ,
m['name'] as name ,
m['self'] as self ,
m['status'] as status ,
m['email'] as email
from
(--remove spaces after commas, convert to map
select str_to_map(regexp_replace(a.s,', +',','),',','=') m --map
from your_table t --replace w your table
lateral view explode(split(regexp_replace(str,'\\[|\\{|]',''),'}, *')) a as s --remove extra characters: '[' or '{' or ']', split and explode
)s;
结果:
OK
true abc true accepted abc@gmail.com
false cab abc false needsAction cab@google.com
Time taken: 1.001 seconds, Fetched: 2 row(s)
推荐阅读
- java - 了解优先队列中的 SORT 方法
- docker - 挂载操作系统特定的卷
- reactjs - 可以在呈现页面之前更改特定链接/页面/路径的元数据/图像/标题吗?
- react-native - Expo 构建错误不是描述性的 - 构建 JavaScript 包失败
- javascript - 如何在 Javascript 的一个文本框中添加两个数字?
- gradle - Gradle 插件 - getArtifacts() 导致“无法解析配置的所有依赖项...”
- python - Flask-WTF SelectMultipleField 填充数据库 ID 而不是名称
- reactjs - 使用 redux 保持“Like”计数器的状态
- html - 在表格单元格中对齐按钮标签
- spring-boot - 使用 SQLite 数据库的简单 SpringBoot CRUD 应用程序