1

How do I get a certain value based on a key inside an object that is part of my array? I store my json data as jsonb inside my Postgres 9.6 DB

addresses (JSONB)
---------
[{"address":"[email protected]", "type": "home"}, {"address":"[email protected]", "type": "work"}]

What I'd love to do is something like:

SELECT addresses ->> 'address' FROM foo

and then use the result in a full text search, where I search for a specific email-address like:

SELECT * FROM foo WHERE 
to_tsvector('simple', CAST(addresses ->>'address' as text)) @@ to_tsquery('abc:*');

All I get when I run the first query is: (NULL)

1 Answer 1

4

You should unnest the json array using jsonb_array_elements():

with foo(addresses) as (
values
    ('[{"address":"[email protected]", "type": "home"}, {"address":"[email protected]", "type": "work"}]'::jsonb)
)

select value->>'address' as address
from foo,
jsonb_array_elements(addresses)
where to_tsvector('simple', value->>'address') @@ to_tsquery('abc:*');

   address   
-------------
 [email protected]
(1 row) 
Sign up to request clarification or add additional context in comments.

Comments

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.