Snowflake SQL Tutorial 91 - FLATTEN Part 2 - RECURSIVE, MODE, PATH, and Nested Flattens

Snowflake SQL · Episode 91

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

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.

Sample data
-- 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.

Query
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;
Result4 rows · 5 columns
EVENT_IDITEMSTAGSTOP_LEVEL_KEYSDEVICE_MISSING
1226FALSE
2116FALSE
3105TRUE
4336FALSE

Three things in that grid are going to matter all the way through this post.

  • The ITEMS column reads 2, 1, 1, 3, which is seven items in all.
  • The TAGS column reads 2, 1, 0, 3, which is six tags in all. Event 3 has an empty tags array.
  • TOP_LEVEL_KEYS reads 6, 6, 5, 6. Event 3 is a key short because DEVICE_MISSING is TRUE on 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.

Query
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;
Result6 rows · 4 columns
EVENT_IDKEYVALUE_TYPEPATH
1amountDECIMALamount
1deviceOBJECTdevice
1eventVARCHARevent
1itemsARRAYitems
1tagsARRAYtags
1userOBJECTuser

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.

Query
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;
Result1 row · 3 columns
FLATTENED_ROWSSUM_OF_KEY_COUNTSIT_MATCHES
2323TRUE

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.

The one-line version

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.

Query
SELECT COUNT(*) AS ROWS_RETURNED
FROM EVENTS_JSON E,
     LATERAL FLATTEN(INPUT => E.PAYLOAD, MODE => 'ARRAY') P;
Result1 row · 1 column
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'.

Query
SELECT COUNT(*) AS ROWS_RETURNED
FROM EVENTS_JSON E,
     LATERAL FLATTEN(INPUT => E.PAYLOAD, MODE => 'OBJECT') P;
Result1 row · 1 column
ROWS_RETURNED
23

Twenty three, which is the number we already had. Let's find out which of the two is the default.

Query
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;
Result1 row · 3 columns
MODE_BOTHNO_MODE_GIVENBOTH_IS_DEFAULT
2323TRUE

'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.

Query
SELECT COUNT(*) AS SHOULD_NOT_GET_THIS_FAR
FROM EVENTS_JSON E,
     LATERAL FLATTEN(INPUT => E.PAYLOAD, MODE => 'SIDEWAYS') P;
Query failed — Snowflake returned an error
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.

One thing to watch

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.

Query
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;
Result20 rows · 6 columns · scroll →
SEQKEYPATHINDEXVALUE_TYPEVALUE
1amountamountNULLDECIMAL4200
1devicedeviceNULLOBJECT{ "os": "windows", "type": "desktop" }
1osdevice.osNULLVARCHAR"windows"
1typedevice.typeNULLVARCHAR"desktop"
1eventeventNULLVARCHAR"purchase"
1itemsitemsNULLARRAY[ { "price": 300, "qty": 8, "sku": "A-100" }, { "price": 450, "qty": 4, "sku": "B-220" } ]
1NULLitems[0]0OBJECT{ "price": 300, "qty": 8, "sku": "A-100" }
1priceitems[0].priceNULLDECIMAL300
1qtyitems[0].qtyNULLINTEGER8
1skuitems[0].skuNULLVARCHAR"A-100"
1NULLitems[1]1OBJECT{ "price": 450, "qty": 4, "sku": "B-220" }
1priceitems[1].priceNULLINTEGER450
1qtyitems[1].qtyNULLINTEGER4
1skuitems[1].skuNULLVARCHAR"B-220"
1tagstagsNULLARRAY[ "priority", "repeat" ]
1NULLtags[0]0VARCHAR"priority"
1NULLtags[1]1VARCHAR"repeat"
1useruserNULLOBJECT{ "id": 101, "name": "Northwind Traders" }
1iduser.idNULLINTEGER101
1nameuser.nameNULLVARCHAR"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.

Query
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;
Result1 row · 5 columns
ALL_NODESOBJECT_NODESARRAY_NODESLEAF_NODESTOP_LEVEL_KEYS_ONLY
2042146

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.

Query
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;
Result1 row · 3 columns
ONE_LEVELRECURSIVE_RECURSIVE_LEAVES_ONLY
62014

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.

Query
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;
Result5 rows · 3 columns
NODE_TYPEHOW_MANYIN_HOW_MANY_EVENTS
VARCHAR284
INTEGER144
OBJECT144
ARRAY84
DECIMAL74

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.

Query
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;
Result7 rows · 3 columns
EVENT_IDPATHSKU
1items[0].skuA-100
1items[1].skuB-220
2items[0].skuC-310
3items[0].skuA-100
4items[0].skuD-400
4items[1].skuA-100
4items[2].skuE-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.

Query
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;
Result1 row · 3 columns
VIA_RECURSIVEVIA_DIRECTSUM_OF_SIZES
777

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.

