Reputation: 1239
I have a JSON column points
of type VARCHAR in a table which I want to parse in Presto. For example:
points = {"0": 0.2, "1": 1.2, "2": 0.5, "15": 1.2, "20": 0.7}
I want to select only the values for keys "0", "2" and "20"
. How do I use the UNNEST functionality of Presto to get them. What I've done till now is:
select t.value from myTable CROSS JOIN UNNEST(points) AS t(key, value) limit 1
But this gives this error:
Cannot unnest type: varchar
Update:
I ran the following query and got the result but it is returning one random key-value pair from the JSON whereas I need specific keys.
select key, value from myTable CROSS JOIN UNNEST(SPLIT_TO_MAP(points, ',', ':')) AS t(key, value) limit 1
Upvotes: 1
Views: 5480
Reputation: 772
You can unnest an Array or Map. So you first need to convert the JSON string into a MAP:
CAST(json_parse(str) AS MAP<BIGINT, DOUBLE>)
Here is an example:
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)
Upvotes: 1
Reputation: 1423
You may need to cast to json datatype first according to these docs: enter link description here
UNNEST(CAST(points AS JSON))
Full query:
select t.value from myTable
CROSS JOIN UNNEST(CAST(points AS JSON)) AS t(key, value) limit 1
Upvotes: 0