Postgres JSONB: 查询 JSON 数组中的值
Postgres JSONB: query values in JSON array
Postgres 9.4
我有一条 JSONB 值如下的记录:
{
"attributeA": 1,
"attributeB": "Foo",
"arrayAttribute": [
{"attributeC": 95, "attributeD": 5},
{"attributeC": 105, "attributeD": 5}
]
}
我想写一个查询:
找到 attributeA = 1,attributeB = 'Foo' 的任何项目,并且对于 arrayAttribute 数组中的每个元素,attributeC 在某个值 X 的 10 点范围内。因此,如果 X 为 100,则以上记录将匹配(95 和 105 都在 100 的 10 分之内)。
不幸的是,我真的很难理解 JSONB 查询语法。执行此操作的最佳方法是什么?
Postgres documentation regarding json 真的很棒。至于搜索查询方法,重要的是要知道 ->>
returns text
和 ->
returns json(b)
.
查询可以是以下内容:
select * from json js,jsonb_array_elements(data->'arrayAttribute') as array_element
where (js.data->>'attributeA')::integer = 1
and js.data->>'attributeB' = 'Foo'
and (array_element->>'attributeC')::integer >= (100-5)
and (array_element->>'attributeC')::integer <= (100+5);
如果你想 select 按索引的特定数组元素,在你的情况下查询将如下:
SELECT * FROM json js,jsonb_extract_path(data,'arrayAttribute') AS entireArray
WHERE (entireArray -> 0 ->> 'attributeC')::integer = 95
AND (entireArray -> 1 ->> 'attributeC')::integer = 105;
Postgres 9.4
我有一条 JSONB 值如下的记录:
{
"attributeA": 1,
"attributeB": "Foo",
"arrayAttribute": [
{"attributeC": 95, "attributeD": 5},
{"attributeC": 105, "attributeD": 5}
]
}
我想写一个查询:
找到 attributeA = 1,attributeB = 'Foo' 的任何项目,并且对于 arrayAttribute 数组中的每个元素,attributeC 在某个值 X 的 10 点范围内。因此,如果 X 为 100,则以上记录将匹配(95 和 105 都在 100 的 10 分之内)。
不幸的是,我真的很难理解 JSONB 查询语法。执行此操作的最佳方法是什么?
Postgres documentation regarding json 真的很棒。至于搜索查询方法,重要的是要知道 ->>
returns text
和 ->
returns json(b)
.
查询可以是以下内容:
select * from json js,jsonb_array_elements(data->'arrayAttribute') as array_element
where (js.data->>'attributeA')::integer = 1
and js.data->>'attributeB' = 'Foo'
and (array_element->>'attributeC')::integer >= (100-5)
and (array_element->>'attributeC')::integer <= (100+5);
如果你想 select 按索引的特定数组元素,在你的情况下查询将如下:
SELECT * FROM json js,jsonb_extract_path(data,'arrayAttribute') AS entireArray
WHERE (entireArray -> 0 ->> 'attributeC')::integer = 95
AND (entireArray -> 1 ->> 'attributeC')::integer = 105;