PGSQL JSONB中具有部分路径的深度JSON查询? [英] Deep JSON query with partial path in PGSQL JSONB?

查看:72
本文介绍了PGSQL JSONB中具有部分路径的深度JSON查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出许多这样的JSON文档:

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
        },
      ],    
    }
  }

如何查询PostgreSQL JSONB中的f1 .... c1:foo1-即不提供lX也不提供c1-c2子文档的列表位置.

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.

这不是> Deep JSON查询的重复项在MySQL 5.7中具有部分路径?,因为这与MySQL有关,而这与PgSQL JSONB有关.

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.

推荐答案

在这里您需要遍历路径{l1,f1}的元素列表元素- @> (运算符检查左侧的JSON值是否包含右侧的值):

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;

结果:

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

更新

如果我们不知道确切的lX位置,则需要遍历每个子文档,然后遍历每个fX;查询如下:

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

这篇关于PGSQL JSONB中具有部分路径的深度JSON查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