Aarthi
Aarthi

Reputation: 1521

JSONB nested query postgres rails

I have a jsonb column where I am storing some filtering data. The structure I am storing the data in the column is like the below,

[
      {
        "filter":[
            {
                "key":"first_name",
                "condition":"has_any_value"
            },
            {
                "key":"count_of",
                "value":"1",
                "event_id":"130",
            }
        ]
     },
     {
        "filter":[
            {
                "key":"count_of",
                "value":"1",
                "event_id":"130"
            }
        ],
        "filter_operator":"AND"
     },
     {
        "filter":[
            {
                "key":"user_id",
                "value":"12",
                "condition":"equals"
            },
            {
                "key":"count_of",
                "value":"112",
                "event_id":"130"
        ],
        "filter_operator":"OR"
     }
]

I need to query if the filter JSON contains specific event id(Which may exists in any of the "filter" data), But I can't find a way to query if the specific event Id exists in the structure I have(Array -> each filter data -> Any of hash may contain the event Id). I am using postgres 10.1. Can anyone help to get this?

Upvotes: 0

Views: 314

Answers (1)

Marcus Ilgner
Marcus Ilgner

Reputation: 7211

One thing before posting a possible approach: please be aware that this will be extremely bad in terms of performance as this will always require you to do a full table scan. It's possible that someone with more DBA experience than me knows a clever way to add an index here, but in terms of maintainability it might still be preferable to go for a slightly different approach.

Having said that, here's my approach.

with filters as (
  select id, jsonb_array_elements(
    jsonb_array_elements(my_jsonb_column)->'filter') as filter
    from my_table
)
select distinct id from filters where filter @> '{"event_id":"130"}'::jsonb

This will give you the id of all records including the event id.

Here's a fiddle to demo it: https://www.db-fiddle.com/f/hMSjM675cqQQnb734V4zne/0

Upvotes: 0

Related Questions