Skip to content
ImagineWorld

Analyzing Text Documents in PostgreSQL

node_idnode-book_ai-ready-postgresql-18_chapter-14-analyzing-text-documents-in-postgresql
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleAnalyzing Text Documents in PostgreSQL
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 14 — Analyzing Text Documents in PostgreSQL

Section titled “Chapter 14 — Analyzing Text Documents in PostgreSQL”

Texts and documents have become an increasingly important part of what is stored and managed in databases. Historically, developers reverted to specialized text-search tools to extract value from that textual data. However, PostgreSQL’s growing polymorphic (or multi-model) capabilities mean that developers can not only store documents in PostgreSQL but also analyze them without resorting to third-party tools.

In this chapter, we will review the text-search capabilities in PostgreSQL:

  • Simple pattern-based search using LIKE
  • Complex pattern searching using regular expressions
  • Full-text search using tsvector and tsquery
  • Fuzzy search using pg_trgm

They each have different strengths and weaknesses, which make them the tool of choice for specific use cases. We will provide guidance on when to use which capability.

The sample code for this chapter is available in psql_scripts / sample_scripts /chapter_14.sql. We encourage you to connect to the central_analytics database and follow the examples!

Text as a key data type in advanced analytics

Section titled “Text as a key data type in advanced analytics”

Historically, text storage in relational databases was limited to short character strings, such as names of people, places, or products. Longer texts, such as detailed product descriptions, meeting reports, and clinical exam protocols, were traditionally stored in document-focused specialty databases or on network drives. The general impression was that relational databases could not handle the data volume and lacked the necessary text-search capabilities.

Recent developments changed that:

  • Relational databases, including PostgreSQL, became capable of handling much larger datasets. Partitioning, faster I/O, improved storage devices, better data compression, and enhanced backup/recovery methods were key drivers for that development. 10 years ago, a PostgreSQL database with 1 terabyte (TB) of data was considered large; today, users report data sizes of 100+ TB in a single database!
  • Integrating the analysis of “softer” data, for example, full-text documents, became increasingly important to the business. Finding customer names, product names, locations, medical diagnoses, and other data points in text documents within a single database query saves time and reduces operational complexity.
  • Databases and applications are increasingly accessed by untrained users or customers who want to access data “their way.” For example, when they search for a store in a specific town, they don’t want to be stymied by spelling issues. When they search for an address in ” San Frncisco,” they expect the database to deal with the typo.

PostgreSQL provides several ways to address these points:

  • LIKE-based pattern matching for low-volume and simple applications
  • POSIX regular expression matching using the ~ operator
  • Vector-based full-text search (FTS) that supports word stemming, complex patterns, ranking, and headlining
  • Trigram search for similarity-based fuzzy pattern matching

We will review and explain each one and conclude with guidance for the developer.

The LIKE operator in SQL is the most widely used and easiest to implement text-search operator. But it is also the slowest and least capable!

This is a simple example of the LIKE operator:

SELECT DISTINCT p.id, p.label AS product, b.label AS brand FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE longdescription LIKE '%shirt%';

The LIKE operator matches against simple expressions, where % matches multiple characters and _ matches a single character:

SELECT DISTINCT p.id, p.label AS product, b.label AS brand FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE p.label LIKE '_olo%';

More complex patterns are also supported, such as this one that matches any string that includes Oxford before Shirt:

SELECT DISTINCT p.id, p.label AS product, b.label AS brand FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE p.label LIKE '%Oxford%Shirt%';

The LIKE operator has a variant, ILIKE, that is case-insensitive. LIKE also has other capabilities, such as the casefold () function introduced in PostgreSQL 18, which provides a global, Unicode-compatible way of working with strings regardless of uppercase/lowercase. The LIKE operator can also leverage GIN, but only for left-aligned search terms, that is, search terms that appear at the beginning of a text – for example, Shirt%, which would match Shirts for business but not White S hirts for business.

LIKE quickly hits its limits. The following query provides the expected results, as the pattern matches the sequence of the words in the target column:

