SNOWFLAKE 查询元素数组

SNOWFLAKE querying the array of elements

我正在使用 SNOW_FLAKE 并尝试查询以列名 nested_colmn 下的元素数组形式存储的数据,例如:

nested_colmn
[
  {
    "firstKey": "val1",
    "secondKey": 2555,
    "thirdKey": false,
    "fourthkey": "otrvalue"
  },
  {
    "firstKey": "val2",
    "secondKey": 255221,
    "thirdKey": true,
    "fourthkey": "otrvalu"
  }
]

如果我这样做,上面的数组将作为一个完整的行返回

Select nested_colmn from table_name

现在我只想 query/get 属性列中 firstkey(nested_colmn.firstkey) 的结果。我如何构建查询以从数组中检索单个自定义元素而不是获取所有元素。如果对此有任何想法,请帮助我

注意:我假设您确实希望源 table 将数组作为值,而不是剥离外部数组并将每个元素放入其自己的行中。

首先,使用您的示例数据创建一个测试table:

CREATE OR REPLACE TEMPORARY TABLE table_name (
  nested_colmn  VARIANT
)
AS
  SELECT PARSE_JSON() AS nested_colmn
    FROM VALUES
           ($$
[
  {
    "firstKey": "val1",
    "secondKey": 2555,
    "thirdKey": false,
    "fourthkey": "otrvalue"
  },
  {
    "firstKey": "val2",
    "secondKey": 255221,
    "thirdKey": true,
    "fourthkey": "otrvalu"
  }
]
$$)
;

有了这个,下面是一个示例查询:

SELECT F.VALUE:"firstKey"::VARCHAR AS FIRST_KEY
  FROM table_name T
      ,LATERAL FLATTEN(nested_colmn) F
;

您需要 运行 对数组进行横向展平,然后解析 JSON:

WITH x as (
SELECT array_construct(parse_json('
  {
    "firstKey": "val1",
    "secondKey": 2555,
    "thirdKey": false,
    "fourthkey": "otrvalue"
  }'),parse_json('
  {
    "firstKey": "val2",
    "secondKey": 255221,
    "thirdKey": true,
    "fourthkey": "otrvalu"
  }')) as var)
SELECT p.value:firstKey::varchar
FROM x,
lateral flatten(input => x.var) p;