[英]Querying an array of objects in JSONB
I have a table with a column of the data type JSONB.我有一个表,其中有一列数据类型为 JSONB。 Each row in the column has a JSON that looks something like this:列中的每一行都有一个 JSON,如下所示:
[
{
"A":{
"AA": "something",
"AB": false
}
},
{
"B": {
"BA":[
{
"BAAA": [1,2,3,4]
},
{
"BABA": {
....
}
}
]
}
}
]
Note: the JSON is a complete mess of lists and objects, and it has a total of 300 lines.注意:JSON 是一堆乱七八糟的列表和对象,总共有 300 行。 Not my data but I am stuck with it.不是我的数据,但我坚持下去。 :( :(
I am using postgresql version 12我正在使用 postgresql 版本 12
How would I write the following queries:我将如何编写以下查询:
You can find the AB = false rows with a JSON Path query:您可以使用 JSON 路径查询找到 AB = false 行:
select *
from test
where data @@ '$[*].A.AB == false'
If you don't know where exactly the key AB
is located, you can use:如果您不知道密钥AB
的确切位置,您可以使用:
select *
from test
where data @@ '$[*].**.AB == false'
To display all elements from the array as rows, you can use:要将数组中的所有元素显示为行,您可以使用:
select id, e.*
from test
cross join jsonb_array_elements(jsonb_path_query_first(data, '$[*].B.BA.BAAA')) with ordinality as e(item, idx)
I include a column "id" as a placeholder for the primary key column, so that the source of the array element can be determined in the output.我包括一个列“id”作为主键列的占位符,以便可以在 output 中确定数组元素的来源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.