SELECT DISTINCT p.id, p.label, b.label FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE p.label ILIKE '%Men%Oxford%shirt%';

The following one, however, doesn’t, as the sequence of words in the search pattern does not match – even though all the individual words are present:

SELECT DISTINCT p.id, p.label, b.label FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE p.label ILIKE '%Oxford%shirt%Men';

LIKE / ILIKE is easy to use, but its capabilities are limited. Because it uses indexes only in exceptional cases, it does not scale.

PostgreSQL supports POSIX regular expression matching using the ~ operator:

  • ~ is used for case-sensitive matching of regular expressions
  • ~* is like ~, but is not case sensitive
  • !~ is true if there is no case-sensitive match
  • !~* is like !~, but is not case sensitive

These expressions are much more powerful than the ones that can be used in the LIKE expression and give the developer full access to regular expressions. Simple expressions look very much like the LIKE statement, except that the % wildcard has been replaced by the regex wildcard .*:

SELECT DISTINCT p.id, p.label, b.label FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE p.label ~* 'Men.*Oxford.*shirt';

Besides the ~ operator, PostgreSQL regex also provides a plethora of other functions, such as regexp_count, regexp_instr, regexp_like, and regexp_match. Developers comfortable with regex have access to a wide array of pattern matches, for example, the ability to match a description that starts with Chinos and ends with either Boss or The Gap:

SELECT DISTINCT p.id, p.label, b.label FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE p.label ~* '^Chinos .* (Boss|The Gap)$';

Regular expressions in PostgreSQL do not leverage general indexes, except for functional indexes that focus on specific expressions, such as URLs, or B-tree indexes to match expressions anchored to the beginning of the string. Regular expressions can be slow and often don’t scale for general-purpose use, but they are frequently used for data cleansing.

Full-text search with tsvector and tsquery

Section titled “Full-text search with tsvector and tsquery”

LIKE and the POSIX regular expression both use a simple pattern matching approach, which is at the heart of their limitations. Fortunately, PostgreSQL FTS, which uses a vectorized model, is much more capable and scalable. FTS transforms text data into text-search vectors (tsvector), an optimal format for complex searches that can be queried effectively and efficiently with tsquery, a specialized query format.

In PostgreSQL, we use the to_tsvector function to transform a text into a text-search vector (tsvector). to_tsvector goes through two steps – stemming and vectorization:

  • Stemming: Texts are transformed into a list of word stems (a.k.a. lexemes) that are normalized to represent different variants of the same word
  • Vectorization: Texts are represented as vectors of word stems and their positions

For example, let’s consider this query:

SELECT to_tsvector(
'english',
'A shirt is not like a T-shirt, even though they both use the string shirt');

It produces an alphabetical vector of word stems and their positions in the input text:

to_tsvector
--------------------------------------------------------------------------------
'even':10 'like':5 'shirt':2,9,17 'string':16 't-shirt':7 'though':11 'use':14

This simplified representation makes it easy to match complex patterns, for example, sequences of words, or just occurrences of words, and more advanced queries, such as shirt, but not T-shirt.

The to_tsvector function uses language-specific dictionaries to identify words and extract their stems (lexemes). Other dictionaries are employed to recognize stop words, such as the, and, and or, which are ignored when constructing the vector. Users can also add custom dictionaries for specialized areas to handle synonyms and abbreviations that should all map to the same lexeme.

Text-search vectors are stored in separate columns and can be indexed using GIN or GiST:

  • GIN indexes are generally preferred because they have higher lookup performance, as they are inverted indexes that map lexemes to the documents where they appear. However, GIN indexes are slower to update than GiST indexes.
  • GiST indexes are used for dynamic, fast-changing data where write performance outweighs read performance requirements.

For an in-depth review of indexes, see Chapter 7, Designing for High - Transaction Volumes and Writing Efficient Transactional Code.

Text-search queries are specified as lexemes and operators. For example, to specify a search for shirts from The Gap, the to_tsquery function creates a simple query pattern from a set of lexemes:

SELECT to_tsquery('english', 'Oxford&Shirts&Gap');

It converts the words Oxford, Shirts, and Gap into their lexemes. Note the lowercasing and the omitted plural s:

to_tsquery
----------------------------
'oxford' & 'shirt' & 'gap'

to_tsquery is the basic function to generate text-search queries and can be used with word stems and operators to create complex AND (&), OR (|), and FOLLOWED BY (< - >) queries.

phraseto_ tsquery is more flexible and generates the text-search query with operators based on the sequence in a phrase:

SELECT phraseto_tsquery('english', 'Oxford Shirt from the Gap');

This converts the words to lexemes but also adds sequence information:

phraseto_tsquery
--------------------------------
'oxford' <-> 'shirt' <3> 'gap'

This means that shirt must follow oxford and that gap should be the third lexeme after shirt.

websearch_to_tsquery is even more flexible and powerful. It recognizes specific keywords as operators to construct even more powerful queries:

SELECT websearch_to_tsquery(
'english',
'T-Shirt from the Gap or Oxford Shirt from the gap');

It automatically derives sequences and alternatives and is often used to convert web searches into SQL queries:

websearch_to_tsquery
------------------------------------------------------------
't-shirt' <2> 'shirt' & 'gap' | 'oxford' & 'shirt' & 'gap'

To satisfy this query, the word t-shirt should precede the combination of the words shirt and gap, or the three words oxford, shirt, and gap should be in the text.

As described earlier, we use to_tsvector or one of its variants to generate the vectorized representation that we match against the output of to_tsquery. Generating the vectorized representation of the text every time we run a query would be terribly inefficient.

Instead, we add a generated and stored column to our table, populate it with text-search vector data, index it, and run our searches against that column.

In our example, we want to search the textual information associated with our products: the label, the short description, and the long description. To that purpose, we add the infotext_tsv column of type tsvector to the product table.

This column stores the text-search vector information resulting from the combination of three text fields: label, short description, and long description. The column is a generated column, ensuring it’s continuously updated, and it’s a stored column, which means we can index it:

ALTER TABLE product
ADD COLUMN infotext_tsv tsvector
GENERATED ALWAYS AS (
to_tsvector('english',
-- cannot use format here as it's not immutable
coalesce(label,'') || ' ' ||
coalesce(shortdescription,'') || ' ' ||
coalesce(longdescription,'')
)
) STORED;

We add a GIN index to that column to improve query efficiency:

-- create an index on the tsvector column
CREATE INDEX idx_product_infotext_tsv ON product USING GIN (infotext_tsv);

Now we can run our first FTS queries:

SELECT DISTINCT p.id, p.label product, b.label brand FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE p.infotext_tsv @@
plainto_tsquery('english', 'An Oxford shirt from the Gap');

The FTS automatically found matching entries in the product table using the search pattern:

id | product | brand
----+--------------------------------------+-------
4 | Mens Classic Oxford Shirt by The Gap | Gap

When we use websearch_to_ tsquery, we can run much more complex queries:

SELECT DISTINCT p.id, p.label product, b.label brand FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE p.infotext_tsv @@
websearch_to_tsquery(
'english',
'T-Shirt from the Gap or Oxford Shirt from the gap');

In this case, an OR condition was added (see above), and FTS found two matching entries:

id | product | brand
----+--------------------------------------+-------
4 | Mens Classic Oxford Shirt by The Gap | Gap
6 | T-Shirt by The Gap | Gap

Figure 1 4*.1* shows how the to_tsvector and websearch_to_tsquery functions, the tsvector data type, and the FTS @@ match operator work together.

Figure 14.1: The interaction of the PostgreSQL FTS building blocks

In our example, we combined the label, short description, and long description of our products into a single text vector to serve as the foundation for the FTS. What if we decide that the information on the label is more pertinent than that in the short and long descriptions, and that it should carry greater weight?

Text-search vectoring allows us to do that by assembling a vector from several component vectors, each with a different weight.