Query
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;
Result14 rows · 3 columns
EVENT_IDSKUTAG
1A-100priority
1A-100repeat
1B-220priority
1B-220repeat
2C-310new
4A-100enterprise
4A-100priority
4A-100repeat
4D-400enterprise
4D-400priority
4D-400repeat
4E-505enterprise
4E-505priority
4E-505repeat

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.

Query
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;
Result4 rows · 5 columns
EVENT_IDITEMSTAGSIF_IT_ADDEDWHAT_IT_ACTUALLY_IS
12244
21121
31010
43369

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.

Why nobody catches it

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.

Query
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;
Result1 row · 4 columns
CROSS_ROWSSUM_OF_PRODUCTSSUM_OF_SUMSEVENTS_SURVIVING
1414133

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.

Query
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;
Result1 row · 3 columns
CORRECT_TOTALAFTER_ONE_FLATTENAFTER_TWO_FLATTENS
15840.5038540.50100940.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.

The fix is the same as last time

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.

Query
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;
Result1 row · 4 columns
ITEMS_OUTER_ONLYTAGS_OUTER_ONLYBOTH_OUTEREVENTS_TOTAL
3444

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.

Query
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;
Result3 rows · 4 columns
EVENT_IDITEM_INDEXKEYVALUE
20price296.83
20qty3
20sku"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.

Query
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;
Result1 row · 4 columns
ROWS_TOTALEVENTSDISTINCT_ITEM_KEYSITEM_ROWS
21437

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.

Query
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;
Result3 rows · 4 columns
KEYTIMES_SEENITEM_ROWS_TOTALPRESENT_ON_EVERY_ITEM
price77TRUE
qty77TRUE
sku77TRUE

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'.

Query
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;
Result7 rows · 3 columns
EVENT_IDINDEXSKU
10A-100
11B-220
20C-310
30A-100
40D-400
41A-100
42E-505

Seven rows with an INDEX and a sku, which is exactly what FLATTEN(INPUT => PAYLOAD:items) gave us earlier.

Query
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;
Result1 row · 3 columns
VIA_PATH_ARGVIA_COLONSUM_OF_SIZES
777

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.

Query
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;
Result25 rows · 5 columns
PATHTIMES_SEENIN_EVENTSDISTINCT_TYPESA_TYPE
amount443DECIMAL
device331OBJECT
device.os331VARCHAR
device.type331VARCHAR
event441VARCHAR
items441ARRAY
items[0]441OBJECT
items[0].price441DECIMAL
items[0].qty441INTEGER
items[0].sku441VARCHAR
items[1]221OBJECT
items[1].price221INTEGER
items[1].qty221INTEGER
items[1].sku221VARCHAR
items[2]111OBJECT
items[2].price111DECIMAL
items[2].qty111INTEGER
items[2].sku111VARCHAR
tags441ARRAY
tags[0]331VARCHAR
tags[1]221VARCHAR
tags[2]111VARCHAR
user441OBJECT
user.id441INTEGER
user.name441VARCHAR

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.

Query
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;
Result15 rows · 4 columns
PATH_SHAPETIMES_SEENIN_EVENTSDISTINCT_TYPES
amount443
device331
device.os331
device.type331
event441
items441
items[*]741
items[*].price742
items[*].qty741
items[*].sku741
tags441
tags[*]631
user441
user.id441
user.name441

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.

Query
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;
Result4 rows · 4 columns
PATH_SHAPEIN_EVENTSEVENTS_TOTALIN_ALL_OF_THEM
device34FALSE
device.os34FALSE
device.type34FALSE
tags[*]34FALSE

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.

Query
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;
Result15 rows · 5 columns
PATH_SHAPEDEPTHIN_EVENTSNODESTYPES_SEEN
amount144[ "VARCHAR", "INTEGER", "DECIMAL" ]
device133[ "OBJECT" ]
event144[ "VARCHAR" ]
items144[ "ARRAY" ]
items[*]147[ "OBJECT" ]
tags144[ "ARRAY" ]
tags[*]136[ "VARCHAR" ]
user144[ "OBJECT" ]
device.os233[ "VARCHAR" ]
device.type233[ "VARCHAR" ]
items[*].price247[ "INTEGER", "DECIMAL" ]
items[*].qty247[ "INTEGER" ]
items[*].sku247[ "VARCHAR" ]
user.id244[ "INTEGER" ]
user.name244[ "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 KEY holding the key name and TYPEOF(VALUE) telling you what is underneath.
  • MODE takes 'ARRAY', 'OBJECT' or 'BOTH', and 'BOTH' is the default. MODE => 'ARRAY' over an object returns no rows and no error.
  • RECURSIVE => TRUE returns 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 PATH column says where a row came from. On an array element KEY is NULL and INDEX is 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.50 to 100940.50 with no error anywhere.
  • OUTER => TRUE on 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 as PAYLOAD:items, and it can be built as a string.
  • GROUP BY on the PATH of a recursive flatten, with the array indexes collapsed, is an inferred schema with optional fields and per-path types.
Next in this series

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.