我正在努力使用JSONB_PATH_EXISTSPostgres 功能
我正在使用 PG 12 并遵循此檔案:https : //www.postgresql.org/docs/12/functions-json.html
使用以下請求(在 DBFiddle 上測驗:https : //dbfiddle.uk/ ? rdbms = postgres_12 & fiddle = d5aa984182852438c6f71cf5fa70324e ):
select
json
from (
select '{
"fields": {
"foo": true,
"number": 3,
"listnb": [3, 4],
"listenb2": ["3", "4"],
"txt": "hello how are you",
"listtxt": ["hello","how","are", "you", "3"],
"nullval": null
}
}'::jsonb as json
) t
where 1=1
-- Works with 'strict'
AND JSONB_PATH_EXISTS(json -> 'fields' -> 'listtxt', 'strict $ ? (@.type() == "array")')
-- Doesn't work without 'strict'. Why ?
--AND JSONB_PATH_EXISTS(json -> 'fields' -> 'listtxt', '$ ? (@.type() == "array")')
-- Can't add a nested condition on an array element value (syntax error)
--AND JSONB_PATH_EXISTS(json -> 'fields' -> 'listtxt', 'strict $ ? (@.type() == "array" && @[*] ? (@ == "how"))')
;
#1 - 我無法在沒有strict模式的情況下使用type() 函式
它可能與自動展開陣列的松散模式有關,但檔案明確指出在type()呼叫函式時未完成:
如果 JSON 資料不符合預期的模式,松散模式有助于匹配 JSON 檔案結構和路徑運算式。[...] 僅在以下情況下才執行自動解包:
- 路徑運算式包含 type() 或 size() 方法,分別回傳陣列中元素的型別和數量。
- [...]
所以我不明白為什么我們的結果不同
#2 我無法獲得嵌套條件作業(AND示例請求中的第三個)
根據檔案中的示例,語法看起來不錯,但我有一個我不明白的語法錯誤。
感謝您的幫助
uj5u.com熱心網友回復:
如果您將完整的 JSON 值傳遞給函式,則以下操作有效:
where jsonb_path_exists(json, '$ ? (@.fields.listtxt.type() == "array")')
但是我可能只是在jsonb_typeof()沒有路徑查詢的情況下使用
where jsonb_typeof(json -> 'fields' -> 'listtxt') = 'array'
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/317104.html
標籤:json PostgreSQL postgresql-12
