在 PostgresQL 中查询 JSONB 字段数组

Querying an array of JSONB fields in PostgresQL

我不知道如何查询 PostgreSQL JsonB 数据类型。我有一个简单的 table 结构:

CREATE TABLE myTable (id BIGINT PRIMARY KEY, answers JSONB)

“答案”列中的所有 Json 篇文档的格式为:

[
{"R" : "aaa", "V" : 25},
{"R" : "aaa", "V" : 31}, 
{"R" : "bbb", "V" : 38}
...
]

列表中可以有很多元素,但所有元素都会有一个“R”和一个“V”项。

我想使用 SQL、列表 ID 和包含所有“V”的 table 列表检索 table,其中“R”==“aaa” .

对于上面的例子,我会得到:

有什么想法吗?任何帮助表示感谢我花了一些时间在网络上可用的 JSon 路径示例上,但没有找到类似的东西。

提前致谢。

我会展开元素,按 R 过滤,然后重新聚合。这导致 int[] 数组。

select m.id, array_agg((a.obj->>'V')::int) as vvals
  from mytable m
 cross join lateral jsonb_array_elements(answers) as a(obj)
 where a.obj->>'R' = 'aaa';

全部为纯 JSONB:

SELECT id, jsonb_agg(ans->'V') FROM (
  SELECT id, jsonb_array_elements(answers) AS ans
  FROM myTable
) zz
WHERE ans->'R' = '"aaa"'
GROUP BY id;

注意:仅限 Postgresql 12+

使用 jsonpath:

WITH data(id, json_arr) AS (
    VALUES (1, $$[
      { "R": "aaa", "V": 25 },
      { "R": "aaa", "V": 31 },
      { "R": "bbb", "V": 38 }
    ]$$::JSONB)
)
SELECT id,
       -- $[*]             : "inside the top level array"
       -- ? (@.R == "aaa") : "keep only when the "R" key's value is "aaa""
       -- .V               : "select the "V" key of those elements"
       jsonb_path_query_array(json_arr, '$[*] ? (@.R == "aaa").V')
FROM data

returns:

+--+----------------------+
|id|jsonb_path_query_array|
+--+----------------------+
|1 |[25, 31]              |
+--+----------------------+

注意:您也可以使用

jsonb_path_query_array(
    json_arr,
    '$[*] ? (@.R == $r_value).V',
    '{"r_value": "aaa"}'  -- pass the 'r_value' to the query above
)