Skip to content
Aurabase Logo
aurabase

Full-text search

Find rows by the words they contain, in the right language, sorted by relevance, fast on large tables, and tolerant of typos.

How-to guide11 min readLevel intermediate

PostgreSQL full-text search turns text into a list of normalized words (a tsvector) and matches it against a query (a tsquery): reading and reads both match read, and common words such as the are ignored. Aurabase exposes it through the SDK filter textSearch(), the REST operators fts, plfts, phfts and wfts, the endpoint POST /v1/db/{table}/search, and SQL. The examples follow PostgreSQL 18.

Prerequisites#

  • A linked project: aura link <project-id>.

  • The example schema, installed with the service role key of the project:

    export AURABASE_SERVICE_ROLE_KEY=aura_sk_…
    aura db seed --example docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See Example schema.

  • AURABASE_URL and AURABASE_ANON_KEY in the environment, for the SDK and curl examples.

The examples create the table qd_fts_articles and the functions qd_fts_search and qd_fts_fuzzy, read them with the service_role key, then remove them.

Choose a method#

MethodLanguageRankingSpeed on large tablesTypos
textSearch() on a tsvector column with a GIN indexFixed in the column definitionNo (sort by another column)FastNo
textSearch() on a text columnconfig option, english by defaultNoScans every rowNo
A function with ts_rank, called with rpc()YoursYes, with highlightsFast with the indexNo
POST /v1/db/{table}/searchFrench, fixedYes (_rank)Scans every rowNo
Trigrams (pg_trgm) in a functionAnyBy similarityFast with a GIN trigram indexYes
ilike('%word%')NoneNoFast with a trigram indexNo

A searchable table#

Store the tsvector in a generated column, so PostgreSQL keeps it up to date, and index it with GIN:

create table qd_fts_articles (
  id int primary key,
  title text not null,
  body text not null,
  search tsvector generated always as (
    setweight(to_tsvector('english', title), 'A') || setweight(to_tsvector('english', body), 'B')
  ) stored
);
create index qd_fts_articles_search on qd_fts_articles using gin (search);
insert into qd_fts_articles (id, title, body) values
  (1, 'Getting started with Postgres', 'Create a table, insert rows and read them back.'),
  (2, 'Row level security', 'Policies decide which rows each user reads and writes.'),
  (3, 'Search your data', 'Full-text search ranks documents by the words they contain.'),
  (4, 'Indexes for faster reads', 'A GIN index makes text search fast on large tables.');
  ℹ No results (0 rows).

setweight marks title words as more important (A) than body words (B), which ranking uses below. The generated column is read-only: you insert title and body, never search.

textSearch(column, query, options) adds a full-text filter. On the tsvector column, it uses the index:

import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const { data, error } = await admin
  .from('qd_fts_articles')
  .select('title')
  .textSearch('search', 'reading', { type: 'plain', config: 'english' })
  .order('id')
console.log(data, error)
[
  { title: 'Getting started with Postgres' },
  { title: 'Row level security' },
  { title: 'Indexes for faster reads' }
] null

reading matched read and reads in three articles: all three are reduced to the word read. Over REST:

curl -s --get "$AURABASE_URL/v1/db/qd_fts_articles" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  --data-urlencode 'select=title' --data-urlencode 'search=wfts(english).search -security'
echo
{"data":[{"title":"Search your data"},
 {"title":"Indexes for faster reads"}],"meta":{}}

On a plain text column, textSearch('body', 'policies') also works: PostgreSQL converts the text on the fly for every row, with the english configuration unless you pass config. That is fine for small tables; add a tsvector column and an index before the table grows.

Query syntaxes#

typeREST operatorPostgreSQL functionInput
(none)ftsto_tsqueryOperators written by you: postgres & !mysql, search <-> data, read:* (prefix).
'plain'plftsplainto_tsqueryPlain words, all required.
'phrase'phftsphraseto_tsqueryWords in this order.
'websearch'wftswebsearch_to_tsqueryWhat users type: "exact phrase", or, -excluded.
import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const titles = async (q: any) => {
  const { data, error } = await q
  return error ? `${error.status} ${error.code} ${error.message}` : data.map((r: any) => r.id).join(',')
}
const q = () => admin.from('qd_fts_articles').select('id').order('id')

console.log('fts prefix:  ', await titles(q().textSearch('search', 'index:*', { config: 'english' })))
console.log('fts and/not: ', await titles(q().textSearch('search', 'rows & !policies', { config: 'english' })))
console.log('plain:       ', await titles(q().textSearch('search', 'text search', { type: 'plain', config: 'english' })))
console.log('phrase:      ', await titles(q().textSearch('search', 'row level', { type: 'phrase', config: 'english' })))
console.log('websearch:   ', await titles(q().textSearch('search', '"text search" or policies', { type: 'websearch', config: 'english' })))
console.log('bad syntax:  ', await titles(q().textSearch('search', 'rows &', { config: 'english' })))
fts prefix:   4
fts and/not:  1
plain:        3,4
phrase:       2
websearch:    2,3,4
bad syntax:   400 POSTGREST_ERROR no operand in tsquery: "rows &"

