La forma portabile espande l'array e testa ogni elemento:
SELECT * FROM posts p WHERE EXISTS ( SELECT FROM jsonb_array_elements_text(p.tags) tag WHERE tag LIKE '%TAG%' ); Correlato, con spiegazione:
- Search a JSON array for an object containing a value matching a pattern
Da Postgres 12, che implementa SQL/JSON, l'operatore @? si legge in modo più pulito:
SELECT * -- optional, to also show the matching item: -- , jsonb_path_query_first(tags, '$[*] ? (@ like_regex "^ tag" flag "i")') FROM posts WHERE tags @? '$[*] ? (@ like_regex "TAG")'; È solo un wrapper attorno a jsonb_path_exists(), quindi questo è identico:
... WHERE jsonb_path_exists(tags, '$[*] ? (@ like_regex "TAG")'); Nessuno dei due ha supporto per gli indici — almeno non in pg 13 — quindi entrambi sono lenti su tabelle grandi. Un design normalizzato, come suggerito da Laurenz, è superiore. Con un indice trigramme:
- PostgreSQL LIKE query performance variations
Solo per corrispondenza prefisso (LIKE 'TAG%', senza wildcard iniziale), un indice full text funziona:
CREATE INDEX posts_tags_fts_gin_idx ON posts USING GIN (to_tsvector('simple', tags)); E la query di corrispondenza:
SELECT * FROM posts p WHERE to_tsvector('simple', tags) @@ 'TAG:*'::tsquery Sostituisci english a simple se vuoi lo stemming per testo inglese naturale.
to_tsvector(json(b)) richiede Postgres 10 o successivo.
Correlati:
- Get partial match from GIN indexed TSVECTOR column
- Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL