Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL ts_filter: How to Filter Full Text Search

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL does not have a built-in function literally named ts_filter in its core distribution; instead, "ts_filter" refers to the architectural pattern of using tsvector and tsquery operators to filter datasets based on linguistic relevance. To achieve a filtered full-text search, you use the @@ match operator combined with to_tsvector and to_tsquery (or plainto_tsquery) to isolate rows that contain specific lexemes while excluding others. This process allows you to transform raw text into a searchable document format and then apply a boolean filter to retrieve only the most relevant records.

What You'll Need

  • A running instance of PostgreSQL (Version 9.6 or newer is recommended for modern FTS features).
  • A database table containing text columns that you wish to search.
  • Superuser or table-owner permissions to create indexes (GIN indexes) for performance.
  • Basic knowledge of SQL queries and the concept of lexemes (the root form of a word).

Step-by-Step

  1. Identify your searchable columns. Determine which columns in your table contain the text you need to filter. For example, if you have a products table, you might want to filter by both product_name and product_description.
  2. Convert text to a tsvector. The to_tsvector() function takes a string and converts it into a tsvector, which is a sorted list of distinct lexemes. For a basic filter, you can call this in your WHERE clause: to_tsvector('english', product_description). This tells PostgreSQL to use the English dictionary to stem words (e.g., "running" becomes "run").
  3. Create a tsquery for your filter. Use to_tsquery() to define the search terms. This function requires boolean operators. For example, to_tsquery('english', 'smart & home') will filter for documents containing both "smart" and "home". If you want a more user-friendly input that doesn't require operators, use plainto_tsquery('english', 'smart home'), which automatically inserts the AND operator between words.
  4. Apply the match operator (@@). The @@ operator is the core of the filtering mechanism. It returns a boolean true if the tsquery matches the tsvector. Construct your query as follows:
    SELECT * FROM products WHERE to_tsvector('english', product_description) @@ to_tsquery('english', 'smart & home');
  5. Implement advanced boolean filtering. To refine your filter further, use the OR (|) and NOT (!) operators within your tsquery. For instance, to find products that are "smart" but NOT "bulbs", use: to_tsquery('english', 'smart & !bulbs'). This allows you to create highly specific filters that remove noise from your search results.
  6. Optimize with a GIN Index. Running to_tsvector on every row during a search is slow for large datasets. To make your filter performant, create a Generalized Inverted Index (GIN). You can do this by creating a stored generated column or using a functional index:
    CREATE INDEX idx_fts_description ON products USING GIN (to_tsvector('english', product_description));
    Once the index is created, PostgreSQL will use it to instantly find matching rows instead of scanning the entire table.
  7. Rank and sort the filtered results. Filtering only tells you if a row matches; it doesn't tell you how well it matches. Use the ts_rank or ts_rank_cd function to order your filtered results by relevance. This ensures that the most relevant documents appear at the top of your list:
    SELECT product_name, ts_rank(to_tsvector('english', product_description), query) AS rank
    FROM products, to_tsquery('english', 'smart & home') query
    WHERE to_tsvector('english', product_description) @@ query
    ORDER BY rank DESC;

Common Mistakes

One of the most frequent errors is mismatching the configuration language. If you use to_tsvector('english', ... ) but use to_tsquery('spanish', ... ), the filter will likely return zero results because the stemming rules for English and Spanish differ. Always ensure the language configuration is consistent across both functions.

Another common mistake is neglecting the difference between to_tsquery and plainto_tsquery. New users often pass a raw user-input string directly into to_tsquery. If the user enters a space or a special character that isn't a valid boolean operator, PostgreSQL will throw a syntax error. Always use plainto_tsquery or websearch_to_tsquery for raw user input to avoid application crashes.

Many developers forget to index the exact expression used in the WHERE clause. If your index is created on to_tsvector('english', name) but your query uses to_tsvector('simple', name), the index will be ignored, and the database will perform a slow sequential scan of the entire table.

Tips

For maximum efficiency, use a stored tsvector column. Instead of calculating the vector on the fly, add a column of type tsvector to your table and use a trigger or a generated column to keep it updated. This reduces the CPU load during search operations significantly.

If you need to search across multiple columns (e.g., Title and Body), concatenate them within the to_tsvector function. You can assign different weights to different columns using setweight(). For example, a match in the Title (Weight 'A') should be ranked higher than a match in the Body (Weight 'D'). This makes your filtering logic much more sophisticated.

Consider using websearch_to_tsquery if you are building a public-facing search bar. This function supports "quoted phrases" for exact matches and the minus sign (-) for exclusion, mimicking the behavior of modern web search engines without requiring the user to know PostgreSQL syntax.

Troubleshooting

If your filter is returning no results when you know the text exists, first check the stemming. Run SELECT to_tsvector('english', 'your text here'); to see exactly how PostgreSQL is breaking down the words. You might find that a word is being stopped (removed) because it is considered a common word (like "the" or "and") by the English dictionary.

If the query is extremely slow despite having an index, run EXPLAIN ANALYZE on your query. Look for "Seq Scan" in the output. If you see a sequential scan instead of a "Bitmap Index Scan," it means your WHERE clause does not exactly match the expression used in your index definition. Ensure the language and the column order are identical.

If you encounter "syntax error in tsquery," it is almost certainly because you are using to_tsquery with input that contains spaces or unsupported characters. Switch to plainto_tsquery or sanitize the input string to ensure only &, |, and ! are used as separators.

Frequently Asked Questions

What is the difference between to_tsquery and plainto_tsquery?

to_tsquery requires explicit boolean operators (AND, OR, NOT) and will fail if they are missing. plainto_tsquery takes a plain string, ignores punctuation, and automatically joins all words with the AND operator.

Can I filter by a specific phrase instead of individual words?

Yes, use phraseto_tsquery. Unlike the standard query functions, this ensures that the lexemes appear in the specified order and are adjacent to one another in the document.

How do I exclude specific words from my search filter?

Use the NOT operator (represented by !) in your tsquery. For example, to_tsquery('english', 'postgresql & !mysql') will find documents containing PostgreSQL but excluding any that mention MySQL.

Does full text filtering work with non-English languages?

Yes, PostgreSQL supports many languages. You simply replace 'english' with the appropriate configuration, such as 'french', 'german', or 'simple' (which does no stemming and just splits by whitespace).

Is a GIN index always the best choice for ts_filter?

For most full-text search scenarios, GIN (Generalized Inverted Index) is the best choice because it is optimized for reading. While GiST indexes are faster to update, they are significantly slower to query for text search.