【问题标题】:Bigquery STRUCT ARRAY IGNORE NULLS TO JSONBigquery STRUCT ARRAY IGNORE NULLS TO JSON
【发布时间】:2023-01-13 03:13:11
【问题描述】:

我正在从 Bigquery 生成一个 .json 文件输出,并尝试仅在“属性”数组/结构中包含 NON NULL 值。我的以下查询生成了包含所有值(包括 NULL)的 STRUCT 字段。

WITH t0 AS (
    SELECT 'd1' AS product_code, 'AA|BB' AS f1, '11|22|33' AS f2, NULL AS f3
    UNION ALL
    SELECT 'd2' AS product_code, 'ZZ' AS f1, '55|66' AS f2, 1 AS f3
)
,t1 AS (
    SELECT
        product_code
        ,SPLIT(f1, '|') AS f1
        ,SPLIT(f2, '|') AS f2
        ,f3
    FROM t0
)
SELECT
    product_code
    ,STRUCT(f1, f2, f3) AS attributes --IGNORE NULLS ?
FROM t1

查询以 json 格式返回:

[
  {
    "product_code": "d1",
    "attributes": {
      "f1": [
        "AA",
        "BB"
      ],
      "f2": [
        "11",
        "22",
        "33"
      ],
      "f3": null
    }
  },
  {
    "product_code": "d2",
    "attributes": {
      "f1": [
        "ZZ"
      ],
      "f2": [
        "55",
        "66"
      ],
      "f3": "1"
    }
  }
]

如何从 d1 数组 (null) 中删除 f3 但将其保留在 d2 中?

【问题讨论】:

    标签: sql arrays json struct google-bigquery


    【解决方案1】:

    试图复制您的问题,但没有直接的方法从 Bigquery 中的 d1 数组中删除 f3。作为替代方案,您可以参考此 SO post,它使用 node.js 从 JSON 对象中删除空值。您可以将此 JSON 解析器应用于 Bigquery 的查询返回(JSON 格式)。

    【讨论】:

      【解决方案2】:

      使用 JavaScript UDF 输出 JSON(不含空值),如下所示:

      CREATE TEMP FUNCTION
        stripNulls(input JSON)
        RETURNS JSON
        LANGUAGE js AS r"""
        const out = {};
      
        Object.keys(input).forEach(key => {
            const value = input[key];
            if (value !== null) {
                out[key] = value;
            }
        });
      
        return out;
      """;
      
      SELECT stripNulls(TO_JSON(STRUCT('a' AS foo, 'b' AS bar, NULL AS biz)));
      
      --> {"bar":"b","foo":"a"}
      

      【讨论】:

        猜你喜欢
        • 2020-09-22
        • 1970-01-01
        • 2017-12-07
        • 2020-12-09
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多