Deep JSON query with partial path in PGSQL JSONB?

一曲冷凌霜 提交于 2019-12-24 15:53:15

问题


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.


回答1:


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"}';


来源:https://stackoverflow.com/questions/35444927/deep-json-query-with-partial-path-in-pgsql-jsonb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!