使用数组字段查询 JSONB

querying JSONB with array fields

如果我有一个名为 valuejsonb 列,其中包含以下字段:

{"id": "5e367554-bf4e-4057-8089-a3a43c9470c0",
 "tags": ["principal", "reversal", "interest"],,, etc}

我如何找到包含给定标签的所有记录,例如: 如果给出:["reversal", "interest"] 它应该找到所有带有 "reversal" 或 "interest" 或两者的记录。

到目前为止,我的实验让我感到厌恶:

select value from account_balance_updated 
where value @> '{}' :: jsonb and value->>'tags' LIKE '%"principal"%';

当然这是完全错误和低效的

假设你使用的是PG 9.4+,你可以使用jsonb_array_elements()函数:

SELECT DISTINCT abu.*
FROM account_balance_updated abu,
     jsonb_array_elements(abu.value->'tags') t
WHERE t.value <@ '["reversal", "interest"]'::jsonb;

事实证明,您可以使用此处描述的很酷的 jsonb 运算符:

https://www.postgresql.org/docs/9.5/static/functions-json.html

所以原始查询不必改变太多:

select value from account_balance_updated 
where value @> '{}' :: jsonb and value->'tags' ?| array['reversal', 'interest'];

在我的例子中,我还需要转义 ? (??|),因为我使用所谓的 "prepared statement",您将查询字符串和参数传递给 jdbc问号就像参数的占位符:

https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html