Postgres 9.4
我有一个像这样的 JSONB 值的记录:
{
"attributeA": 1,
"attributeB": "Foo",
"arrayAttribute": [
{"attributeC": 95, "attributeD": 5},
{"attributeC": 105, "attributeD": 5}
]
}
Run Code Online (Sandbox Code Playgroud)
我想写一个查询,它说:
查找其中 attributeA = 1、attributeB = 'Foo' 的任何项目,并且对于 arrayAttribute 数组中的每个元素,attributeC 在某个值 X 的 10 点范围内。因此,如果 X 为 100,则上述记录将匹配(95 和105 与 100 相差 10 分)。
不幸的是,我真的在 JSONB 查询语法上苦苦挣扎。做到这一点的最佳方法是什么?
Postgres关于 json 的文档真的很棒。至于搜索查询方法,重要的是要知道->>返回text和->返回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);
Run Code Online (Sandbox Code Playgroud)
如果要按索引选择特定的数组元素,在您的情况下,查询将如下所示:
SELECT * FROM json js,jsonb_extract_path(data,'arrayAttribute') AS entireArray
WHERE (entireArray -> 0 ->> 'attributeC')::integer = 95
AND (entireArray -> 1 ->> 'attributeC')::integer = 105;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1239 次 |
| 最近记录: |