1

I have a PostgreSQL table (creatures) that looks like the following:

| id <integer> | json <jsonb> |
-------------------------------
|      1       | {"name": "Grooper", "weaknesses":[{"type":"Fire", "value":2},{"type":"Dark", "value":2}]} |
|      2       | {"name": "Zik", "weaknesses":[{"type":"Fire", "value":2}]} |

I am trying to create a query that filters on weakness type, such that I can filter on all creatures with weaknesses to types Fire or Dark (contain either one), but also query on creatures with weaknesses of type Fire and Dark (must contain both).

I have figured out a query that works with Fire or Dark:

select 
  distinct c.* 
from 
  creatures c, 
  jsonb_array_elements(json->'weaknesses') as weakness 
where weakness->'type' ?| array['Fire','Dark']

How can I get this query to work to filter on creatures of types Fire and Dark?

UPDATE:

I have a query which seems to accomplish what I want, but it doesn't look pretty. Any tips?

SELECT * FROM creatures
WHERE 'Fire' in (SELECT jsonb_array_elements(json->'weaknesses')->>'type') 
AND 'Dark' in (SELECT jsonb_array_elements(json->'weaknesses')->>'type')

1 Answer 1

1

The problem here is that you have to "look into" the jsonb values inside the array so you can't use the ?& operator. Instead, find the appropriate keys with the ? operator and select only those rows that have two hits:

SELECT DISTINCT id, json
FROM creatures
JOIN LATERAL jsonb_array_elements(json->'weaknesses') ON value ? 'Dark' OR value ? 'Fire'
GROUP BY 1, 2
HAVING count(id) = 2;

By the way, if id is unique (primary key perhaps?) then SELECT DISTINCT ON (id) id, json ... is much faster because the jsonb document does not have to be examined to remove duplicates.

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.