Pass user input with 'websearch' or 'plain': they never fail on syntax. Use the default to_tsquery syntax only for queries your code writes. Always pass the same config as the one used to build the tsvector, or words may be normalized differently.

Rank and highlight results#

A filter only keeps or drops rows. To sort by relevance and show the matching words, write a function with ts_rank and ts_headline, and call it with rpc():

create function qd_fts_search(p_query text)
returns table (id int, title text, rank real, snippet text)
language sql stable as $$
  select a.id, a.title,
         ts_rank(a.search, q) as rank,
         ts_headline('english', a.body, q, 'StartSel=[, StopSel=]') as snippet
  from qd_fts_articles a, websearch_to_tsquery('english', p_query) q
  where a.search @@ q
  order by rank desc, a.id
  limit 20
$$;
  ℹ No results (0 rows).
import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const { data, error } = await admin.rpc('qd_fts_search', { p_query: 'search' })
if (error) throw error
for (const r of data) console.log(r.rank.toFixed(3), r.title, '|', r.snippet)
0.669 Search your data | Full-text [search] ranks documents by the words they contain.
0.243 Indexes for faster reads | A GIN index makes text [search] fast on large tables.

The title match counts more because of weight A. Grant EXECUTE and add a select policy on the table to let the anon key or users call it (Call functions with rpc()); the function runs with the caller's rights, so users only find rows they may read.

The /search endpoint#

POST /v1/db/{table}/search takes query, columns (required), and optional limit and offset. It searches the given columns with the French configuration, whatever the language of your text, and adds a _rank field:

curl -s -X POST "$AURABASE_URL/v1/db/qd_fts_articles/search" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
  -d '{"query": "policies", "columns": ["title", "body"], "limit": 5}' \
  | node -e 'for (const r of JSON.parse(require("fs").readFileSync(0, "utf8")).data) console.log(r.title, Number(r._rank).toFixed(3))'
curl -s -X POST "$AURABASE_URL/v1/db/qd_fts_articles/search" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
  -d '{"query": "reading", "columns": ["title", "body"]}'
echo
Row level security 0.061
{"data":[],"meta":null}

reading finds nothing here, while the English configuration matched three articles: the French rules do not reduce reading to read. The endpoint has no SDK method, returns every column plus _rank, cannot use your index, and applies the caller's policies (the anon key gets [] on a table without a select policy). Prefer textSearch() or a function for English or any other language.

Fuzzy search with trigrams#

Full-text search matches words, not spellings: postgers finds nothing. The pg_trgm extension, installed in every project, compares strings by their groups of three letters, which tolerates typos. A GIN trigram index serves % (similar to), ilike '%…%' and similarity() ordering:

create index qd_fts_articles_title_trgm on qd_fts_articles using gin (title gin_trgm_ops);

create function qd_fts_fuzzy(p_text text)
returns table (title text, score real)
language sql stable as $$
  select title, similarity(title, p_text)
  from qd_fts_articles
  where title % p_text
  order by similarity(title, p_text) desc
  limit 10
$$;
  ℹ No results (0 rows).
import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const fuzzy = await admin.rpc('qd_fts_fuzzy', { p_text: 'serch yuor data' })
console.log(fuzzy.data?.map((r: any) => `${r.title} ${r.score.toFixed(2)}`), fuzzy.error)

const fts = await admin.from('qd_fts_articles').select('title').textSearch('search', 'postgers', { type: 'plain', config: 'english' })
console.log('full-text, typo:', fts.data)

const contains = await admin.from('qd_fts_articles').select('title').ilike('title', '%level%')
console.log('ilike:', contains.data)
[ 'Search your data 0.43' ] null
full-text, typo: []
ilike: [ { title: 'Row level security' } ]

% keeps rows whose similarity is above pg_trgm.similarity_threshold (0.3 by default). Combine both methods in one function when you need words and typos: full-text first, trigrams when it finds nothing. unaccent, also installed, removes accents before comparing, so that a search without accents finds words written with them.

Result#

aura db raw "select id, title from qd_fts_articles where search @@ websearch_to_tsquery('english', 'fast index') order by id"
  id   │ title
  ─────┼─────────────────────────
  4    │ Indexes for faster reads

  ℹ 1 row(s).

Common errors#

MessageCauseFix
400 POSTGREST_ERROR no operand in tsquery: "…" (or another tsquery syntax error)User input passed to textSearch() without type.Use type: 'websearch' or 'plain'.
No result for a word that is in the textDifferent config for the column and the query, or the French /search endpoint on English text.Use the same configuration on both sides.
400 BAD_REQUEST Invalid request: search: …, a message in French saying that at least one column is required/search without columns.Send "columns": ["title"].
cannot insert a non-DEFAULT value into column "search"A value sent to the generated tsvector column.Leave it out; PostgreSQL computes it.
A slow search on a large tableNo GIN index, or a search on a text column converted for every row.Search a tsvector column with a GIN index.

Clean up#

aura db raw "drop function if exists qd_fts_search(text); drop function if exists qd_fts_fuzzy(text)"
aura db raw "drop table qd_fts_articles"
  ℹ No results (0 rows).
  ℹ No results (0 rows).

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ Report a problem