如何在 JSON 内分解多个列表值 JSON,并在 Snowflake 中横向展平?

How to explode several list values JSON within JSON with lateral flatten in Snowflake?

我有一个带有 24 个 JSON 的变体 table,如下所示(每行一个):

{
  "context": "marketplace",
  "metadata": {
    "app_version": "1.0.4 (166)",
  },
  "params": {
    "filter": {
      "brands": [],
      "categories": [
        "f28c7c9f-09ae-4218-821a-bec344998289"
      ],
      "manufacturers": [],
      "page": 1,
      "product_name": "",
    },
    "page": "product_list",
    "results": 3
  },
  "user_id": "6443a2db-4526-4fc5-8084-290fc78e5336"
}

我希望所有内容都成行展开。我已经设法拥有了除过滤器之外的所有内容,代码如下:

SELECT data:event::string,
       data:user_id::string,
       data:metadata.app_version::string,
       data:context::string,
       data:params.page::string,
       data:params.filter.page::string,
       data:params.results::string
FROM ods.stg_tanimis_events

品牌、类别和制造商列表可以为空,但如果是这种情况,我需要一个空值。我想要一个包含以下列的 table:

event, user_id, app_version, context, param_page, filter_page, results, manufacturer, brand, category

我试过几次横向展平都没有成功:

select * FROM table
, lateral flatten (data:params:filter:categories) j2;

select * FROM table
, lateral flatten (data:params:filter.brands) j1

select * FROM table
, lateral flatten (data:params:filter:brands) j1
, lateral flatten (data:params:filter:categories) j2;

select user_id, filter, flat.*
from table
, lateral flatten(parse_json(filter)) flat;


WITH j as (
SELECT *
FROM table
, lateral flatten(data:params:filter))

SELECT *
from j,
lateral flatten (j.value) j2;

无论哪种方式,我得到 8 行或 0 行,或错误。我怎么能做到?谢谢

在您的示例数据中,“品牌”中没有数据,这意味着除非您在 lateral flatten 语句中添加 , OUTER => TRUE ,否则任何针对它的扁平化都将 return 没有任何意义。更像是这样的:

SELECT table.data:event::string,
   table.data:user_id::string,
   table.data:metadata.app_version::string,
   table.data:context::string,
   table.data:params.page::string,
   table.data:params.filter.page::string,
   table.data:params.results::string,
   j1.value::string as brands,
   j2.value::string as categories
FROM table
, lateral flatten (data:params:filter:brands, OUTER => TRUE) j1
, lateral flatten (data:params:filter:categories, OUTER => TRUE) j2;

对于任何空的展平数组,这将类似于基数 table 和 return NULL 的 LEFT JOIN。