In the following example, we state that the information in the label column is more critical than the short description, which in turn is more important than the long description:

ALTER TABLE product
ADD COLUMN infotext_tsv tsvector
GENERATED ALWAYS AS (
setweight (to_tsvector('english', COALESCE(label, '')), 'A') ||
setweight (to_tsvector('english', COALESCE(shortdescription, '')), 'B') ||
setweight (to_tsvector('english', COALESCE(longdescription, '')), 'C'
)
) STORED;

Weights are handy when working with complex texts. For example, when searching in blogs or articles, we might give the title, tagline, and abstract higher weights than the body, since the body is more likely to match many lexemes. In contrast, the title, tagline, and abstract are more likely to focus on key elements.

The preceding examples used FTS in a binary mode: either a row is in the result set or it isn’t. PostgreSQL FTS also allows us to rank results. In the following code block, we are using the same query, but instead of using it in the WHERE clause, we use ts_rank to rank the results:

SELECT DISTINCT p.id, p.label as product_label, b.label as brand_label,
ts_rank(p.infotext_tsv,
websearch_to_tsquery(
'english',
'T-Shirt from the Gap or Oxford Shirt from the gap')) AS rank
FROM product p
JOIN brand b ON p.brand_id = b.id
ORDER BY rank DESC
LIMIT 5;

Instead of just giving us two results (ranked above a match of 0.5), we get a longer list of matches in decreasing order:

id | product_label | brand_label | rank
----+--------------------------------------+-------------+------------
6 | T-Shirt by The Gap | Gap | 0.51621455
4 | Mens Classic Oxford Shirt by The Gap | Gap | 0.51537025
7 | T-Shirt by Diesel | Diesel | 0.34903458
5 | Mens Classic Oxford Shirt from Boss | Boss | 0.34819028
1 | Dress shirt by The Gap | Gap | 0.3431678

Ranking helps us do more than just true/false binary searches and adds incredible flexibility to FTS.

Sometimes, users want to understand why a text document was selected. Headlining highlights the text that matches a query:

SELECT DISTINCT p.id, p.label as product_label, b.label as brand_label,
ts_rank(p.infotext_tsv,
websearch_to_tsquery(
'english',
'T-Shirt from the Gap or Oxford Shirt from the gap')) AS rank,
ts_headline(p.label || ' '|| p.shortdescription|| ' '|| p.longdescription,
websearch_to_tsquery(
'english',
'T-Shirt from the Gap or Oxford Shirt from the gap')) AS snippet
FROM product p
JOIN brand b ON p.brand_id = b.id
ORDER BY rank DESC
LIMIT 3;

The ts_headline command pulls relevant text fragments from the source text and highlights all words that appear in the query:

id | product_label | brand_label | rank| snippet
----+-----------------+-------------+-----+-------------------
6 | T-Shirt by Th...| Gap |0.51 | T-<b>Shirt</b> by The <b>Gap</b> Short
| | | sleeved fitted T-<b>shirt</b> from
| <b>Gap</b>
4 | Mens Classic ...| Gap |0.51 | <b>Oxford</b> <b>Shirt</b> by The
| <b>Gap</b> Timeless mens <b>Oxford</b>
| <b>shirt</b> in 100% cotton
7 | T-Shirt by D... | Diesel |0.34 | T-<b>Shirt</b> by Diesel Short sleeved
| fitted T-<b>shirt</b> by Diesel Mens T
(3 rows)

Note that the output has been manually formatted and abbreviated for readability.

< b > & lt``;``/ b > is the default format for highlights. This default, just like the length and details of the headlines, is fully configurable.

The headline feature, in combination with weighting and ranking, makes it easier to work with large documents and helps explain why a document was included in the results.

Using PostgreSQL FTS in combination with regular queries

Section titled “Using PostgreSQL FTS in combination with regular queries”

The real strength of PostgreSQL’s polymorphism appears when we combine FTS with conventional queries. Now we get the best of both worlds: a flexible FTS engine with multi-lingual capabilities, stemming, pattern matching, and vectorization, combined with the power of SQL. The following query shows how to combine a text query (edgy and cool shirt or t-shirt) with a standard SQL condition (price < 50):

SELECT p.id, p.label,
FORMAT ('%s-%s', MIN(pvp.price), MAX (pvp.price)) AS price_range
FROM product p
JOIN product_variant pv ON p.id = pv.product_id
JOIN product_variant_price pvp ON pv.id = pvp.product_variant_id
WHERE p.infotext_tsv @@
websearch_to_tsquery(
'english',
'edgy and cool shirt or t-shirt')
AND pvp.price < 50
GROUP BY p.id, p.label
ORDER BY MAX( pvp.price) desc;

The results are filtered by both conditions – the text search for the edgy and cool t-shirt, and the price of less than $50:

id | label | price_range
----+-----------------------+-------------
7 | T-Shirt by Diesel | 29.05-32.69
6 | T-Shirt by The Gap | 29.00-32.64
23 | Nike Athletic T-Shirt | 25.12-28.27

PostgreSQL FTS is a powerful tool, especially when used alongside standard SQL queries.

Conventional approaches might have used two different solutions, one for the text search and one for the SQL query, combined with custom code to merge the results.

This would not only have been harder to manage (licensing, patching, maintenance, and data updates) but would also have resulted in worse performance and required significant amounts of custom code.

, Multi-Modal Reasoning: Combining AI Vectors with Standard SQL will introduce another form of vectorization using AI and pgvector, where we encode semantic information (a.k.a. embeddings) to calculate similarity. Whereas PostgreSQL FTS uses word stemming and dictionaries to vectorize syntactical information, the AI/ pgvector approach leverages LLMs to vectorize semantic information.

PostgreSQL trigram-based similarity search and fuzzy matching

Section titled “PostgreSQL trigram-based similarity search and fuzzy matching”

Text searches using LIKE or tsvector always rely on correct spelling; a simple typo can cause them to return no results. Trigram-based similarity searches help us address this problem by introducing fuzzy matching of character strings or phrases.

The pg_trgm extension, part of the standard PostgreSQL distribution, decomposes strings into groups of three characters. If needed, the trigrams are padded with blanks. p g_trgm determines string similarity by counting how many of those trigrams are found in both strings.

This example decomposes the string Uniqlo and a misspelling of that brand to illustrate trigram-based fuzzy matching:

SELECT
show_trgm('Uniqlo'),
show_trgm('Uniclo'),
similarity('Uniqlo','Uniclo'),
word_similarity('Uniqlo','Uniclo');

We can see that Uniqlo and Uniclo share several trigrams (u, ni, lo, uni), which helps establish the degree of similarity:

-[ RECORD 1 ]---+------------------------------------
show_trgm | {" u"," un",iql,"lo ",niq,qlo,uni}
show_trgm | {" u"," un",clo,icl,"lo ",nic,uni}
similarity | 0.4
word_similarity | 0.42857143

The similarity function identifies the ratio of three-character strings that match in both words: number of matching trigrams / *(*number of trigrams in string1 + number of trigrams in string2 – number of matching trigrams). The word_similarity function checks how many trigrams of the first word match those of the second.

When we use pg_trgm in queries, we can configure the similarity threshold required for a match.

One obvious way to put this capability to work is to help users deal with spelling issues in people’s or product names:

SELECT p.id, p.label AS product, b.label AS brand FROM product p
JOIN brand b ON p.brand_id = b.id
WHERE b.label % 'Uniclo';

This query, with a misspelled brand name (Uniclo instead of Uniqlo), will nevertheless return the expected result:

id | product | brand
----+--------------------+--------
26 | Uniqlo Down Jacket | Uniqlo

This type of fuzzy matching is also beneficial for data cleansing, for example, to identify matching but misspelled names or addresses.

Auto-completes, or type-ahead searches, are another use case for trigrams. Using the similarity() function, we can easily propose auto-completions:

