【问题标题】:Extract keys and values from json string in bigquery where there is no specified key in the json document在 json 文档中没有指定键的 bigquery 中从 json 字符串中提取键和值
【发布时间】:2019-07-20 02:23:42
【问题描述】:

我在 bigquery 中有一个表,其中有对象,并且对于每个对象,我都有一些字符串化的 json。在 json 中,示例行如下所示:

{
    "ObjectID": "1984931229",
    "indexed_abstract": "{\"IndexLength\":123,\"InvertedIndex\":{\"Twenty-seven\":[0],\"metastatic\":[1,45],\"breast\":[2],\"adenocarcinoma\":[3],\"patients,\":[4]}}" 
}

indexed_abstract 中我们有一个InvertedIndex,其中包含一些关键字以及这些关键字在ObjectID 中出现的次数。

现在我想通过使用 bigquery 解析 json 来访问字符串化的 json,并且对于每个 ObjectID,我想创建一个嵌套字段,其中包含关键字、对应数组和对应数组的长度。

例如,在这种情况下,输出将如下所示:

+------------+----------------+---------------+-------------------+
|  ObjectID  |  keyword.key   | keyword.count | keyword.positions |
+------------+----------------+---------------+-------------------+
| 1984931229 | Twenty-seven   |             1 | [0]               |
|            | metastatic     |             2 | [1,45]            |
|            | breast         |             1 | [2]               |
|            | adenocarcinoma |             1 | [3]               |
|            | patients       |             1 | [4]               |
+------------+----------------+---------------+-------------------+

我知道我可以使用 JSON_EXTRACT 函数,但我不确定我在倒排索引中访问关键字和与它们对应的数组的键是什么。

【问题讨论】:

    标签: json google-bigquery json-extract


    【解决方案1】:

    以下是 BigQuery 标准 SQL

    #standardSQL
    SELECT ObjectID, 
      ARRAY(
        SELECT AS STRUCT 
          key, 
          ARRAY_LENGTH(SPLIT(value)) `count`, 
          value positions 
        FROM UNNEST(REGEXP_EXTRACT_ALL(JSON_EXTRACT(indexed_abstract, '$.InvertedIndex'), r'"[^"]+":\[[\d,]*?]')) pair,
        UNNEST([STRUCT(REPLACE(SPLIT(pair, ':')[OFFSET(0)], '"', '') AS key, SPLIT(pair, ':')[OFFSET(1)] AS value)])
      ) keyword
    FROM `project.dataset.table`
    

    如果适用于您问题的样本数据 - 结果是

    Row ObjectID    keyword.key     keyword.count   keyword.positions    
    1   1984931229  Twenty-seven    1               [0]  
                    metastatic      2               [1,45]   
                    breast          1               [2]  
                    adenocarcinoma  1               [3]  
                    patients        1               [4]  
    

    更新 Op 的评论 - 我想知道是否要将位置设为数组(重复字段),我该怎么做?

    更改只需一行

      SPLIT(REGEXP_REPLACE(value, r'\[|]', '')) positions 
    

    【讨论】:

    • 哇,我好复杂!不过谢谢。我想知道如果我想让位置成为一个数组(一个重复的字段),我该怎么做?
    • 顺便说一句,我再次阅读了您的评论,您的额外问题非常简单 - 所以我将更新我的答案 - 但我现在正在继续 - 所以它会在一天晚些时候:o)
    • 其实它很简单,打字不多,所以我现在就把它添加到我的答案中
    • 我刚才也从这里尝试了你的答案,这也有效! stackoverflow.com/questions/46199823/… 。谢谢!
    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 2016-05-27
    • 2023-01-13
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多