Il tipo tsvector
Usa il tipo tsvector, parte della funzione di full-text search di PostgreSQL. La tokenizzazione mantiene la punteggiatura quando è parte del token:
postgres=# select 'What are Q-type Operations?'::tsvector;
tsvector
------------------------
'Operations?' 'Q-type' 'What' 'are'
(1 row)
Gli operatori familiari funzionano anche sui tsvectors, e con || puoi concatenarli:
postgres=# select 'What are Q-type Operations?'::tsvector
postgres-# || 'A.B.C''s of Coding'::tsvector;
?column?
------------------------------------------------------
'A.B.C''s' 'Coding' 'Operations?' 'Q-type' 'What' 'are' 'of'
Se ti serve anche una normalizzazione specifica della lingua — rimozione delle stopword, stemming, assegnazione di pesi — usa la funzione to_tsvector:
postgres=# select to_tsvector('english',
postgres-# 'What are Q-type Operations? A.B.C''s of Coding');
to_tsvector
------------------------------------------------
'a.b.c':7 'code':10 'oper':6 'q':4 'q-type':3 'type':5
(1 row)
Full-text search vero e proprio
Calcolare il tsvector a ogni query, riga per riga, è costoso. La soluzione è memorizzarlo in una colonna dedicata e cercare con l'operatore @@. Così puoi anche creare un indice (GIN, oggi preferibile a GiST per il full-text, oppure pg_trgm per ricerche parziali).
postgres=# insert into text (phrase, tsvec)
postgres-# values ('What are Q-type Operations?',
postgres-# to_tsvector('english', 'What are Q-type Operations?'));
INSERT 0 1
La ricerca si esegue con to_tsquery e l'operatore @@:
postgres=# select phrase from text where tsvec @@ to_tsquery('q-type');
phrase
-----------------------------
What are Q-type Operations?
(1 row)
Puoi anche indicizzare direttamente un'espressione, evitando la colonna fisica:
CREATE INDEX idx ON text USING GIN (to_tsvector('english', phrase));