从字符串中提取键值对

camsedfj  于 2021-06-24  发布在  Hive
关注(0)|答案(2)|浏览(301)

我刚接触配置单元,正在尝试运行一个查询,其中一列 (col1) 描述为类型字符串,并包含键值对,例如 {color=blue, name=john, size=M} . 我正在尝试提取一些值,以便可以执行类似于返回col1包含color=blue的所有行的操作。
我一直想用 get_json_object 但我不认为这是正确的方法,因为我不确定这个字段在技术上是json数组。

a7qyws3x

a7qyws3x1#

使用与配置单元兼容的sparksql。
如果col1是字符串,则可以是一个解决方案:

val initDF = spark.sql("select '{color=blue, name=john, size=M}' as col1 union select '{color=red, name=jim, size=L}' as col1")
initDF.show(false)

它显示:

+-------------------------------+
|col1                           |
+-------------------------------+
|{color=blue, name=john, size=M}|
|{color=red, name=jim, size=L}  |
+-------------------------------+

如果只想得到color=blue的行

initDF.where("col1 like '%color=blue%'").show(false)

显示预期结果:

+-------------------------------+
|col1                           |
+-------------------------------+
|{color=blue, name=john, size=M}|
+-------------------------------+

如果col1是一个结构:

val initDFStruct = spark.sql("select 'blue' as color, 'john' as name, 'M' as size union select 'red' as color, 'jim' as name, 'L'")
  .selectExpr("(color, name, size) as col1")
initDFStruct.show(false)

它显示:

+---------------+
|col1           |
+---------------+
|[red, jim, L]  |
|[blue, john, M]|
+---------------+
initDFStruct.where("col1.color = 'blue'").show(false)

显示想要的结果:

+---------------+
|col1           |
+---------------+
|[blue, john, M]|
+---------------+

总之,如果将其作为字符串列,则可以在where子句中使用 where col1 like '%color=blue%' 如果将其作为结构,则where子句应为: "col1.color = 'blue'

c7rzv4ha

c7rzv4ha2#

您可以将字符串转换为map(删除逗号后的大括号和空格,并使用str\u to\u map函数)。配置单元示例:

with your_data as 
(
select '{color=blue, name=john, size=M}' str
)

select str        as original_string,
       m['color'] as color,
       m['name']  as name,
       m['size']  as size
from
(
select str, str_to_map(regexp_replace(regexp_replace(str,'\\{|\\}',''),', *',','),',','=') m 
  from your_data --use your table
)s;

结果:

original_string                 color   name    size    
{color=blue, name=john, size=M} blue    john    M

相关问题