正则表达式 – 在PostgreSQL中搜索jsonb数组

前端之家收集整理的这篇文章主要介绍了正则表达式 – 在PostgreSQL中搜索jsonb数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在Postgresql 9.4中搜索JSONB对象.我的问题类似于 this thread.

但是我的数据结构略有不同,这导致了我的问题.我的数据结构如下:

  1. [
  2. {"id":1,"msg":"testing"}
  3. {"id":2,"msg":"tested"}
  4. {"id":3,"msg":"nothing"}
  5. ]

我想通过msg(RegEx,LIKE,=等)搜索该数组中的匹配对象.更具体地说,我希望表中JSONB字段有一个对象的所有行都有一个与我的请求匹配的“msg”.

以下显示了与我的结构类似的结构:

  1. SELECT * FROM
  2. (SELECT
  3. '[{"id":1,"msg":"testing"},{"id":2,"msg":"tested"},{"id":3,"msg":"nothing"}]'::jsonb as data)
  4. as jsonbexample;

显示了尝试实现上述链接的答案,但不起作用(返回0行):

  1. SELECT * FROM
  2. (SELECT
  3. '[{"id":1,"msg":"nothing"}]'::jsonb as data)
  4. as jsonbexample
  5. WHERE
  6. (data #>> '{msg}') LIKE '%est%';

任何人都可以解释如何搜索JSONB数组?在上面的例子中,我想在表中找到其“data”JSONB字段包含“msg”匹配的对象的任何行(例如,LIKE’%est%’).

更新

代码创建一个新类型(以后需要):

  1. CREATE TYPE AlertLine AS (id INTEGER,msg TEXT);

然后你可以用它来用JSONB_POPULATE_RECORDSET来拆分列:

  1. SELECT * FROM
  2. JSONB_POPULATE_RECORDSET(
  3. null::AlertLine,(SELECT '[{"id":1,"msg":"nothing"}]'::jsonb
  4. as data
  5. )
  6. ) as jsonbex;

输出

  1. id | msg
  2. ----+---------
  3. 1 | testing
  4. 2 | tested
  5. 3 | nothing

并加入限制:

  1. SELECT * FROM
  2. JSONB_POPULATE_RECORDSET(
  3. null::AlertLine,"msg":"nothing"}]'::jsonb
  4. as data)
  5. ) as jsonbex
  6. WHERE
  7. msg LIKE '%est%';

输出

  1. id | msg
  2. ---+---------
  3. 1 | testing
  4. 2 | tested

所以问题的一部分仍然是如何将其作为另一个查询中的子句.

那么,如果上面代码输出= x,我该怎么问:

  1. SELECT * FROM mytable WHERE x > (0 rows);
你可以使用exists:
  1. SELECT * FROM
  2. (SELECT
  3. '[{"id":1,"msg":"nothing"}]'::jsonb as data)
  4. as jsonbexample
  5. WHERE
  6. EXISTS (SELECT 1 FROM jsonb_array_elements(data) as j(data) WHERE (data#>> '{msg}') LIKE '%est%');

查询表格,如下面的评论中所述:

  1. SELECT * FROM atable
  2. WHERE EXISTS (SELECT 1 FROM jsonb_array_elements(columnx) as j(data) WHERE (data#>> '{msg}') LIKE '%est%');

猜你在找的正则表达式相关文章