Given a table that contains a column of JSON like this:
{"payload":[{"type":"b","value":"9"}, {"type":"a","value":"8"}]}
{"payload":[{"type":"c","value":"7"}, {"type":"b","value":"3"}]}
How can I write a Presto query to give me the average b
value across all entries?
So far I think I need to use something like Hive's lateral view explode, whose equivalent is cross join unnest in Presto.
But I'm stuck on how to write the Presto query for cross join unnest
.
How can I use cross join unnest
to expand all array elements and select them?
Here's an example of that
with
defines a common table expression (CTE) namesexample
with a column aliased asmessage
VALUES
returns a verbatim table rowsetUNNEST
is taking an array within a column of a single row and returning the elements of the array as multiple rows.CAST
is changing theJSON
type into anARRAY
type that is required forUNNEST
. It could easily have been anARRAY<MAP<
but I findARRAY(ROW(
nicer as you can specify column names, and use dot notation in the select clause.JSON_EXTRACT
is using a jsonPath expression to return the array value of thepayload
keyavg()
andgroup by
should be familiar SQL.The problem was that I was running an old version of Presto.
unnest
was added in version 0.79https://github.com/facebook/presto/blob/50081273a9e8c4d7b9d851425211c71bfaf8a34e/presto-docs/src/main/sphinx/release/release-0.79.rst
As you pointed out, this was finally implemented in Presto 0.79. :)
Here is an example of the syntax for the cast from here:
Special word of advice, there is no 'string' type in Presto like there is in Hive. That means if your array contains strings make sure you use type 'varchar' otherwise you get an error msg saying 'type array does not exist' which can be misleading.