我正在嘗試將 jsonb 列中的每一行轉換為我定義的型別,但我似乎無法到達那里。
我有一個應用程式可以從The Guardian Open Platform中抓取文章并將回應(作為 jsonb)轉儲到一個名為“body”的列中。其他列是順序 ID 和從回應有效負載中提取的時間戳,可幫助我的應用程式僅抓取新資料。
我想將回應轉儲資料移動到一個正確定義的表中,因為我知道回應的架構,我已經定義了一個型別 ( my_type)。
我一直在指9.16。Postgres 檔案中的JSON 函式和運算子。我可以得到一條記錄作為我的型別:
select * from jsonb_populate_record(null::my_type, (select body from data_ingestion limit 1));
產生
| ID | 型別 | 部分ID | ... |
|---|---|---|---|
| example_id | 示例型別 | example_section_id | ... |
(為簡潔而縮寫)
如果我洗掉限制,我會收到一個錯誤,這是有道理的:子查詢將提供多行jsonb_populate_record,只需要一個行。
我可以讓它做多行,但結果沒有分成幾列:
select jsonb_populate_record(null::my_type, body) from reviews_ingestion limit 3;
產生:
| jsonb_populate_record |
|---|
| (example_id_1,example_type_1,example_section_id_1,...) |
| (example_id_2,example_type_2,example_section_id_2,...) |
| (example_id_3,example_type_3,example_section_id_3,...) |
這有點奇怪,我本來希望看到列名;這畢竟是提供型別的重點。
我知道我可以通過使用 Postgres JSON 查詢功能來做到這一點,例如
select
body -> 'id' as id,
body -> 'type' as type,
body -> 'sectionId' as section_id,
...
from reviews_ingestion;
這有效,但似乎很不優雅。另外,我失去的資料型別。
我還考慮將列中的所有行聚合body到一個 JSON 陣列中,以便能夠將其提供給,jsonb_populate_recordset但這似乎是一種愚蠢的方法,并且不太可能具有性能。
有沒有辦法使用 Postgres 函式來實作我想要的?
uj5u.com熱心網友回復:
也許你需要這個 - 將my_type記錄分成幾列:
select (jsonb_populate_record(null::my_type, body)).*
from reviews_ingestion
limit 3;
-- or whatever other query clauses here
即選擇所有這些my_type記錄。所有列名和型別都已就位。
這是一個插圖。我的自定義型別是delmet和 CTOt遠程模仿data_ingestion.
create type delmet as (x integer, y text, z boolean);
with t(i, j, k) as
(
values
(1, '{"x":10, "y":"Nope", "z":true}'::jsonb, 'cats'),
(2, '{"x":11, "y":"Yep", "z":false}', 'dogs'),
(3, '{"x":12, "y":null, "z":true}', 'parrots')
)
select i, (jsonb_populate_record(null::delmet, j)).*, k
from t;
結果:
| 一世 | X | 是 | z | 克 |
|---|---|---|---|---|
| 1 | 10 | 不 | 真的 | 貓 |
| 2 | 11 | 是的 | 錯誤的 | 小狗 |
| 3 | 12 | 真的 | 鸚鵡 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/344802.html
