Unable to convert varchar to array in Presto Athena

╄→гoц情女王★ 提交于 2020-06-12 08:59:11

问题


My data is in varchar format. I want to split both the elements of this array so that I can then extract a key value from the json.

Data format:

[
  {
    "skuId": "5bc87ae20d298a283c297ca1",
    "unitPrice": 0,
    "id": "5bc87ae20d298a283c297ca1",
    "quantity": "1"
  },

{
    "skuId": "182784738484wefhdchs4848",
    "unitPrice": 50,
    "id": "5bc87ae20d298a283c297ca1",
    "quantity": "4"
  },
]

For e.g. I want to extract skuid from the above column. So my data after extraction should look like:

1 5bc87ae20d298a283c297ca1
2 182784738484wefhdchs4848

Cast to array doesn't work e.g select cast(col as array) gives the following error: Unknown type: array

So I am not able to unnest the array.

How do I do solve this problem in Athena?


回答1:


You can use a combination of parsing the value as JSON, casting it to a structured SQL type (array/map/row), and UNNEST WITH ORDINALITY to extract the elements from the array as separate rows. Note that this only works if the array elements in the JSON payload don't have a trailing commas. Your example has one but it is removed from the example below.

WITH data(value) AS (VALUES
 '[
    {
      "skuId": "5bc87ae20d298a283c297ca1",
      "unitPrice": 0,
      "id": "5bc87ae20d298a283c297ca1",
      "quantity": "1"
    },
    {
      "skuId": "182784738484wefhdchs4848",
      "unitPrice": 50,
      "id": "5bc87ae20d298a283c297ca1",
      "quantity": "4"
    }
  ]'
),
parsed(entries) AS (
  SELECT cast(json_parse(value) AS array(row(skuId varchar)))
  FROM data
)
SELECT ordinal, skuId
FROM parsed, UNNEST(entries) WITH ORDINALITY t(skuId, ordinal)

produces:

 ordinal |          skuId
---------+--------------------------
       1 | 5bc87ae20d298a283c297ca1
       2 | 182784738484wefhdchs4848
(2 rows)


来源:https://stackoverflow.com/questions/56167704/unable-to-convert-varchar-to-array-in-presto-athena

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!