2016-05-16 93 views
3

我在AWS Redshift数据库中有一个字段varchar(65000)列,用于存储JSON字符串。 JSON键/值对经常更改,我需要能够运行每日报告以从列中检索所有键/值数据。查询AWS Redshift中的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; 

回答

3

使用普通SQL使用当前架构无法做到您想要的。

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

选项A

加载整个JSON在您的应用程序,分析它,并获取所需的信息这种方式。

选项B

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

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

+0

感谢您的回答GuiSim,这是很好的知道。选项B将为我所需要的:)工作 – fez