2016-05-16 51 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