2017-10-07 1 views
1

Ich habe derzeit eine Tabelle, die eine Spalte mit einem JSON-Objekt enthält, das Twitter Cashtags darstellt.postgreSQL: jsonb traversal

Zum Beispiel ist meine ursprüngliche Anfrage:

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

Die cashtags Säule wird so etwas wie

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

zurückkehren Wie kann ich diesen Datentyp durchqueren, die als jsonb aufgeführt ist, um Sagen wir, nur Ergebnisse zurück, wo der Text gleich HEMP oder MSEZ ist?

Antwort

1

Der Wert data->'entities'->'symbols' ist ein JSON-Array. Sie können das Array mit der Funktion jsonb_array_elements(), z.B .:

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) 

oder UNNEST:

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) 
Verwandte Themen