CREATE FUNCTION type_ahead_product_search(search_text TEXT, limit_results INT DEFAULT 5)
RETURNS TABLE (product_label TEXT, simi REAL) AS $$
BEGIN
RETURN QUERY
SELECT label::TEXT, similarity(label, search_text) AS simi FROM product
WHERE label ILIKE search_text || '%'
ORDER BY simi DESC
LIMIT limit_results;
END;
$$ LANGUAGE plpgsql;

When we call the preceding function in a web search for products, with the initial entry of Casual Leather Jacket, it will tell us that, based on the available products in the database, there are two possible completions – by Boss or by Aeropostale:

SELECT * FROM type_ahead_product_search('Casual Leather Jacket', 2);
product_label | simi
--------------------------------------+-----------
Casual Leather Jacket by Boss | 0.7586207
Casual Leather Jacket by Aeropostale | 0.5945946

Trigram searches are extremely performant when supported by a GIN index, and this approach scales to hundreds of thousands of rows.

The unaccent extension is a valuable helper function. It removes the diacritics, or accents, from words:

CREATE EXTENSION IF NOT EXISTS unaccent;
SELECT unaccent('Café Münsterländer');

The é, ü, and ä diacritics have been replaced to avoid unintentional search failures:

unaccent
--------------------
Cafe Munsterlander
(1 row)

Accents are a widespread cause of search failures. In general, it pays to apply the unaccent function if there are any accents (e.g., é or à), contractions (e.g., ¼), or other diacritics (e.g., ä, ç, ñ, or ü) in either the query text or the query target.

The unaccent() function can easily be applied in a LIKE or ILIKE statement. For text-search vectors, the unaccent extension provides a special dictionary that can be included in the text-search configuration to ensure all diacritics are removed when producing lexemes. Remember that indexes also need to leverage the unaccent function in that case!

The four text-search capabilities have very different, complementary use cases. Table 14.1 will help developers choose the right option for their use case:

PostgreSQL CapabilityLIKERegular ExpressionsText- S earch V ectorsTrigrams
Primary use casePattern matching with wildcards (%, _)Pattern matching (~, ~*)Word-based FTSFuzzy matching, text similarity
Approach to matchingSimple patternsComplex pattern matchingWord-based, ranked relevanceCharacter-based trigrams; can find similar words or substrings
IndexingB-tree for prefix searchesLimited index supportGIN and GiSTGIN and GiST
Performance and scalabilityPoor performance on large tables. Often slow for middle of string matches.Medium performanceHigh performance and highly scalableHigh performance and highly scalable

Table 14.1: When to use which text-search capability in PostgreSQL

  • Use LIKE: For simple, precise pattern matching when performance is not a major concern, especially for prefix matches (Postgres%) where a B-tree index can be used efficiently Example: Filtering email addresses by name or domain
  • Use regular expressions: When searching for complex patterns during data cleansing Example: Search for internet addresses in texts
  • Use tsvector: For high-performance FTS where you want to find documents based on words, relevance ranking, and stemming Example: Searching blogs and providing a relevance ranking
  • Use pg_trgm: For fuzzy matching and identifying similar text Example: Users look for a product by name or vendor

In this chapter, we reviewed PostgreSQL’s robust text-search features. Combined with PostgreSQL’s increasing scalability, these capabilities enable developers to integrate SQL-based analytics with text search, creating a compelling, versatile business platform that integrates traditional SQL processing with various forms of text analytics. This not only helps keep it simple and avoid integrating third-party text-search solutions but also enables powerful business solutions that handle multilingual spelling, typos, auto-complete, and the analysis of large document sets.

This chapter focused on PostgreSQL’s syntactical text-search capabilities (LIKE, regular expression, FTS, and trigrams). They find strings based on word similarity, not based on meaning.

In the following chapters, we will explore the use of AI and embeddings. Embeddings, represented as AI vectors, enable us to work with the semantics and meaning of polymorphic data, such as text and images. You will learn that just like text search, AI-based embeddings and vectors integrate tightly with PostgreSQL’s SQL capabilities.