In this post we are going to cover the rest of FLATTEN in Snowflake: the RECURSIVE argument, the MODE argument, the PATH column, the PATH argument, and what happens when you put two flattens in one query.
In Episode 90 we flattened an array and got one row per element. That is the form everybody learns. FLATTEN has four more parts to it, and they are the parts that either save you an afternoon or quietly give you the wrong total.
We will start with the four documents we already have and build it up step by step. By the end we will read a schema out of JSON that never had one.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 91 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's look at the documents we are flattening
- Let's flatten the object instead of an array
- Now let's look at the MODE argument
- Now let's walk the whole document with RECURSIVE
- So what did RECURSIVE actually give us?
- Let's use PATH to pick out one field
- Now let's put two flattens in one query
- Where did fourteen rows come from?
- Now let's see what it does to a total
- Can OUTER rescue it?
- Now let's nest one flatten inside another
- Let's try the PATH argument
- One last thing: let's read a schema out of the data
Let's look at the documents we are flattening
This is the same EVENTS_JSON table we used in the last post. Four rows, and each row holds one JSON document in a VARIANT column.
Copy this into a Snowflake worksheet and run it once.
-- EVENTS_JSON is the table this whole level runs against. It holds four
-- JSON documents, and they are deliberately not all the same shape.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE EVENTS_JSON (
EVENT_ID INT,
PAYLOAD VARIANT
);
INSERT INTO EVENTS_JSON (EVENT_ID, PAYLOAD)
SELECT 1, PARSE_JSON('{
"event": "purchase",
"amount": 4200,
"device": { "os": "windows", "type": "desktop" },
"user": { "id": 101, "name": "Northwind Traders" },
"items": [ { "sku": "A-100", "qty": 8, "price": 300 },
{ "sku": "B-220", "qty": 4, "price": 450 } ],
"tags": [ "priority", "repeat" ]
}')
UNION ALL SELECT 2, PARSE_JSON('{
"event": "purchase",
"amount": 890.5,
"device": { "os": "ios", "type": "mobile" },
"user": { "id": 102, "name": "Blue Ridge Supply" },
"items": [ { "sku": "C-310", "qty": 3, "price": 296.83 } ],
"tags": [ "new" ]
}')
UNION ALL SELECT 3, PARSE_JSON('{
"event": "refund",
"amount": "1500.00",
"user": { "id": 103, "name": "Kestrel Analytics" },
"items": [ { "sku": "A-100", "qty": 5, "price": 300 } ],
"tags": []
}')
UNION ALL SELECT 4, PARSE_JSON('{
"event": "purchase",
"amount": 9250,
"device": { "os": "android", "type": "tablet" },
"user": { "id": 107, "name": "Meridian Health" },
"items": [ { "sku": "D-400", "qty": 12, "price": 500 },
{ "sku": "A-100", "qty": 10, "price": 300 },
{ "sku": "E-505", "qty": 8, "price": 156.25 } ],
"tags": [ "priority", "enterprise", "repeat" ]
}');Before we flatten anything, let's measure the shapes. How many items, how many tags, how many keys at the top level, and is the device key there at all.
SELECT EVENT_ID,
ARRAY_SIZE(PAYLOAD:items) AS ITEMS,
ARRAY_SIZE(PAYLOAD:tags) AS TAGS,
ARRAY_SIZE(OBJECT_KEYS(PAYLOAD)) AS TOP_LEVEL_KEYS,
PAYLOAD:device IS NULL AS DEVICE_MISSING
FROM EVENTS_JSON
ORDER BY EVENT_ID;| EVENT_ID | ITEMS | TAGS | TOP_LEVEL_KEYS | DEVICE_MISSING |
|---|---|---|---|---|
| 1 | 2 | 2 | 6 | FALSE |
| 2 | 1 | 1 | 6 | FALSE |
| 3 | 1 | 0 | 5 | TRUE |
| 4 | 3 | 3 | 6 | FALSE |
Three things in that grid are going to matter all the way through this post.
- The
ITEMScolumn reads2,1,1,3, which is seven items in all. - The
TAGScolumn reads2,1,0,3, which is six tags in all. Event3has an empty tags array. TOP_LEVEL_KEYSreads6,6,5,6. Event3is a key short becauseDEVICE_MISSINGisTRUEon that row.
So the data is ragged on purpose. That is what real JSON looks like.
Let's flatten the object instead of an array
Last time we handed FLATTEN a path to an array, PAYLOAD:items, and got one row per element.
This time let's hand it the whole payload and see what it does with an object.
SELECT E.EVENT_ID, P.KEY, TYPEOF(P.VALUE) AS VALUE_TYPE, P.PATH
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD) P
WHERE E.EVENT_ID = 1
ORDER BY P.KEY;| EVENT_ID | KEY | VALUE_TYPE | PATH |
|---|---|---|---|
| 1 | amount | DECIMAL | amount |
| 1 | device | OBJECT | device |
| 1 | event | VARCHAR | event |
| 1 | items | ARRAY | items |
| 1 | tags | ARRAY | tags |
| 1 | user | OBJECT | user |
Six rows for one document, one per key, in key order: amount, device, event, items, tags and user.
Two columns are doing the work here. KEY holds the name of the key, which is empty when you flatten an array and full when you flatten an object. VALUE_TYPE is TYPEOF of what is underneath.
Read the VALUE_TYPE column down the grid: DECIMAL, OBJECT, VARCHAR, ARRAY, ARRAY, OBJECT. Four of those six values have something inside them, and this flatten stopped at the door of all four of them.
Now let's count the same thing over the whole table, and check it against something we worked out without FLATTEN at all.
SELECT COUNT(*) AS FLATTENED_ROWS,
(SELECT SUM(ARRAY_SIZE(OBJECT_KEYS(PAYLOAD))) FROM EVENTS_JSON)
AS SUM_OF_KEY_COUNTS,
COUNT(*) = (SELECT SUM(ARRAY_SIZE(OBJECT_KEYS(PAYLOAD))) FROM EVENTS_JSON)
AS IT_MATCHES
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD) P;| FLATTENED_ROWS | SUM_OF_KEY_COUNTS | IT_MATCHES |
|---|---|---|
| 23 | 23 | TRUE |
Twenty three rows, and the sum of the four key counts is also twenty three, so IT_MATCHES is TRUE. Add up the TOP_LEVEL_KEYS column from the first grid and you get the same figure by hand.
Flattening an object gives you one row per key. Flattening an array gives you one row per element. Same function, same syntax, and the shape of the input decides which one you get.
Now let's look at the MODE argument
FLATTEN takes an argument called MODE that says what it is allowed to expand. It takes 'ARRAY', 'OBJECT' or 'BOTH'.
Let's ask for 'ARRAY' over a payload that is an object.
SELECT COUNT(*) AS ROWS_RETURNED
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, MODE => 'ARRAY') P;| ROWS_RETURNED |
|---|
| 0 |
Zero rows. No error, no warning. We asked it to expand arrays, we gave it an object, and it expanded nothing.
Now the same query with 'OBJECT'.
SELECT COUNT(*) AS ROWS_RETURNED
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, MODE => 'OBJECT') P;| ROWS_RETURNED |
|---|
| 23 |
Twenty three, which is the number we already had. Let's find out which of the two is the default.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, MODE => 'BOTH') P) AS MODE_BOTH,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD) P) AS NO_MODE_GIVEN,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, MODE => 'BOTH') P)
= (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD) P) AS BOTH_IS_DEFAULT;| MODE_BOTH | NO_MODE_GIVEN | BOTH_IS_DEFAULT |
|---|---|---|
| 23 | 23 | TRUE |
'BOTH' and no MODE at all give the same twenty three rows, and BOTH_IS_DEFAULT is TRUE. So 'BOTH' is what you have been using every time you left the argument out, and it is why you have probably never needed it.
And a mode it does not recognise? Let's try one.
SELECT COUNT(*) AS SHOULD_NOT_GET_THIS_FAR
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, MODE => 'SIDEWAYS') P;001043 (22023): SQL compilation error: Bad flattening mode 'SIDEWAYS' (not 'BOTH', 'ARRAY', or 'OBJECT')
That one is a compile error, and the message names the three values it will accept. This is the kind of mistake you want: it stops you before the query runs.
Compare that with what MODE => 'ARRAY' did on an object. A wrong value is caught at compile time. The right value applied to the wrong shape returns an empty result and says nothing at all. If a flatten comes back with no rows, check the mode against the shape before you check anything else.
Now let's walk the whole document with RECURSIVE
This is the argument the episode is really about. RECURSIVE => TRUE keeps going instead of stopping at the first level.
Same input, the whole payload, same single document. Let's ask for the PATH column as well this time, and the raw VALUE.
SELECT R.SEQ, R.KEY, R.PATH, R.INDEX,
TYPEOF(R.VALUE) AS VALUE_TYPE,
R.VALUE
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
WHERE E.EVENT_ID = 1
ORDER BY R.SEQ;| SEQ | KEY | PATH | INDEX | VALUE_TYPE | VALUE |
|---|---|---|---|---|---|
| 1 | amount | amount | NULL | DECIMAL | 4200 |
| 1 | device | device | NULL | OBJECT | { "os": "windows", "type": "desktop" } |
| 1 | os | device.os | NULL | VARCHAR | "windows" |
| 1 | type | device.type | NULL | VARCHAR | "desktop" |
| 1 | event | event | NULL | VARCHAR | "purchase" |
| 1 | items | items | NULL | ARRAY | [ { "price": 300, "qty": 8, "sku": "A-100" }, { "price": 450, "qty": 4, "sku": "B-220" } ] |
| 1 | NULL | items[0] | 0 | OBJECT | { "price": 300, "qty": 8, "sku": "A-100" } |
| 1 | price | items[0].price | NULL | DECIMAL | 300 |
| 1 | qty | items[0].qty | NULL | INTEGER | 8 |
| 1 | sku | items[0].sku | NULL | VARCHAR | "A-100" |
| 1 | NULL | items[1] | 1 | OBJECT | { "price": 450, "qty": 4, "sku": "B-220" } |
| 1 | price | items[1].price | NULL | INTEGER | 450 |
| 1 | qty | items[1].qty | NULL | INTEGER | 4 |
| 1 | sku | items[1].sku | NULL | VARCHAR | "B-220" |
| 1 | tags | tags | NULL | ARRAY | [ "priority", "repeat" ] |
| 1 | NULL | tags[0] | 0 | VARCHAR | "priority" |
| 1 | NULL | tags[1] | 1 | VARCHAR | "repeat" |
| 1 | user | user | NULL | OBJECT | { "id": 101, "name": "Northwind Traders" } |
| 1 | id | user.id | NULL | INTEGER | 101 |
| 1 | name | user.name | NULL | VARCHAR | "Northwind Traders" |
Read the PATH column from the top. amount, then device, then device.os and device.type. It went inside device. Then event, then items, then items[0], then items[0].price, items[0].qty and items[0].sku.
So PATH tells you exactly where in the document each row came from. That is the column that makes a recursive flatten worth running.
Have a look at the items[0] row in particular. Its KEY is NULL and its INDEX is 0. That row is an array element, and an array element has a position rather than a name. Every row whose KEY is filled in came out of an object.
So what did RECURSIVE actually give us?
Let's count what came back and split it by what kind of node each row is.
SELECT COUNT(*) AS ALL_NODES,
COUNT_IF(TYPEOF(R.VALUE) = 'OBJECT') AS OBJECT_NODES,
COUNT_IF(TYPEOF(R.VALUE) = 'ARRAY') AS ARRAY_NODES,
COUNT_IF(TYPEOF(R.VALUE) NOT IN ('OBJECT','ARRAY')) AS LEAF_NODES,
(SELECT ARRAY_SIZE(OBJECT_KEYS(PAYLOAD)) FROM EVENTS_JSON WHERE EVENT_ID = 1)
AS TOP_LEVEL_KEYS_ONLY
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
WHERE E.EVENT_ID = 1;| ALL_NODES | OBJECT_NODES | ARRAY_NODES | LEAF_NODES | TOP_LEVEL_KEYS_ONLY |
|---|---|---|---|---|
| 20 | 4 | 2 | 14 | 6 |
Twenty nodes in total: four objects, two arrays and fourteen leaves. And the same document has only six keys at the top level.
Let's put the three numbers that matter side by side.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD) P
WHERE E.EVENT_ID = 1) AS ONE_LEVEL,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
WHERE E.EVENT_ID = 1) AS RECURSIVE_,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
WHERE E.EVENT_ID = 1
AND TYPEOF(R.VALUE) NOT IN ('OBJECT','ARRAY')) AS RECURSIVE_LEAVES_ONLY;| ONE_LEVEL | RECURSIVE_ | RECURSIVE_LEAVES_ONLY |
|---|---|---|
| 6 | 20 | 14 |
One level gave six rows. Recursive gave twenty. Filtered down to the leaves, fourteen.
The six rows in between are the containers. Recursive does not hand you the leaves of the document. It hands you every node, branches included, and the device object and the items array each come back as a row of their own as well as being walked into.
Which means a recursive flatten almost always wants a filter. WHERE TYPEOF(VALUE) NOT IN ('OBJECT','ARRAY') is the one you will write most often, and it is what took twenty down to fourteen in the grid above.
Now let's take the filter off and run a census of every node in the whole table, grouped by type.
SELECT TYPEOF(R.VALUE) AS NODE_TYPE,
COUNT(*) AS HOW_MANY,
COUNT(DISTINCT E.EVENT_ID) AS IN_HOW_MANY_EVENTS
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
GROUP BY TYPEOF(R.VALUE)
ORDER BY HOW_MANY DESC;| NODE_TYPE | HOW_MANY | IN_HOW_MANY_EVENTS |
|---|---|---|
| VARCHAR | 28 | 4 |
| INTEGER | 14 | 4 |
| OBJECT | 14 | 4 |
| ARRAY | 8 | 4 |
| DECIMAL | 7 | 4 |
Twenty eight VARCHAR nodes, fourteen INTEGER, and the rest on down the grid. Every one of the five types appears in all four events.
Let's use PATH to pick out one field
Once you have PATH you can filter on it like any other string column. Let's pull out every sku in the table without knowing how many items any event has.
SELECT E.EVENT_ID, R.PATH, R.VALUE::VARCHAR AS SKU
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
WHERE R.PATH LIKE 'items[%].sku'
ORDER BY E.EVENT_ID, R.PATH;| EVENT_ID | PATH | SKU |
|---|---|---|
| 1 | items[0].sku | A-100 |
| 1 | items[1].sku | B-220 |
| 2 | items[0].sku | C-310 |
| 3 | items[0].sku | A-100 |
| 4 | items[0].sku | D-400 |
| 4 | items[1].sku | A-100 |
| 4 | items[2].sku | E-505 |
Seven rows, which is the seven items we counted in the first grid. The PATH column still tells us which element each one came from, so event 4's three skus arrive as items[0].sku, items[1].sku and items[2].sku.
Let's check that against the two other ways of getting the same number.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
WHERE R.PATH LIKE 'items[%].sku') AS VIA_RECURSIVE,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I) AS VIA_DIRECT,
(SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON) AS SUM_OF_SIZES;| VIA_RECURSIVE | VIA_DIRECT | SUM_OF_SIZES |
|---|---|---|
| 7 | 7 | 7 |
Seven, seven and seven. The recursive flatten filtered by path, the direct flatten of PAYLOAD:items, and the plain sum of the array sizes all agree.
That is worth doing once on your own data. If those three numbers ever disagree, the pattern you have reached for is not counting what you think it is.
Now let's put two flattens in one query
Here is the mistake this post exists to save you from. We have two arrays on every document, items and tags, and we want both. So we write two flattens.
SELECT E.EVENT_ID,
I.VALUE:sku::VARCHAR AS SKU,
T.VALUE::VARCHAR AS TAG
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags) T
ORDER BY E.EVENT_ID, SKU, TAG;| EVENT_ID | SKU | TAG |
|---|---|---|
| 1 | A-100 | priority |
| 1 | A-100 | repeat |
| 1 | B-220 | priority |
| 1 | B-220 | repeat |
| 2 | C-310 | new |
| 4 | A-100 | enterprise |
| 4 | A-100 | priority |
| 4 | A-100 | repeat |
| 4 | D-400 | enterprise |
| 4 | D-400 | priority |
| 4 | D-400 | repeat |
| 4 | E-505 | enterprise |
| 4 | E-505 | priority |
| 4 | E-505 | repeat |
Fourteen rows out of four documents. Look at event 1: A-100 appears with both tags and B-220 appears with both tags. Two items and two tags gave four rows.
Event 4 has three items and three tags, and it takes up nine rows of that grid. Each sku is paired with every tag.
And event 3 is not in the grid at all. It has one item and no tags, so a query about its items returned nothing about it.
Where did fourteen rows come from?
Two flattens of the same parent row do not add. They multiply. Let's put the arithmetic on screen per event.
SELECT EVENT_ID,
ARRAY_SIZE(PAYLOAD:items) AS ITEMS,
ARRAY_SIZE(PAYLOAD:tags) AS TAGS,
ARRAY_SIZE(PAYLOAD:items) + ARRAY_SIZE(PAYLOAD:tags) AS IF_IT_ADDED,
ARRAY_SIZE(PAYLOAD:items) * ARRAY_SIZE(PAYLOAD:tags) AS WHAT_IT_ACTUALLY_IS
FROM EVENTS_JSON
ORDER BY EVENT_ID;| EVENT_ID | ITEMS | TAGS | IF_IT_ADDED | WHAT_IT_ACTUALLY_IS |
|---|---|---|---|---|
| 1 | 2 | 2 | 4 | 4 |
| 2 | 1 | 1 | 2 | 1 |
| 3 | 1 | 0 | 1 | 0 |
| 4 | 3 | 3 | 6 | 9 |
Go down the last two columns. Event 2 adds to 2 and multiplies to 1. Event 3 adds to 1 and multiplies to 0. Event 4 adds to 6 and multiplies to 9.
Now look at event 1. It has two items and two tags, so IF_IT_ADDED and WHAT_IT_ACTUALLY_IS are both 4.
That tie is how this reaches production. The first event anybody checks is usually the first row of the table, and on a document with two items and two tags the wrong model and the right model give the same answer. It looks correct, it ships, and it is wrong on every other document.
Let's total the two models up and count how many of the four events survived.
SELECT COUNT(*) AS CROSS_ROWS,
(SELECT SUM(ARRAY_SIZE(PAYLOAD:items) * ARRAY_SIZE(PAYLOAD:tags))
FROM EVENTS_JSON) AS SUM_OF_PRODUCTS,
(SELECT SUM(ARRAY_SIZE(PAYLOAD:items) + ARRAY_SIZE(PAYLOAD:tags))
FROM EVENTS_JSON) AS SUM_OF_SUMS,
COUNT(DISTINCT E.EVENT_ID) AS EVENTS_SURVIVING
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags) T;| CROSS_ROWS | SUM_OF_PRODUCTS | SUM_OF_SUMS | EVENTS_SURVIVING |
|---|---|---|---|
| 14 | 14 | 13 | 3 |
The query returned fourteen rows, and the sum of the products is fourteen. The sum of the sums is thirteen, which is not what came back. And EVENTS_SURVIVING is three out of four, because one times zero is zero and event 3 dropped out entirely.
Now let's see what it does to a total
Row counts are easy to shrug at. Let's do the same thing to the amount column, which is the one somebody will put on a report.
SELECT (SELECT SUM(PAYLOAD:amount::NUMBER(12,2)) FROM EVENTS_JSON)
AS CORRECT_TOTAL,
(SELECT SUM(E.PAYLOAD:amount::NUMBER(12,2))
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I)
AS AFTER_ONE_FLATTEN,
(SELECT SUM(E.PAYLOAD:amount::NUMBER(12,2))
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags) T)
AS AFTER_TWO_FLATTENS;| CORRECT_TOTAL | AFTER_ONE_FLATTEN | AFTER_TWO_FLATTENS |
|---|---|---|
| 15840.50 | 38540.50 | 100940.50 |
The correct total is 15840.50. After one flatten it is 38540.50, because each event's amount is repeated once per item. After two flattens it is 100940.50.
Nothing in that query is invalid SQL and nothing warned us. The amount was simply counted once per row, and the number of rows stopped being the number of events two joins ago.
This is the same trap as Episode 90, one notch worse. There the total went up by the number of items. Here it went up by the number of items multiplied by the number of tags. Aggregate the parent before you flatten, or aggregate the children separately and join the totals.
Can OUTER rescue it?
In Episode 90 we used OUTER => TRUE to keep a parent row that had nothing to flatten. Event 3 disappeared here, so that is the obvious thing to reach for. Let's try it on one flatten, then the other, then both.
SELECT (SELECT COUNT(DISTINCT E.EVENT_ID) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items, OUTER => TRUE) I,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags) T) AS ITEMS_OUTER_ONLY,
(SELECT COUNT(DISTINCT E.EVENT_ID) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags, OUTER => TRUE) T)
AS TAGS_OUTER_ONLY,
(SELECT COUNT(DISTINCT E.EVENT_ID) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items, OUTER => TRUE) I,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags, OUTER => TRUE) T)
AS BOTH_OUTER,
(SELECT COUNT(*) FROM EVENTS_JSON) AS EVENTS_TOTAL;| ITEMS_OUTER_ONLY | TAGS_OUTER_ONLY | BOTH_OUTER | EVENTS_TOTAL |
|---|---|---|---|
| 3 | 4 | 4 | 4 |
OUTER on the items flatten keeps three of the four events. OUTER on the tags flatten keeps four. Both keeps four.
That makes sense once you say it out loud. Event 3 has an item, so the items flatten was never the one losing it. It has no tags, so putting OUTER on the tags flatten is what brings it back.
And notice what OUTER does not do. It keeps the event, it does not undo the multiplication. The rows that remain are still the cross product, and a SUM over them is still wrong.
Now let's nest one flatten inside another
Two flattens of the same parent multiply. Two flattens where the second one reads the first one's output do something quite different.
Let's flatten the items, and then flatten each item's own VALUE. One document first, so we can see the shape of it.
SELECT E.EVENT_ID, I.INDEX AS ITEM_INDEX, F.KEY, F.VALUE
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I,
LATERAL FLATTEN(INPUT => I.VALUE) F
WHERE E.EVENT_ID = 2
ORDER BY I.INDEX, F.KEY;| EVENT_ID | ITEM_INDEX | KEY | VALUE |
|---|---|---|---|
| 2 | 0 | price | 296.83 |
| 2 | 0 | qty | 3 |
| 2 | 0 | sku | "C-310" |
Event 2 has one item, and that item has three keys: price, qty and sku. So the second flatten ran inside the first rather than beside it.
Let's count it over the whole table.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT(DISTINCT E.EVENT_ID) AS EVENTS,
COUNT(DISTINCT F.KEY) AS DISTINCT_ITEM_KEYS,
(SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON) AS ITEM_ROWS
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I,
LATERAL FLATTEN(INPUT => I.VALUE) F;| ROWS_TOTAL | EVENTS | DISTINCT_ITEM_KEYS | ITEM_ROWS |
|---|---|---|---|
| 21 | 4 | 3 | 7 |
Twenty one rows from all four events, with three distinct item keys and seven item rows underneath. Seven items with three keys each is twenty one, and no document was multiplied by anything belonging to a sibling.
And it answers a question nothing else can
Once the keys are rows you can ask whether every item carries the same ones. Let's group by the key and count.
SELECT F.KEY,
COUNT(*) AS TIMES_SEEN,
(SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON) AS ITEM_ROWS_TOTAL,
COUNT(*) = (SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON)
AS PRESENT_ON_EVERY_ITEM
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I,
LATERAL FLATTEN(INPUT => I.VALUE) F
GROUP BY F.KEY
ORDER BY F.KEY;| KEY | TIMES_SEEN | ITEM_ROWS_TOTAL | PRESENT_ON_EVERY_ITEM |
|---|---|---|---|
| price | 7 | 7 | TRUE |
| qty | 7 | 7 | TRUE |
| sku | 7 | 7 | TRUE |
price, qty and sku each appear seven times, against seven item rows in total, so PRESENT_ON_EVERY_ITEM is TRUE on all three. The items in this table are consistent, and that is now a fact rather than an assumption.
Let's try the PATH argument
There is one more argument, and it reads oddly the first time. FLATTEN takes a PATH argument as well as having a PATH column, and they are not the same thing. The column says where a row came from. The argument says where to start.
Let's hand it the whole payload and the string 'items'.
SELECT E.EVENT_ID, I.INDEX, I.VALUE:sku::VARCHAR AS SKU
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, PATH => 'items') I
ORDER BY E.EVENT_ID, I.INDEX;| EVENT_ID | INDEX | SKU |
|---|---|---|
| 1 | 0 | A-100 |
| 1 | 1 | B-220 |
| 2 | 0 | C-310 |
| 3 | 0 | A-100 |
| 4 | 0 | D-400 |
| 4 | 1 | A-100 |
| 4 | 2 | E-505 |
Seven rows with an INDEX and a sku, which is exactly what FLATTEN(INPUT => PAYLOAD:items) gave us earlier.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, PATH => 'items') I) AS VIA_PATH_ARG,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I) AS VIA_COLON,
(SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON) AS SUM_OF_SIZES;| VIA_PATH_ARG | VIA_COLON | SUM_OF_SIZES |
|---|---|---|
| 7 | 7 | 7 |
Seven, seven and seven again. So PATH => 'items' is another way of writing PAYLOAD:items, and the two are interchangeable.
It earns its place when the path is not fixed. A string argument can be built, passed in or stored in a column. The colon form has to be typed.
One last thing: let's read a schema out of the data
This is the section to actually use. A recursive flatten plus a GROUP BY on the PATH column tells you every path that exists in a column of JSON.
SELECT R.PATH,
COUNT(*) AS TIMES_SEEN,
COUNT(DISTINCT E.EVENT_ID) AS IN_EVENTS,
COUNT(DISTINCT TYPEOF(R.VALUE)) AS DISTINCT_TYPES,
MIN(TYPEOF(R.VALUE)) AS A_TYPE
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
GROUP BY R.PATH
ORDER BY R.PATH;| PATH | TIMES_SEEN | IN_EVENTS | DISTINCT_TYPES | A_TYPE |
|---|---|---|---|---|
| amount | 4 | 4 | 3 | DECIMAL |
| device | 3 | 3 | 1 | OBJECT |
| device.os | 3 | 3 | 1 | VARCHAR |
| device.type | 3 | 3 | 1 | VARCHAR |
| event | 4 | 4 | 1 | VARCHAR |
| items | 4 | 4 | 1 | ARRAY |
| items[0] | 4 | 4 | 1 | OBJECT |
| items[0].price | 4 | 4 | 1 | DECIMAL |
| items[0].qty | 4 | 4 | 1 | INTEGER |
| items[0].sku | 4 | 4 | 1 | VARCHAR |
| items[1] | 2 | 2 | 1 | OBJECT |
| items[1].price | 2 | 2 | 1 | INTEGER |
| items[1].qty | 2 | 2 | 1 | INTEGER |
| items[1].sku | 2 | 2 | 1 | VARCHAR |
| items[2] | 1 | 1 | 1 | OBJECT |
| items[2].price | 1 | 1 | 1 | DECIMAL |
| items[2].qty | 1 | 1 | 1 | INTEGER |
| items[2].sku | 1 | 1 | 1 | VARCHAR |
| tags | 4 | 4 | 1 | ARRAY |
| tags[0] | 3 | 3 | 1 | VARCHAR |
| tags[1] | 2 | 2 | 1 | VARCHAR |
| tags[2] | 1 | 1 | 1 | VARCHAR |
| user | 4 | 4 | 1 | OBJECT |
| user.id | 4 | 4 | 1 | INTEGER |
| user.name | 4 | 4 | 1 | VARCHAR |
Twenty five paths, with how often each one is seen, how many events it appears in, and how many distinct types it carries.
Look at the amount row. DISTINCT_TYPES is 3, so one path holds three different types across four documents. We knew that about this table already. The difference is that it is now the output of a query rather than something somebody remembered.
Let's collapse the array indexes
There is a problem with that grid. items[0].sku, items[1].sku and items[2].sku are listed separately, and they are the same field. Let's replace any bracketed number with [*] and group on that instead.
SELECT REGEXP_REPLACE(R.PATH, $$\[[0-9]+\]$$, '[*]') AS PATH_SHAPE,
COUNT(*) AS TIMES_SEEN,
COUNT(DISTINCT E.EVENT_ID) AS IN_EVENTS,
COUNT(DISTINCT TYPEOF(R.VALUE)) AS DISTINCT_TYPES
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
GROUP BY REGEXP_REPLACE(R.PATH, $$\[[0-9]+\]$$, '[*]')
ORDER BY PATH_SHAPE;| PATH_SHAPE | TIMES_SEEN | IN_EVENTS | DISTINCT_TYPES |
|---|---|---|---|
| amount | 4 | 4 | 3 |
| device | 3 | 3 | 1 |
| device.os | 3 | 3 | 1 |
| device.type | 3 | 3 | 1 |
| event | 4 | 4 | 1 |
| items | 4 | 4 | 1 |
| items[*] | 7 | 4 | 1 |
| items[*].price | 7 | 4 | 2 |
| items[*].qty | 7 | 4 | 1 |
| items[*].sku | 7 | 4 | 1 |
| tags | 4 | 4 | 1 |
| tags[*] | 6 | 3 | 1 |
| user | 4 | 4 | 1 |
| user.id | 4 | 4 | 1 |
| user.name | 4 | 4 | 1 |
Twenty five paths became fifteen path shapes. items[*].sku is one row now, seen seven times across four events, and items[*].price is the one shape carrying two distinct types.
Have a look at the tags[*] row as well. Six nodes, but IN_EVENTS is three. Every other shape that reaches into the data is in four. That three is a flag.
Which shapes are not in every document?
So let's turn that into the question directly, with a HAVING clause.
SELECT REGEXP_REPLACE(R.PATH, $$\[[0-9]+\]$$, '[*]') AS PATH_SHAPE,
COUNT(DISTINCT E.EVENT_ID) AS IN_EVENTS,
(SELECT COUNT(*) FROM EVENTS_JSON) AS EVENTS_TOTAL,
COUNT(DISTINCT E.EVENT_ID) = (SELECT COUNT(*) FROM EVENTS_JSON)
AS IN_ALL_OF_THEM
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
GROUP BY REGEXP_REPLACE(R.PATH, $$\[[0-9]+\]$$, '[*]')
HAVING COUNT(DISTINCT E.EVENT_ID) < (SELECT COUNT(*) FROM EVENTS_JSON)
ORDER BY PATH_SHAPE;| PATH_SHAPE | IN_EVENTS | EVENTS_TOTAL | IN_ALL_OF_THEM |
|---|---|---|---|
| device | 3 | 4 | FALSE |
| device.os | 3 | 4 | FALSE |
| device.type | 3 | 4 | FALSE |
| tags[*] | 3 | 4 | FALSE |
Four shapes came back: device, device.os, device.type and tags[*]. Each is in three events out of four, and IN_ALL_OF_THEM is FALSE on every row.
That is your optional fields list, read out of the data rather than out of a specification nobody kept up to date.
One more column and it is a profile
Let's add how deep each shape sits and which types it has actually been seen holding.
SELECT REGEXP_REPLACE(R.PATH, $$\[[0-9]+\]$$, '[*]') AS PATH_SHAPE,
REGEXP_COUNT(REGEXP_REPLACE(R.PATH, $$\[[0-9]+\]$$, ''), $$\.$$) + 1
AS DEPTH,
COUNT(DISTINCT E.EVENT_ID) AS IN_EVENTS,
COUNT(*) AS NODES,
ARRAY_AGG(DISTINCT TYPEOF(R.VALUE)) AS TYPES_SEEN
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD, RECURSIVE => TRUE) R
GROUP BY PATH_SHAPE, DEPTH
ORDER BY DEPTH, PATH_SHAPE;| PATH_SHAPE | DEPTH | IN_EVENTS | NODES | TYPES_SEEN |
|---|---|---|---|---|
| amount | 1 | 4 | 4 | [ "VARCHAR", "INTEGER", "DECIMAL" ] |
| device | 1 | 3 | 3 | [ "OBJECT" ] |
| event | 1 | 4 | 4 | [ "VARCHAR" ] |
| items | 1 | 4 | 4 | [ "ARRAY" ] |
| items[*] | 1 | 4 | 7 | [ "OBJECT" ] |
| tags | 1 | 4 | 4 | [ "ARRAY" ] |
| tags[*] | 1 | 3 | 6 | [ "VARCHAR" ] |
| user | 1 | 4 | 4 | [ "OBJECT" ] |
| device.os | 2 | 3 | 3 | [ "VARCHAR" ] |
| device.type | 2 | 3 | 3 | [ "VARCHAR" ] |
| items[*].price | 2 | 4 | 7 | [ "INTEGER", "DECIMAL" ] |
| items[*].qty | 2 | 4 | 7 | [ "INTEGER" ] |
| items[*].sku | 2 | 4 | 7 | [ "VARCHAR" ] |
| user.id | 2 | 4 | 4 | [ "INTEGER" ] |
| user.name | 2 | 4 | 4 | [ "VARCHAR" ] |
amount sits at depth 1, appears in all four events, and the TYPES_SEEN column lists three types for it. items[*].price sits at depth 2 with seven nodes and two types.
Have a look at how the depth was worked out, because it is worth knowing before you trust the column. The expression strips the bracketed indexes out of the path and then counts the dots, so items[*] comes back at depth 1 alongside items itself. An array element shares the depth of the array holding it.
That grid is a schema. For data that never had one and never will, from one recursive flatten and a GROUP BY.
Key points
- Flattening an object gives one row per key, with
KEYholding the key name andTYPEOF(VALUE)telling you what is underneath. MODEtakes'ARRAY','OBJECT'or'BOTH', and'BOTH'is the default.MODE => 'ARRAY'over an object returns no rows and no error.RECURSIVE => TRUEreturns the branches as well as the leaves. Twenty nodes where one level gave six, and only fourteen of them are leaves.- So a recursive flatten almost always wants
WHERE TYPEOF(VALUE) NOT IN ('OBJECT','ARRAY'). - The
PATHcolumn says where a row came from. On an array elementKEYisNULLandINDEXis set. - Two flattens of the same parent multiply. Three items and three tags give nine rows, and a document with an empty second array disappears.
- The total went from
15840.50to100940.50with no error anywhere. OUTER => TRUEon one of the two keeps the row. It does not undo the multiplication.- A nested flatten is not a parallel one. Seven items with three keys each gave twenty one rows, and it answers whether every item carries the same keys.
PATH => 'items'is the same asPAYLOAD:items, and it can be built as a string.GROUP BYon thePATHof a recursive flatten, with the array indexes collapsed, is an inferred schema with optional fields and per-path types.
Episode 92 — the ARRAY functions. ARRAY_SIZE, ARRAY_CONTAINS, ARRAY_SLICE, ARRAY_CAT, ARRAY_SORT and ARRAY_AGG, and one argument order that returns FALSE on every row without ever raising an error.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode. The EVENTS_JSON documents are invented demo data and are deliberately ragged. Every count in the text above is read off one of the grids on this page rather than worked out here. Nothing is timed and no performance claims are made anywhere in this series. Argument behaviour follows the Snowflake FLATTEN documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.