4 12.1.1. What Is a Document?
5 12.1.2. Basic Text Matching
8 Full Text Searching (or just text search) provides the capability to
9 identify natural-language documents that satisfy a query, and
10 optionally to sort them by relevance to the query. The most common type
11 of search is to find all documents containing given query terms and
12 return them in order of their similarity to the query. Notions of query
13 and similarity are very flexible and depend on the specific
14 application. The simplest search considers query as a set of words and
15 similarity as the frequency of query words in the document.
17 Textual search operators have existed in databases for years.
18 PostgreSQL has ~, ~*, LIKE, and ILIKE operators for textual data types,
19 but they lack many essential properties required by modern information
21 * There is no linguistic support, even for English. Regular
22 expressions are not sufficient because they cannot easily handle
23 derived words, e.g., satisfies and satisfy. You might miss
24 documents that contain satisfies, although you probably would like
25 to find them when searching for satisfy. It is possible to use OR
26 to search for multiple derived forms, but this is tedious and
27 error-prone (some words can have several thousand derivatives).
28 * They provide no ordering (ranking) of search results, which makes
29 them ineffective when thousands of matching documents are found.
30 * They tend to be slow because there is no index support, so they
31 must process all documents for every search.
33 Full text indexing allows documents to be preprocessed and an index
34 saved for later rapid searching. Preprocessing includes:
35 * Parsing documents into tokens. It is useful to identify various
36 classes of tokens, e.g., numbers, words, complex words, email
37 addresses, so that they can be processed differently. In principle
38 token classes depend on the specific application, but for most
39 purposes it is adequate to use a predefined set of classes.
40 PostgreSQL uses a parser to perform this step. A standard parser is
41 provided, and custom parsers can be created for specific needs.
42 * Converting tokens into lexemes. A lexeme is a string, just like a
43 token, but it has been normalized so that different forms of the
44 same word are made alike. For example, normalization almost always
45 includes folding upper-case letters to lower-case, and often
46 involves removal of suffixes (such as s or es in English). This
47 allows searches to find variant forms of the same word, without
48 tediously entering all the possible variants. Also, this step
49 typically eliminates stop words, which are words that are so common
50 that they are useless for searching. (In short, then, tokens are
51 raw fragments of the document text, while lexemes are words that
52 are believed useful for indexing and searching.) PostgreSQL uses
53 dictionaries to perform this step. Various standard dictionaries
54 are provided, and custom ones can be created for specific needs.
55 * Storing preprocessed documents optimized for searching. For
56 example, each document can be represented as a sorted array of
57 normalized lexemes. Along with the lexemes it is often desirable to
58 store positional information to use for proximity ranking, so that
59 a document that contains a more “dense” region of query words is
60 assigned a higher rank than one with scattered query words.
62 Dictionaries allow fine-grained control over how tokens are normalized.
63 With appropriate dictionaries, you can:
64 * Define stop words that should not be indexed.
65 * Map synonyms to a single word using Ispell.
66 * Map phrases to a single word using a thesaurus.
67 * Map different variations of a word to a canonical form using an
69 * Map different variations of a word to a canonical form using
70 Snowball stemmer rules.
72 A data type tsvector is provided for storing preprocessed documents,
73 along with a type tsquery for representing processed queries
74 (Section 8.11). There are many functions and operators available for
75 these data types (Section 9.13), the most important of which is the
76 match operator @@, which we introduce in Section 12.1.2. Full text
77 searches can be accelerated using indexes (Section 12.9).
79 12.1.1. What Is a Document? #
81 A document is the unit of searching in a full text search system; for
82 example, a magazine article or email message. The text search engine
83 must be able to parse documents and store associations of lexemes (key
84 words) with their parent document. Later, these associations are used
85 to search for documents that contain query words.
87 For searches within PostgreSQL, a document is normally a textual field
88 within a row of a database table, or possibly a combination
89 (concatenation) of such fields, perhaps stored in several tables or
90 obtained dynamically. In other words, a document can be constructed
91 from different parts for indexing and it might not be stored anywhere
92 as a whole. For example:
93 SELECT title || ' ' || author || ' ' || abstract || ' ' || body AS document
97 SELECT m.title || ' ' || m.author || ' ' || m.abstract || ' ' || d.body AS docum
99 FROM messages m, docs d
100 WHERE m.mid = d.did AND m.mid = 12;
104 Actually, in these example queries, coalesce should be used to prevent
105 a single NULL attribute from causing a NULL result for the whole
108 Another possibility is to store the documents as simple text files in
109 the file system. In this case, the database can be used to store the
110 full text index and to execute searches, and some unique identifier can
111 be used to retrieve the document from the file system. However,
112 retrieving files from outside the database requires superuser
113 permissions or special function support, so this is usually less
114 convenient than keeping all the data inside PostgreSQL. Also, keeping
115 everything inside the database allows easy access to document metadata
116 to assist in indexing and display.
118 For text search purposes, each document must be reduced to the
119 preprocessed tsvector format. Searching and ranking are performed
120 entirely on the tsvector representation of a document — the original
121 text need only be retrieved when the document has been selected for
122 display to a user. We therefore often speak of the tsvector as being
123 the document, but of course it is only a compact representation of the
126 12.1.2. Basic Text Matching #
128 Full text searching in PostgreSQL is based on the match operator @@,
129 which returns true if a tsvector (document) matches a tsquery (query).
130 It doesn't matter which data type is written first:
131 SELECT 'a fat cat sat on a mat and ate a fat rat'::tsvector @@ 'cat & rat'::tsqu
137 SELECT 'fat & cow'::tsquery @@ 'a fat cat sat on a mat and ate a fat rat'::tsvec
143 As the above example suggests, a tsquery is not just raw text, any more
144 than a tsvector is. A tsquery contains search terms, which must be
145 already-normalized lexemes, and may combine multiple terms using AND,
146 OR, NOT, and FOLLOWED BY operators. (For syntax details see
147 Section 8.11.2.) There are functions to_tsquery, plainto_tsquery, and
148 phraseto_tsquery that are helpful in converting user-written text into
149 a proper tsquery, primarily by normalizing words appearing in the text.
150 Similarly, to_tsvector is used to parse and normalize a document
151 string. So in practice a text search match would look more like this:
152 SELECT to_tsvector('fat cats ate fat rats') @@ to_tsquery('fat & rat');
157 Observe that this match would not succeed if written as
158 SELECT 'fat cats ate fat rats'::tsvector @@ to_tsquery('fat & rat');
163 since here no normalization of the word rats will occur. The elements
164 of a tsvector are lexemes, which are assumed already normalized, so
165 rats does not match rat.
167 The @@ operator also supports text input, allowing explicit conversion
168 of a text string to tsvector or tsquery to be skipped in simple cases.
169 The variants available are:
175 The first two of these we saw already. The form text @@ tsquery is
176 equivalent to to_tsvector(x) @@ y. The form text @@ text is equivalent
177 to to_tsvector(x) @@ plainto_tsquery(y).
179 Within a tsquery, the & (AND) operator specifies that both its
180 arguments must appear in the document to have a match. Similarly, the |
181 (OR) operator specifies that at least one of its arguments must appear,
182 while the ! (NOT) operator specifies that its argument must not appear
183 in order to have a match. For example, the query fat & ! rat matches
184 documents that contain fat but not rat.
186 Searching for phrases is possible with the help of the <-> (FOLLOWED
187 BY) tsquery operator, which matches only if its arguments have matches
188 that are adjacent and in the given order. For example:
189 SELECT to_tsvector('fatal error') @@ to_tsquery('fatal <-> error');
194 SELECT to_tsvector('error is not fatal') @@ to_tsquery('fatal <-> error');
199 There is a more general version of the FOLLOWED BY operator having the
200 form <N>, where N is an integer standing for the difference between the
201 positions of the matching lexemes. <1> is the same as <->, while <2>
202 allows exactly one other lexeme to appear between the matches, and so
203 on. The phraseto_tsquery function makes use of this operator to
204 construct a tsquery that can match a multi-word phrase when some of the
205 words are stop words. For example:
206 SELECT phraseto_tsquery('cats ate rats');
208 -------------------------------
209 'cat' <-> 'ate' <-> 'rat'
211 SELECT phraseto_tsquery('the cats ate the rats');
213 -------------------------------
214 'cat' <-> 'ate' <2> 'rat'
216 A special case that's sometimes useful is that <0> can be used to
217 require that two patterns match the same word.
219 Parentheses can be used to control nesting of the tsquery operators.
220 Without parentheses, | binds least tightly, then &, then <->, and !
223 It's worth noticing that the AND/OR/NOT operators mean something subtly
224 different when they are within the arguments of a FOLLOWED BY operator
225 than when they are not, because within FOLLOWED BY the exact position
226 of the match is significant. For example, normally !x matches only
227 documents that do not contain x anywhere. But !x <-> y matches y if it
228 is not immediately after an x; an occurrence of x elsewhere in the
229 document does not prevent a match. Another example is that x & y
230 normally only requires that x and y both appear somewhere in the
231 document, but (x & y) <-> z requires x and y to match at the same
232 place, immediately before a z. Thus this query behaves differently from
233 x <-> z & y <-> z, which will match a document containing two separate
234 sequences x z and y z. (This specific query is useless as written,
235 since x and y could not match at the same place; but with more complex
236 situations such as prefix-match patterns, a query of this form could be
239 12.1.3. Configurations #
241 The above are all simple text search examples. As mentioned before,
242 full text search functionality includes the ability to do many more
243 things: skip indexing certain words (stop words), process synonyms, and
244 use sophisticated parsing, e.g., parse based on more than just white
245 space. This functionality is controlled by text search configurations.
246 PostgreSQL comes with predefined configurations for many languages, and
247 you can easily create your own configurations. (psql's \dF command
248 shows all available configurations.)
250 During installation an appropriate configuration is selected and
251 default_text_search_config is set accordingly in postgresql.conf. If
252 you are using the same text search configuration for the entire cluster
253 you can use the value in postgresql.conf. To use different
254 configurations throughout the cluster but the same configuration within
255 any one database, use ALTER DATABASE ... SET. Otherwise, you can set
256 default_text_search_config in each session.
258 Each text search function that depends on a configuration has an
259 optional regconfig argument, so that the configuration to use can be
260 specified explicitly. default_text_search_config is used only when this
263 To make it easier to build custom text search configurations, a
264 configuration is built up from simpler database objects. PostgreSQL's
265 text search facility provides four types of configuration-related
267 * Text search parsers break documents into tokens and classify each
268 token (for example, as words or numbers).
269 * Text search dictionaries convert tokens to normalized form and
271 * Text search templates provide the functions underlying
272 dictionaries. (A dictionary simply specifies a template and a set
273 of parameters for the template.)
274 * Text search configurations select a parser and a set of
275 dictionaries to use to normalize the tokens produced by the parser.
277 Text search parsers and templates are built from low-level C functions;
278 therefore it requires C programming ability to develop new ones, and
279 superuser privileges to install one into a database. (There are
280 examples of add-on parsers and templates in the contrib/ area of the
281 PostgreSQL distribution.) Since dictionaries and configurations just
282 parameterize and connect together some underlying parsers and
283 templates, no special privilege is needed to create a new dictionary or
284 configuration. Examples of creating custom dictionaries and
285 configurations appear later in this chapter.