我正在尝试在PostgreSQL 9.4中搜索JSONB对象。我的问题类似于this thread。
但是我的数据结构略有不同,这导致了我的问题。我的数据结构如下:
[
{"id":1, "msg":"testing"}
{"id":2, "msg":"tested"}
{"id":3, "msg":"nothing"}
]
我希望通过msg(RegEx,LIKE,=等)在该数组中搜索匹配的对象。更具体地说,我希望表中JSONB字段有一个对象的所有行都有一个与我的请求匹配的“msg”。
以下显示的结构类似于我所拥有的结构:
SELECT * FROM
(SELECT
'[{"id":1,"msg":"testing"},{"id":2,"msg":"tested"},{"id":3,"msg":"nothing"}]'::jsonb as data)
as jsonbexample;
这显示尝试实现上述链接的答案,但不起作用(返回0行):
SELECT * FROM
(SELECT
'[{"id":1,"msg":"testing"},{"id":2,"msg":"tested"},{"id":3,"msg":"nothing"}]'::jsonb as data)
as jsonbexample
WHERE
(data #>> '{msg}') LIKE '%est%';
任何人都可以解释如何搜索JSONB数组吗?在上面的示例中,我想在表中找到其“data”JSONB字段包含“msg”匹配的对象的任何行(例如,LIKE'%est%')。
此代码创建一个新类型(稍后需要):
CREATE TYPE AlertLine AS (id INTEGER, msg TEXT);
然后你可以使用它来用JSONB_POPULATE_RECORDSET来拆分列:
SELECT * FROM
JSONB_POPULATE_RECORDSET(
null::AlertLine,
(SELECT '[{"id":1,"msg":"testing"},
{"id":2,"msg":"tested"},
{"id":3,"msg":"nothing"}]'::jsonb
as data
)
) as jsonbex;
输出:
id | msg
----+---------
1 | testing
2 | tested
3 | nothing
并加入限制:
SELECT * FROM
JSONB_POPULATE_RECORDSET(
null::AlertLine,
(SELECT '[{"id":1,"msg":"testing"},
{"id":2,"msg":"tested"},
{"id":3,"msg":"nothing"}]'::jsonb
as data)
) as jsonbex
WHERE
msg LIKE '%est%';
输出:
id | msg
---+---------
1 | testing
2 | tested
因此问题的一部分仍然是如何将其作为另一个查询中的子句。
所以,如果上面代码的输出= x,我该怎么问:
SELECT * FROM mytable WHERE x > (0 rows);
答案 0 :(得分:2)
您可以使用exists
:
SELECT * FROM
(SELECT
'[{"id":1,"msg":"testing"},{"id":2,"msg":"tested"},{"id":3,"msg":"nothing"}]'::jsonb as data)
as jsonbexample
WHERE
EXISTS (SELECT 1 FROM jsonb_array_elements(data) as j(data) WHERE (data#>> '{msg}') LIKE '%est%');
如下面评论中所述查询表格:
SELECT * FROM atable
WHERE EXISTS (SELECT 1 FROM jsonb_array_elements(columnx) as j(data) WHERE (data#>> '{msg}') LIKE '%est%');