Skip to content

Updated

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 finds documents or records that contain specific words or phrases. The following table compares it with semantic search:

Keyword searchSemantic search
MatchesMainly an exact match between the search terms and the textThe meaning behind the query, even if the exact words aren't in the text
ConsidersThe specific words or phrases in the querySynonyms, intent, and natural language nuances
ReturnsResults that contain the search terms, or normalized forms of them, such as egg for eggsResults 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:

  1. to_tsvector() converts your data into searchable tokens. Together, these tokens are called a document.
  2. to_tsquery() converts the search query into tokens to match, so a search for eggs can still match a value of egg.
  3. The @@ operator tests whether the document matches the query and returns a boolean. A where clause uses that result to select matching rows.

For each function and its options, see Full text 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.