我正在尝试在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;
SELECT * FROM (SELECT '[{"id":1,"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":"nothing"}]'::jsonb as data ) ) as jsonbex;
输出:
id | msg ----+--------- 1 | testing 2 | tested 3 | nothing
并加入限制:
SELECT * FROM JSONB_POPULATE_RECORDSET( null::AlertLine,"msg":"nothing"}]'::jsonb as data) ) as jsonbex WHERE msg LIKE '%est%';
输出:
id | msg ---+--------- 1 | testing 2 | tested
所以问题的一部分仍然是如何将其作为另一个查询中的子句.
SELECT * FROM mytable WHERE x > (0 rows);
你可以使用exists:
原文链接:https://www.f2er.com/regex/357312.htmlSELECT * FROM (SELECT '[{"id":1,"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%');