/
textsearch.sgml
4012 lines (3463 loc) · 145 KB
/
textsearch.sgml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!-- doc/src/sgml/textsearch.sgml -->
<chapter id="textsearch">
<title>Full Text Search</title>
<indexterm zone="textsearch">
<primary>full text search</primary>
</indexterm>
<indexterm zone="textsearch">
<primary>text search</primary>
</indexterm>
<sect1 id="textsearch-intro">
<title>Introduction</title>
<para>
Full Text Searching (or just <firstterm>text search</firstterm>) provides
the capability to identify natural-language <firstterm>documents</firstterm> that
satisfy a <firstterm>query</firstterm>, and optionally to sort them by
relevance to the query. The most common type of search
is to find all documents containing given <firstterm>query terms</firstterm>
and return them in order of their <firstterm>similarity</firstterm> to the
query. Notions of <varname>query</varname> and
<varname>similarity</varname> are very flexible and depend on the specific
application. The simplest search considers <varname>query</varname> as a
set of words and <varname>similarity</varname> as the frequency of query
words in the document.
</para>
<para>
Textual search operators have existed in databases for years.
<productname>PostgreSQL</productname> has
<literal>~</literal>, <literal>~*</literal>, <literal>LIKE</literal>, and
<literal>ILIKE</literal> operators for textual data types, but they lack
many essential properties required by modern information systems:
</para>
<itemizedlist spacing="compact" mark="bullet">
<listitem>
<para>
There is no linguistic support, even for English. Regular expressions
are not sufficient because they cannot easily handle derived words, e.g.,
<literal>satisfies</literal> and <literal>satisfy</literal>. You might
miss documents that contain <literal>satisfies</literal>, although you
probably would like to find them when searching for
<literal>satisfy</literal>. It is possible to use <literal>OR</literal>
to search for multiple derived forms, but this is tedious and error-prone
(some words can have several thousand derivatives).
</para>
</listitem>
<listitem>
<para>
They provide no ordering (ranking) of search results, which makes them
ineffective when thousands of matching documents are found.
</para>
</listitem>
<listitem>
<para>
They tend to be slow because there is no index support, so they must
process all documents for every search.
</para>
</listitem>
</itemizedlist>
<para>
Full text indexing allows documents to be <emphasis>preprocessed</emphasis>
and an index saved for later rapid searching. Preprocessing includes:
</para>
<itemizedlist mark="none">
<listitem>
<para>
<emphasis>Parsing documents into <firstterm>tokens</firstterm></emphasis>. It is
useful to identify various classes of tokens, e.g., numbers, words,
complex words, email addresses, so that they can be processed
differently. In principle token classes depend on the specific
application, but for most purposes it is adequate to use a predefined
set of classes.
<productname>PostgreSQL</productname> uses a <firstterm>parser</firstterm> to
perform this step. A standard parser is provided, and custom parsers
can be created for specific needs.
</para>
</listitem>
<listitem>
<para>
<emphasis>Converting tokens into <firstterm>lexemes</firstterm></emphasis>.
A lexeme is a string, just like a token, but it has been
<firstterm>normalized</firstterm> so that different forms of the same word
are made alike. For example, normalization almost always includes
folding upper-case letters to lower-case, and often involves removal
of suffixes (such as <literal>s</literal> or <literal>es</literal> in English).
This allows searches to find variant forms of the
same word, without tediously entering all the possible variants.
Also, this step typically eliminates <firstterm>stop words</firstterm>, which
are words that are so common that they are useless for searching.
(In short, then, tokens are raw fragments of the document text, while
lexemes are words that are believed useful for indexing and searching.)
<productname>PostgreSQL</productname> uses <firstterm>dictionaries</firstterm> to
perform this step. Various standard dictionaries are provided, and
custom ones can be created for specific needs.
</para>
</listitem>
<listitem>
<para>
<emphasis>Storing preprocessed documents optimized for
searching</emphasis>. For example, each document can be represented
as a sorted array of normalized lexemes. Along with the lexemes it is
often desirable to store positional information to use for
<firstterm>proximity ranking</firstterm>, so that a document that
contains a more <quote>dense</quote> region of query words is
assigned a higher rank than one with scattered query words.
</para>
</listitem>
</itemizedlist>
<para>
Dictionaries allow fine-grained control over how tokens are normalized.
With appropriate dictionaries, you can:
</para>
<itemizedlist spacing="compact" mark="bullet">
<listitem>
<para>
Define stop words that should not be indexed.
</para>
</listitem>
<listitem>
<para>
Map synonyms to a single word using <application>Ispell</application>.
</para>
</listitem>
<listitem>
<para>
Map phrases to a single word using a thesaurus.
</para>
</listitem>
<listitem>
<para>
Map different variations of a word to a canonical form using
an <application>Ispell</application> dictionary.
</para>
</listitem>
<listitem>
<para>
Map different variations of a word to a canonical form using
<application>Snowball</application> stemmer rules.
</para>
</listitem>
</itemizedlist>
<para>
A data type <type>tsvector</type> is provided for storing preprocessed
documents, along with a type <type>tsquery</type> for representing processed
queries (<xref linkend="datatype-textsearch"/>). There are many
functions and operators available for these data types
(<xref linkend="functions-textsearch"/>), the most important of which is
the match operator <literal>@@</literal>, which we introduce in
<xref linkend="textsearch-matching"/>. Full text searches can be accelerated
using indexes (<xref linkend="textsearch-indexes"/>).
</para>
<sect2 id="textsearch-document">
<title>What Is a Document?</title>
<indexterm zone="textsearch-document">
<primary>document</primary>
<secondary>text search</secondary>
</indexterm>
<para>
A <firstterm>document</firstterm> is the unit of searching in a full text search
system; for example, a magazine article or email message. The text search
engine must be able to parse documents and store associations of lexemes
(key words) with their parent document. Later, these associations are
used to search for documents that contain query words.
</para>
<para>
For searches within <productname>PostgreSQL</productname>,
a document is normally a textual field within a row of a database table,
or possibly a combination (concatenation) of such fields, perhaps stored
in several tables or obtained dynamically. In other words, a document can
be constructed from different parts for indexing and it might not be
stored anywhere as a whole. For example:
<programlisting>
SELECT title || ' ' || author || ' ' || abstract || ' ' || body AS document
FROM messages
WHERE mid = 12;
SELECT m.title || ' ' || m.author || ' ' || m.abstract || ' ' || d.body AS document
FROM messages m, docs d
WHERE m.mid = d.did AND m.mid = 12;
</programlisting>
</para>
<note>
<para>
Actually, in these example queries, <function>coalesce</function>
should be used to prevent a single <literal>NULL</literal> attribute from
causing a <literal>NULL</literal> result for the whole document.
</para>
</note>
<para>
Another possibility is to store the documents as simple text files in the
file system. In this case, the database can be used to store the full text
index and to execute searches, and some unique identifier can be used to
retrieve the document from the file system. However, retrieving files
from outside the database requires superuser permissions or special
function support, so this is usually less convenient than keeping all
the data inside <productname>PostgreSQL</productname>. Also, keeping
everything inside the database allows easy access
to document metadata to assist in indexing and display.
</para>
<para>
For text search purposes, each document must be reduced to the
preprocessed <type>tsvector</type> format. Searching and ranking
are performed entirely on the <type>tsvector</type> representation
of a document — the original text need only be retrieved
when the document has been selected for display to a user.
We therefore often speak of the <type>tsvector</type> as being the
document, but of course it is only a compact representation of
the full document.
</para>
</sect2>
<sect2 id="textsearch-matching">
<title>Basic Text Matching</title>
<para>
Full text searching in <productname>PostgreSQL</productname> is based on
the match operator <literal>@@</literal>, which returns
<literal>true</literal> if a <type>tsvector</type>
(document) matches a <type>tsquery</type> (query).
It doesn't matter which data type is written first:
<programlisting>
SELECT 'a fat cat sat on a mat and ate a fat rat'::tsvector @@ 'cat & rat'::tsquery;
?column?
----------
t
SELECT 'fat & cow'::tsquery @@ 'a fat cat sat on a mat and ate a fat rat'::tsvector;
?column?
----------
f
</programlisting>
</para>
<para>
As the above example suggests, a <type>tsquery</type> is not just raw
text, any more than a <type>tsvector</type> is. A <type>tsquery</type>
contains search terms, which must be already-normalized lexemes, and
may combine multiple terms using AND, OR, NOT, and FOLLOWED BY operators.
(For syntax details see <xref linkend="datatype-tsquery"/>.) There are
functions <function>to_tsquery</function>, <function>plainto_tsquery</function>,
and <function>phraseto_tsquery</function>
that are helpful in converting user-written text into a proper
<type>tsquery</type>, primarily by normalizing words appearing in
the text. Similarly, <function>to_tsvector</function> is used to parse and
normalize a document string. So in practice a text search match would
look more like this:
<programlisting>
SELECT to_tsvector('fat cats ate fat rats') @@ to_tsquery('fat & rat');
?column?
----------
t
</programlisting>
Observe that this match would not succeed if written as
<programlisting>
SELECT 'fat cats ate fat rats'::tsvector @@ to_tsquery('fat & rat');
?column?
----------
f
</programlisting>
since here no normalization of the word <literal>rats</literal> will occur.
The elements of a <type>tsvector</type> are lexemes, which are assumed
already normalized, so <literal>rats</literal> does not match <literal>rat</literal>.
</para>
<para>
The <literal>@@</literal> operator also
supports <type>text</type> input, allowing explicit conversion of a text
string to <type>tsvector</type> or <type>tsquery</type> to be skipped
in simple cases. The variants available are:
<programlisting>
tsvector @@ tsquery
tsquery @@ tsvector
text @@ tsquery
text @@ text
</programlisting>
</para>
<para>
The first two of these we saw already.
The form <type>text</type> <literal>@@</literal> <type>tsquery</type>
is equivalent to <literal>to_tsvector(x) @@ y</literal>.
The form <type>text</type> <literal>@@</literal> <type>text</type>
is equivalent to <literal>to_tsvector(x) @@ plainto_tsquery(y)</literal>.
</para>
<para>
Within a <type>tsquery</type>, the <literal>&</literal> (AND) operator
specifies that both its arguments must appear in the document to have a
match. Similarly, the <literal>|</literal> (OR) operator specifies that
at least one of its arguments must appear, while the <literal>!</literal> (NOT)
operator specifies that its argument must <emphasis>not</emphasis> appear in
order to have a match.
For example, the query <literal>fat & ! rat</literal> matches documents that
contain <literal>fat</literal> but not <literal>rat</literal>.
</para>
<para>
Searching for phrases is possible with the help of
the <literal><-></literal> (FOLLOWED BY) <type>tsquery</type> operator, which
matches only if its arguments have matches that are adjacent and in the
given order. For example:
<programlisting>
SELECT to_tsvector('fatal error') @@ to_tsquery('fatal <-> error');
?column?
----------
t
SELECT to_tsvector('error is not fatal') @@ to_tsquery('fatal <-> error');
?column?
----------
f
</programlisting>
There is a more general version of the FOLLOWED BY operator having the
form <literal><<replaceable>N</replaceable>></literal>,
where <replaceable>N</replaceable> is an integer standing for the difference between
the positions of the matching lexemes. <literal><1></literal> is
the same as <literal><-></literal>, while <literal><2></literal>
allows exactly one other lexeme to appear between the matches, and so
on. The <literal>phraseto_tsquery</literal> function makes use of this
operator to construct a <literal>tsquery</literal> that can match a multi-word
phrase when some of the words are stop words. For example:
<programlisting>
SELECT phraseto_tsquery('cats ate rats');
phraseto_tsquery
-------------------------------
'cat' <-> 'ate' <-> 'rat'
SELECT phraseto_tsquery('the cats ate the rats');
phraseto_tsquery
-------------------------------
'cat' <-> 'ate' <2> 'rat'
</programlisting>
</para>
<para>
A special case that's sometimes useful is that <literal><0></literal>
can be used to require that two patterns match the same word.
</para>
<para>
Parentheses can be used to control nesting of the <type>tsquery</type>
operators. Without parentheses, <literal>|</literal> binds least tightly,
then <literal>&</literal>, then <literal><-></literal>,
and <literal>!</literal> most tightly.
</para>
<para>
It's worth noticing that the AND/OR/NOT operators mean something subtly
different when they are within the arguments of a FOLLOWED BY operator
than when they are not, because within FOLLOWED BY the exact position of
the match is significant. For example, normally <literal>!x</literal> matches
only documents that do not contain <literal>x</literal> anywhere.
But <literal>!x <-> y</literal> matches <literal>y</literal> if it is not
immediately after an <literal>x</literal>; an occurrence of <literal>x</literal>
elsewhere in the document does not prevent a match. Another example is
that <literal>x & y</literal> normally only requires that <literal>x</literal>
and <literal>y</literal> both appear somewhere in the document, but
<literal>(x & y) <-> z</literal> requires <literal>x</literal>
and <literal>y</literal> to match at the same place, immediately before
a <literal>z</literal>. Thus this query behaves differently from
<literal>x <-> z & y <-> z</literal>, which will match a
document containing two separate sequences <literal>x z</literal> and
<literal>y z</literal>. (This specific query is useless as written,
since <literal>x</literal> and <literal>y</literal> could not match at the same place;
but with more complex situations such as prefix-match patterns, a query
of this form could be useful.)
</para>
</sect2>
<sect2 id="textsearch-intro-configurations">
<title>Configurations</title>
<para>
The above are all simple text search examples. As mentioned before, full
text search functionality includes the ability to do many more things:
skip indexing certain words (stop words), process synonyms, and use
sophisticated parsing, e.g., parse based on more than just white space.
This functionality is controlled by <firstterm>text search
configurations</firstterm>. <productname>PostgreSQL</productname> comes with predefined
configurations for many languages, and you can easily create your own
configurations. (<application>psql</application>'s <command>\dF</command> command
shows all available configurations.)
</para>
<para>
During installation an appropriate configuration is selected and
<xref linkend="guc-default-text-search-config"/> is set accordingly
in <filename>postgresql.conf</filename>. If you are using the same text search
configuration for the entire cluster you can use the value in
<filename>postgresql.conf</filename>. To use different configurations
throughout the cluster but the same configuration within any one database,
use <command>ALTER DATABASE ... SET</command>. Otherwise, you can set
<varname>default_text_search_config</varname> in each session.
</para>
<para>
Each text search function that depends on a configuration has an optional
<type>regconfig</type> argument, so that the configuration to use can be
specified explicitly. <varname>default_text_search_config</varname>
is used only when this argument is omitted.
</para>
<para>
To make it easier to build custom text search configurations, a
configuration is built up from simpler database objects.
<productname>PostgreSQL</productname>'s text search facility provides
four types of configuration-related database objects:
</para>
<itemizedlist spacing="compact" mark="bullet">
<listitem>
<para>
<firstterm>Text search parsers</firstterm> break documents into tokens
and classify each token (for example, as words or numbers).
</para>
</listitem>
<listitem>
<para>
<firstterm>Text search dictionaries</firstterm> convert tokens to normalized
form and reject stop words.
</para>
</listitem>
<listitem>
<para>
<firstterm>Text search templates</firstterm> provide the functions underlying
dictionaries. (A dictionary simply specifies a template and a set
of parameters for the template.)
</para>
</listitem>
<listitem>
<para>
<firstterm>Text search configurations</firstterm> select a parser and a set
of dictionaries to use to normalize the tokens produced by the parser.
</para>
</listitem>
</itemizedlist>
<para>
Text search parsers and templates are built from low-level C functions;
therefore it requires C programming ability to develop new ones, and
superuser privileges to install one into a database. (There are examples
of add-on parsers and templates in the <filename>contrib/</filename> area of the
<productname>PostgreSQL</productname> distribution.) Since dictionaries and
configurations just parameterize and connect together some underlying
parsers and templates, no special privilege is needed to create a new
dictionary or configuration. Examples of creating custom dictionaries and
configurations appear later in this chapter.
</para>
</sect2>
</sect1>
<sect1 id="textsearch-tables">
<title>Tables and Indexes</title>
<para>
The examples in the previous section illustrated full text matching using
simple constant strings. This section shows how to search table data,
optionally using indexes.
</para>
<sect2 id="textsearch-tables-search">
<title>Searching a Table</title>
<para>
It is possible to do a full text search without an index. A simple query
to print the <structname>title</structname> of each row that contains the word
<literal>friend</literal> in its <structfield>body</structfield> field is:
<programlisting>
SELECT title
FROM pgweb
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'friend');
</programlisting>
This will also find related words such as <literal>friends</literal>
and <literal>friendly</literal>, since all these are reduced to the same
normalized lexeme.
</para>
<para>
The query above specifies that the <literal>english</literal> configuration
is to be used to parse and normalize the strings. Alternatively we
could omit the configuration parameters:
<programlisting>
SELECT title
FROM pgweb
WHERE to_tsvector(body) @@ to_tsquery('friend');
</programlisting>
This query will use the configuration set by <xref
linkend="guc-default-text-search-config"/>.
</para>
<para>
A more complex example is to
select the ten most recent documents that contain <literal>create</literal> and
<literal>table</literal> in the <structname>title</structname> or <structname>body</structname>:
<programlisting>
SELECT title
FROM pgweb
WHERE to_tsvector(title || ' ' || body) @@ to_tsquery('create & table')
ORDER BY last_mod_date DESC
LIMIT 10;
</programlisting>
For clarity we omitted the <function>coalesce</function> function calls
which would be needed to find rows that contain <literal>NULL</literal>
in one of the two fields.
</para>
<para>
Although these queries will work without an index, most applications
will find this approach too slow, except perhaps for occasional ad-hoc
searches. Practical use of text searching usually requires creating
an index.
</para>
</sect2>
<sect2 id="textsearch-tables-index">
<title>Creating Indexes</title>
<para>
We can create a <acronym>GIN</acronym> index (<xref
linkend="textsearch-indexes"/>) to speed up text searches:
<programlisting>
CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector('english', body));
</programlisting>
Notice that the 2-argument version of <function>to_tsvector</function> is
used. Only text search functions that specify a configuration name can
be used in expression indexes (<xref linkend="indexes-expressional"/>).
This is because the index contents must be unaffected by <xref
linkend="guc-default-text-search-config"/>. If they were affected, the
index contents might be inconsistent because different entries could
contain <type>tsvector</type>s that were created with different text search
configurations, and there would be no way to guess which was which. It
would be impossible to dump and restore such an index correctly.
</para>
<para>
Because the two-argument version of <function>to_tsvector</function> was
used in the index above, only a query reference that uses the 2-argument
version of <function>to_tsvector</function> with the same configuration
name will use that index. That is, <literal>WHERE
to_tsvector('english', body) @@ 'a & b'</literal> can use the index,
but <literal>WHERE to_tsvector(body) @@ 'a & b'</literal> cannot.
This ensures that an index will be used only with the same configuration
used to create the index entries.
</para>
<para>
It is possible to set up more complex expression indexes wherein the
configuration name is specified by another column, e.g.:
<programlisting>
CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector(config_name, body));
</programlisting>
where <literal>config_name</literal> is a column in the <literal>pgweb</literal>
table. This allows mixed configurations in the same index while
recording which configuration was used for each index entry. This
would be useful, for example, if the document collection contained
documents in different languages. Again,
queries that are meant to use the index must be phrased to match, e.g.,
<literal>WHERE to_tsvector(config_name, body) @@ 'a & b'</literal>.
</para>
<para>
Indexes can even concatenate columns:
<programlisting>
CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector('english', title || ' ' || body));
</programlisting>
</para>
<para>
Another approach is to create a separate <type>tsvector</type> column
to hold the output of <function>to_tsvector</function>. To keep this
column automatically up to date with its source data, use a stored
generated column. This example is a
concatenation of <literal>title</literal> and <literal>body</literal>,
using <function>coalesce</function> to ensure that one field will still be
indexed when the other is <literal>NULL</literal>:
<programlisting>
ALTER TABLE pgweb
ADD COLUMN textsearchable_index_col tsvector
GENERATED ALWAYS AS (to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, ''))) STORED;
</programlisting>
Then we create a <acronym>GIN</acronym> index to speed up the search:
<programlisting>
CREATE INDEX textsearch_idx ON pgweb USING GIN (textsearchable_index_col);
</programlisting>
Now we are ready to perform a fast full text search:
<programlisting>
SELECT title
FROM pgweb
WHERE textsearchable_index_col @@ to_tsquery('create & table')
ORDER BY last_mod_date DESC
LIMIT 10;
</programlisting>
</para>
<para>
One advantage of the separate-column approach over an expression index
is that it is not necessary to explicitly specify the text search
configuration in queries in order to make use of the index. As shown
in the example above, the query can depend on
<varname>default_text_search_config</varname>. Another advantage is that
searches will be faster, since it will not be necessary to redo the
<function>to_tsvector</function> calls to verify index matches. (This is more
important when using a GiST index than a GIN index; see <xref
linkend="textsearch-indexes"/>.) The expression-index approach is
simpler to set up, however, and it requires less disk space since the
<type>tsvector</type> representation is not stored explicitly.
</para>
</sect2>
</sect1>
<sect1 id="textsearch-controls">
<title>Controlling Text Search</title>
<para>
To implement full text searching there must be a function to create a
<type>tsvector</type> from a document and a <type>tsquery</type> from a
user query. Also, we need to return results in a useful order, so we need
a function that compares documents with respect to their relevance to
the query. It's also important to be able to display the results nicely.
<productname>PostgreSQL</productname> provides support for all of these
functions.
</para>
<sect2 id="textsearch-parsing-documents">
<title>Parsing Documents</title>
<para>
<productname>PostgreSQL</productname> provides the
function <function>to_tsvector</function> for converting a document to
the <type>tsvector</type> data type.
</para>
<indexterm>
<primary>to_tsvector</primary>
</indexterm>
<synopsis>
to_tsvector(<optional> <replaceable class="parameter">config</replaceable> <type>regconfig</type>, </optional> <replaceable class="parameter">document</replaceable> <type>text</type>) returns <type>tsvector</type>
</synopsis>
<para>
<function>to_tsvector</function> parses a textual document into tokens,
reduces the tokens to lexemes, and returns a <type>tsvector</type> which
lists the lexemes together with their positions in the document.
The document is processed according to the specified or default
text search configuration.
Here is a simple example:
<screen>
SELECT to_tsvector('english', 'a fat cat sat on a mat - it ate a fat rats');
to_tsvector
-----------------------------------------------------
'ate':9 'cat':3 'fat':2,11 'mat':7 'rat':12 'sat':4
</screen>
</para>
<para>
In the example above we see that the resulting <type>tsvector</type> does not
contain the words <literal>a</literal>, <literal>on</literal>, or
<literal>it</literal>, the word <literal>rats</literal> became
<literal>rat</literal>, and the punctuation sign <literal>-</literal> was
ignored.
</para>
<para>
The <function>to_tsvector</function> function internally calls a parser
which breaks the document text into tokens and assigns a type to
each token. For each token, a list of
dictionaries (<xref linkend="textsearch-dictionaries"/>) is consulted,
where the list can vary depending on the token type. The first dictionary
that <firstterm>recognizes</firstterm> the token emits one or more normalized
<firstterm>lexemes</firstterm> to represent the token. For example,
<literal>rats</literal> became <literal>rat</literal> because one of the
dictionaries recognized that the word <literal>rats</literal> is a plural
form of <literal>rat</literal>. Some words are recognized as
<firstterm>stop words</firstterm> (<xref linkend="textsearch-stopwords"/>), which
causes them to be ignored since they occur too frequently to be useful in
searching. In our example these are
<literal>a</literal>, <literal>on</literal>, and <literal>it</literal>.
If no dictionary in the list recognizes the token then it is also ignored.
In this example that happened to the punctuation sign <literal>-</literal>
because there are in fact no dictionaries assigned for its token type
(<literal>Space symbols</literal>), meaning space tokens will never be
indexed. The choices of parser, dictionaries and which types of tokens to
index are determined by the selected text search configuration (<xref
linkend="textsearch-configuration"/>). It is possible to have
many different configurations in the same database, and predefined
configurations are available for various languages. In our example
we used the default configuration <literal>english</literal> for the
English language.
</para>
<para>
The function <function>setweight</function> can be used to label the
entries of a <type>tsvector</type> with a given <firstterm>weight</firstterm>,
where a weight is one of the letters <literal>A</literal>, <literal>B</literal>,
<literal>C</literal>, or <literal>D</literal>.
This is typically used to mark entries coming from
different parts of a document, such as title versus body. Later, this
information can be used for ranking of search results.
</para>
<para>
Because <function>to_tsvector</function>(<literal>NULL</literal>) will
return <literal>NULL</literal>, it is recommended to use
<function>coalesce</function> whenever a field might be null.
Here is the recommended method for creating
a <type>tsvector</type> from a structured document:
<programlisting>
UPDATE tt SET ti =
setweight(to_tsvector(coalesce(title,'')), 'A') ||
setweight(to_tsvector(coalesce(keyword,'')), 'B') ||
setweight(to_tsvector(coalesce(abstract,'')), 'C') ||
setweight(to_tsvector(coalesce(body,'')), 'D');
</programlisting>
Here we have used <function>setweight</function> to label the source
of each lexeme in the finished <type>tsvector</type>, and then merged
the labeled <type>tsvector</type> values using the <type>tsvector</type>
concatenation operator <literal>||</literal>. (<xref
linkend="textsearch-manipulate-tsvector"/> gives details about these
operations.)
</para>
</sect2>
<sect2 id="textsearch-parsing-queries">
<title>Parsing Queries</title>
<para>
<productname>PostgreSQL</productname> provides the
functions <function>to_tsquery</function>,
<function>plainto_tsquery</function>,
<function>phraseto_tsquery</function> and
<function>websearch_to_tsquery</function>
for converting a query to the <type>tsquery</type> data type.
<function>to_tsquery</function> offers access to more features
than either <function>plainto_tsquery</function> or
<function>phraseto_tsquery</function>, but it is less forgiving about its
input. <function>websearch_to_tsquery</function> is a simplified version
of <function>to_tsquery</function> with an alternative syntax, similar
to the one used by web search engines.
</para>
<indexterm>
<primary>to_tsquery</primary>
</indexterm>
<synopsis>
to_tsquery(<optional> <replaceable class="parameter">config</replaceable> <type>regconfig</type>, </optional> <replaceable class="parameter">querytext</replaceable> <type>text</type>) returns <type>tsquery</type>
</synopsis>
<para>
<function>to_tsquery</function> creates a <type>tsquery</type> value from
<replaceable>querytext</replaceable>, which must consist of single tokens
separated by the <type>tsquery</type> operators <literal>&</literal> (AND),
<literal>|</literal> (OR), <literal>!</literal> (NOT), and
<literal><-></literal> (FOLLOWED BY), possibly grouped
using parentheses. In other words, the input to
<function>to_tsquery</function> must already follow the general rules for
<type>tsquery</type> input, as described in <xref
linkend="datatype-tsquery"/>. The difference is that while basic
<type>tsquery</type> input takes the tokens at face value,
<function>to_tsquery</function> normalizes each token into a lexeme using
the specified or default configuration, and discards any tokens that are
stop words according to the configuration. For example:
<screen>
SELECT to_tsquery('english', 'The & Fat & Rats');
to_tsquery
---------------
'fat' & 'rat'
</screen>
As in basic <type>tsquery</type> input, weight(s) can be attached to each
lexeme to restrict it to match only <type>tsvector</type> lexemes of those
weight(s). For example:
<screen>
SELECT to_tsquery('english', 'Fat | Rats:AB');
to_tsquery
------------------
'fat' | 'rat':AB
</screen>
Also, <literal>*</literal> can be attached to a lexeme to specify prefix matching:
<screen>
SELECT to_tsquery('supern:*A & star:A*B');
to_tsquery
--------------------------
'supern':*A & 'star':*AB
</screen>
Such a lexeme will match any word in a <type>tsvector</type> that begins
with the given string.
</para>
<para>
<function>to_tsquery</function> can also accept single-quoted
phrases. This is primarily useful when the configuration includes a
thesaurus dictionary that may trigger on such phrases.
In the example below, a thesaurus contains the rule <literal>supernovae
stars : sn</literal>:
<screen>
SELECT to_tsquery('''supernovae stars'' & !crab');
to_tsquery
---------------
'sn' & !'crab'
</screen>
Without quotes, <function>to_tsquery</function> will generate a syntax
error for tokens that are not separated by an AND, OR, or FOLLOWED BY
operator.
</para>
<indexterm>
<primary>plainto_tsquery</primary>
</indexterm>
<synopsis>
plainto_tsquery(<optional> <replaceable class="parameter">config</replaceable> <type>regconfig</type>, </optional> <replaceable class="parameter">querytext</replaceable> <type>text</type>) returns <type>tsquery</type>
</synopsis>
<para>
<function>plainto_tsquery</function> transforms the unformatted text
<replaceable>querytext</replaceable> to a <type>tsquery</type> value.
The text is parsed and normalized much as for <function>to_tsvector</function>,
then the <literal>&</literal> (AND) <type>tsquery</type> operator is
inserted between surviving words.
</para>
<para>
Example:
<screen>
SELECT plainto_tsquery('english', 'The Fat Rats');
plainto_tsquery
-----------------
'fat' & 'rat'
</screen>
Note that <function>plainto_tsquery</function> will not
recognize <type>tsquery</type> operators, weight labels,
or prefix-match labels in its input:
<screen>
SELECT plainto_tsquery('english', 'The Fat & Rats:C');
plainto_tsquery
---------------------
'fat' & 'rat' & 'c'
</screen>
Here, all the input punctuation was discarded.
</para>
<indexterm>
<primary>phraseto_tsquery</primary>
</indexterm>
<synopsis>
phraseto_tsquery(<optional> <replaceable class="parameter">config</replaceable> <type>regconfig</type>, </optional> <replaceable class="parameter">querytext</replaceable> <type>text</type>) returns <type>tsquery</type>
</synopsis>
<para>
<function>phraseto_tsquery</function> behaves much like
<function>plainto_tsquery</function>, except that it inserts
the <literal><-></literal> (FOLLOWED BY) operator between
surviving words instead of the <literal>&</literal> (AND) operator.
Also, stop words are not simply discarded, but are accounted for by
inserting <literal><<replaceable>N</replaceable>></literal> operators rather
than <literal><-></literal> operators. This function is useful
when searching for exact lexeme sequences, since the FOLLOWED BY
operators check lexeme order not just the presence of all the lexemes.
</para>
<para>
Example:
<screen>
SELECT phraseto_tsquery('english', 'The Fat Rats');
phraseto_tsquery
------------------
'fat' <-> 'rat'
</screen>
Like <function>plainto_tsquery</function>, the
<function>phraseto_tsquery</function> function will not
recognize <type>tsquery</type> operators, weight labels,
or prefix-match labels in its input:
<screen>
SELECT phraseto_tsquery('english', 'The Fat & Rats:C');
phraseto_tsquery
-----------------------------
'fat' <-> 'rat' <-> 'c'
</screen>
</para>
<synopsis>
websearch_to_tsquery(<optional> <replaceable class="parameter">config</replaceable> <type>regconfig</type>, </optional> <replaceable class="parameter">querytext</replaceable> <type>text</type>) returns <type>tsquery</type>
</synopsis>
<para>
<function>websearch_to_tsquery</function> creates a <type>tsquery</type>
value from <replaceable>querytext</replaceable> using an alternative
syntax in which simple unformatted text is a valid query.
Unlike <function>plainto_tsquery</function>
and <function>phraseto_tsquery</function>, it also recognizes certain
operators. Moreover, this function will never raise syntax errors,
which makes it possible to use raw user-supplied input for search.
The following syntax is supported:
<itemizedlist spacing="compact" mark="bullet">
<listitem>
<para>
<literal>unquoted text</literal>: text not inside quote marks will be
converted to terms separated by <literal>&</literal> operators, as
if processed by <function>plainto_tsquery</function>.
</para>
</listitem>
<listitem>
<para>
<literal>"quoted text"</literal>: text inside quote marks will be
converted to terms separated by <literal><-></literal>
operators, as if processed by <function>phraseto_tsquery</function>.
</para>
</listitem>
<listitem>
<para>
<literal>OR</literal>: the word <quote>or</quote> will be converted to
the <literal>|</literal> operator.
</para>
</listitem>
<listitem>
<para>
<literal>-</literal>: a dash will be converted to
the <literal>!</literal> operator.