【问题标题】:Select particular values from JSON column in Presto从 Presto 中的 JSON 列中选择特定值
【发布时间】:2017-11-29 22:41:49
【问题描述】:

我想在 Presto 中解析的表中有一个 VARCHAR 类型的 JSON 列 points。例如:

points = {"0": 0.2, "1": 1.2, "2": 0.5, "15": 1.2, "20": 0.7}

我只想选择键 "0", "2" and "20" 的值。如何使用 Presto 的 UNNEST 功能来获取它们。到目前为止我所做的是:

select t.value from myTable CROSS JOIN UNNEST(points) AS t(key, value) limit 1

但这给出了这个错误:

Cannot unnest type: varchar

Update:

我运行了以下查询并得到了结果,但它从 JSON 返回一个随机键值对,而我需要特定的键。

select key, value from myTable CROSS JOIN UNNEST(SPLIT_TO_MAP(points, ',', ':')) AS t(key, value) limit 1

【问题讨论】:

    标签: sql database presto


    【解决方案1】:

    您可以取消嵌套数组或映射。所以首先需要将 JSON 字符串转换成 MAP:

    CAST(json_parse(str) AS MAP<BIGINT, DOUBLE>)
    

    这是一个例子:

    presto> select tt.value
         -> from (VALUES '{"0": 0.2, "1": 1.2, "2": 0.5, "15": 1.2, "20": 0.7}') as t(json)
         -> CROSS JOIN UNNEST(CAST(json_parse(json) AS MAP<BIGINT, DOUBLE>)) AS tt(key, value)
         -> ;
     value
    -------
       0.2
       1.2
       1.2
       0.5
       0.7
    (5 rows)
    

    【讨论】:

      【解决方案2】:

      您可能需要先根据这些文档转换为 json 数据类型:enter link description here

      UNNEST(CAST(points AS JSON))
      

      完整查询:

      select t.value from myTable
      CROSS JOIN UNNEST(CAST(points AS JSON)) AS t(key, value) limit 1
      

      【讨论】:

      • 完整的查询应该是什么?
      • 我把它添加到答案中,让我知道它是怎么回事
      • 我试过了,但这也没有用:select t.value from myTable CROSS JOIN UNNEST(CAST(JSON CAST(points AS JSON) AS MAP(INTEGER, REAL))) AS t(键,值)限制1
      • 啊,unnest 期待一个数组,看看你是否可以将你的 json 有效负载转换为数组
      • 也许:select t.value from myTable CROSS JOIN UNNEST(CAST(CAST(points AS JSON) AS ARRAY&lt;VARCHAR&gt;) AS t(key, value) limit 1
      猜你喜欢
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 2021-06-16
      • 2021-10-30
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      相关资源
      最近更新 更多