1

I'm looking to use postgres jsonb columns with arrays and being able to filter on them, so I have a schema with a column:

CREATE TABLE testtable
(
id  varchar(32) NOT NULL,   
refs    jsonb           NULL,
)

and the column contains data in the Json format:

{ "refs": ["one-1-0", "two-3-2", "two-3-4" ] }

I would like to be able to return all rows that that contain an array element that starts with (for example) "two-3-"

I have tried several things and can not get it to work as I'd like (the closest I have is to get the array part as text and search it as a string - but this is nasty)

I would also like to add a suitable index to this column to support this query.

Any suggestions would be briliant and greatfully received! Thanks

1

1 Answer 1

5

step-by-step demo:db<>fiddle

SELECT DISTINCT                                   -- 3
    id, refs
FROM
    testtable,
    jsonb_array_elements_text(refs -> 'refs')     -- 1
WHERE
    value LIKE 'two_3%'                           -- 2
  1. Expand the array into one row per array element
  2. Filter all records by the array elements (value) using the LIKE comparator and the % wildcard
  3. If there are several occurences then one record per occurence is being given back. So if you only want the original data set, you can remove the duplicates with DISTINCT
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, I'd upvote this 100 times if possible! :)
Am I correct in thinking that the following index is the correct one to support this query: create index idx1 ON testtable((refs->'refs'))
I believe you could try this at least.

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.