Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep JSON query with partial path in PGSQL JSONB?

Given a number of JSON document like this:

  {
    id: some_id,
    l1: {
      f1: [
        {
          c1: foo,
          c2: bar
        },
        {
          c1: foo1,
          c2: bar1
        },
      ],
      f2: [
        {
          c3: baz,
          c4: bar
        },
      ],    
    }
  }

How can I query PostgreSQL JSONB for f1....c1: foo1 -- ie lX is not given nor is the list position of the c1-c2 subdocument.

This is not a duplicate of Deep JSON query with partial path in MySQL 5.7? since that is about MySQL and this one is about PgSQL JSONB.

like image 987
chx Avatar asked Nov 07 '25 21:11

chx


1 Answers

Here you need to iterate over the list of elements for path {l1,f1} #> - operator gets JSON object at specified path; after that, check if any of sub-documents contains '{"c1":"foo1"}'::jsonb element - @> (operator checks if the left JSON value contains within it the right value) :

WITH t(val) AS ( VALUES
  ('{
      "id": "some_id",
      "l1": {
        "f1": [
          {
            "c1": "foo",
            "c2": "bar"
          },
          {
            "c1": "foo1",
            "c2": "bar1"
          }
        ],
        "f2": [
          {
            "c3": "baz",
            "c4": "bar"
          }
        ]
      }
  }'::JSONB)
)
SELECT f1_array_element AS output
FROM
  t,jsonb_array_elements(t.val#>'{l1,f1}') AS f1_array_element
WHERE f1_array_element @> '{"c1":"foo1"}'::JSONB;

Result:

            output            
------------------------------
 {"c1": "foo1", "c2": "bar1"}
(1 row)

UPDATE

If we don't know about about exact lX location, we need to iterate over each subdocument, and than iterate over each fX; Query will be the following:

SELECT count(*)
FROM
  t,
  jsonb_each(t.val#>'{l1}') AS fX_sub_doc,
  jsonb_array_elements(fX_sub_doc.value) AS cX_sub_doc
WHERE
  cX_sub_doc @> '{"c1":"foo1"}';
like image 181
Dmitry S Avatar answered Nov 12 '25 16:11

Dmitry S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!