sql—过滤掉postgresql中包含特定条件的jsonb数组元素

vsmadaxz  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(440)

我有一个表:“events”和jsonb列“logs”。
用以下日志记录事件:

[
{state: "something", recorded_at: "some-timestamp"},
{state: "other", recorded_at: "some-other-timestamp"},
{nothing: "interesting", recorded_at: "timestamp"}
]

我要执行此查询:
选择带有已筛选出不带“state”键的条目的日志的记录
我并不想构造where查询条件,我只想过滤掉返回结果中的“日志”。
怎么做?

6fe3ivhb

6fe3ivhb1#

去获取那些 logs 对象有键 'state' ,您可以使用 not exists 以及 jsonb_array_elements() :

select e.*
from events e
where not exists(select 1 from jsonb_array_elements(e.logs) x(obj) where obj ? 'state')

另一方面,如果您不希望筛选出记录,而是希望筛选出具有键的嵌套json对象 'state' :

select e.*, x.new_logs
from events e
cross join lateral (
    select jsonb_agg(x.obj order by x.ord) new_logs
    from jsonb_array_elements(e.obj) with ordinality x(obj, ord)
    where not obj ? 'state'
) x

相关问题