1

I currently have a table which contains a column with a JSON object representing Twitter cashtags.

For example, this is my original query:

SELECT
DATA->'id' as tweet_id,
DATA->'text' as tweet_text,
DATA->'entities'->'symbols' as cashtags
FROM documents
LIMIT 10

The cashtags column will return something like

[{"text":"HEMP","indices":[0,5]},{"text":"MSEZ","indices":[63,68]}]

How can I traverse this datatype, which is listed as jsonb, in order to say, only return results where the text is equal to HEMP or MSEZ?

1 Answer 1

1

The value data->'entities'->'symbols' is a json array. You can unnest the array using the function jsonb_array_elements(), e.g.:

SELECT
    data->'id' as tweet_id,
    data->'text' as tweet_text,
    value as cashtag
FROM documents,
jsonb_array_elements(data->'entities'->'symbols')
where value->>'text' in ('HEMP', 'MSEZ');

 tweet_id | tweet_text |                cashtag                
----------+------------+---------------------------------------
 1        | "my_tweet" | {"text": "HEMP", "indices": [0, 5]}
 1        | "my_tweet" | {"text": "MSEZ", "indices": [63, 68]}
(2 rows)

or:

SELECT DISTINCT
    data->'id' as tweet_id,
    data->'text' as tweet_text,
    data->'entities'->'symbols' as cashtags
FROM documents,
jsonb_array_elements(data->'entities'->'symbols')
WHERE value->>'text' in ('HEMP', 'MSEZ');

 tweet_id | tweet_text |                                   cashtags                                   
----------+------------+------------------------------------------------------------------------------
 1        | "my_tweet" | [{"text": "HEMP", "indices": [0, 5]}, {"text": "MSEZ", "indices": [63, 68]}]
(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.