1

I have jsonb column in my PgSql table with data like these :

{
  "group": [
    {
      "child1": "test",
      "child2": "test"
    },
    {
      "child1": "test2",
      "child2": "lorem ipsum"
    }
  ]
}

"group" can be multiple and is compounded of nested children data.

Is it possible to concat "child1" data in one select request or to check if one of nested "child1" is like %test%.

Thanks in advance.

1
  • What exactly is the output you want? The whole JSON value for all rows that match the condition? Or only the part of the JSON that matches the condition? Commented Nov 2, 2020 at 9:50

2 Answers 2

2

You can use such a SELECT statement including two functions with CROSS JOINs:

SELECT j2.*
  FROM t
 CROSS JOIN JSONB_EACH(data) AS j
 CROSS JOIN JSONB_ARRAY_ELEMENTS(data->'group') AS j2
 WHERE j2::TEXT like '%"test"%'

in order to look strictly for string with exact value "test" without any heading or trailing parts. If you need whether that value contains a substring test, then get rid of double quotes which wraps up it.

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I did a test and it works. I have to dig a little deeper into the functioning of CROSS JOIN which is not trivial. And the reason why we use j2.value.
you're welcome @Benito103e . Nice catch, yes, value is redundant.
With this solution, I also need to add a groupBy if a row has 2 children1 meeting the criteria.
1

I would use an exists condition:

select t.*
from the_table t
where exists (select *
              from jsonb_array_elements(t.data -> 'group') as g(element)
                cross join jsonb_each_text(g.element) as x(key,value)
              where x.key = 'child1'
                and x.value like '%test%')

Starting with Postgres 12 you can use a SQL/JSON path expression:

select *
from the_table t
where data @@ '$.group[*].child1 like_regex "test"'

2 Comments

Woww this Pg12 feature is amazing ! Using a path expression will be so helpful.
Using "cross join" and "exist" together seems to meet completely my need. Now I have to see how to translate it into ORM language =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.