【问题标题】:Querying JSON Strings in AWS Redshift在 AWS Redshift 中查询 JSON 字符串
【发布时间】:2016-09-12 08:59:02
【问题描述】:

我的 AWS Redshift 数据库中有一个字段 varchar(65000) 列,用于存储 JSON 字符串。 JSON 键/值对经常更改,我需要能够运行每日报告以检索列中的所有键/值数据。

例如:

create table test.json(json varchar(65000));
insert into test.json 
select '{"animal_id": 1, "name": "harry", "animal_type": "cat", "age": 2, "location": "oakland"}' union
select '{"animal_id": 2, "name": "louie","animal_type": "dog", "age": 4}' union 
select '{"animal_id": 3, "gender": "female"}' union
select '{"animal_id": 4, "size": "large"}' ;

使用上面的数据,我可以编写下面的查询来获取我知道的属性,但是如果明天添加一个新属性,我的报告查询将不会选择那个新的键/值对。有什么方法可以在这个表上做一个SELECT * 类型的查询吗?

SELECT
      json_extract_path_text(JSON,'animal_id') animal_id,
      json_extract_path_text(JSON,'name') name,
      json_extract_path_text(JSON,'animal_type') animal_type,
      json_extract_path_text(JSON,'location') location,
      json_extract_path_text(JSON,'age') age,
      json_extract_path_text(JSON,'gender') gender,
      json_extract_path_text(JSON,'size') size
    FROM test.json
    ORDER BY animal_id;

【问题讨论】:

    标签: json amazon-web-services amazon-redshift


    【解决方案1】:

    使用当前模式和普通 SQL 是不可能做你想做的事的。

    如果您可以在创建 SQL 查询时拥有应用程序逻辑,则可以动态创建 SELECT 语句。

    选项 A

    在您的应用中加载整个 JSON,对其进行解析并以这种方式获取所需的信息。

    选项 B

    在数据库中存储值时,解析 JSON 对象并将发现的键添加到另一个表中。查询您的 Redshift 集群时,加载此值列表并使用此信息生成适当的 SQL 语句。

    希望这些解决方法可以应用于您的情况。

    【讨论】:

    • 感谢您的回答 GuiSim,很高兴知道这一点。选项 B 将满足我的需要:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 2020-10-12
    • 2019-02-17
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多