Keyword search
Knowing when keyword search beats semantic search tells you which one to build for your app. For how to set up keyword search in Postgres, see Full text search.
Keyword search vs semantic search
Keyword search finds documents or records that contain specific words or phrases. The following table compares it with semantic search:
| Keyword search | Semantic search | |
|---|---|---|
| Matches | Mainly an exact match between the search terms and the text | The meaning behind the query, even if the exact words aren't in the text |
| Considers | The specific words or phrases in the query | Synonyms, intent, and natural language nuances |
| Returns | Results that contain the search terms, or normalized forms of them, such as egg for eggs | Results that are contextually related to the query |
How keyword search works
In Postgres, keyword search is implemented using full-text search. It supports indexing and text analysis for data retrieval, focusing on records that match the search criteria. Postgres' full-text search extends beyond keyword matching to address linguistic nuances, making it effective for applications that require precise text queries.
A full-text search works in three steps:
to_tsvector()converts your data into searchable tokens. Together, these tokens are called a document.to_tsquery()converts the search query into tokens to match, so a search foreggscan still match a value ofegg.- The
@@operator tests whether the document matches the query and returns a boolean. Awhereclause uses that result to select matching rows.
For each function and its options, see Full text search.
When to use keyword search
Keyword search is useful where precision and specificity matter. It's more effective than semantic search in the following cases:
- Users search with exact terminology or specific identifiers.
- Results must contain those terms, or their normalized forms, so that information that's semantically related but not what the user seeks stays out.
For example, in technical or academic research databases, researchers often search for specific studies, compounds, or concepts identified by certain terms or codes. Searching for a specific chemical compound using its exact molecular formula or a unique identifier will yield more focused and relevant results compared to a semantic search, which could return a wide range of documents discussing the compound in different contexts.
You can also combine keyword search with semantic search, which is called hybrid search.
Related resources
- Full text search: store, index, and query records with Postgres full-text search.
- Semantic search: search by meaning instead of exact terms.
- Hybrid search: combine keyword and semantic search.