served

Articles ·

Full-text search with nothing extra to run

SQLite has a search engine built in, called FTS5. How to index text, rank the results and show where they matched, all in the database you already have.

Keep full-text search in the same SQLite file as your data. FTS5, included in every Served database, lets you index text, rank matches, and show snippets with the matching words highlighted.

Make an index

A search index is a table. You say which columns hold the text:

CREATE VIRTUAL TABLE notes USING fts5(title, body);

INSERT INTO notes (title, body) VALUES
  ('Tomatoes', 'Sow tomato seeds indoors in March. Plant out after the last frost.'),
  ('Watering', 'Water tomatoes at the base, in the morning. Wet leaves invite blight.'),
  ('Compost', 'Turn the heap every few weeks. It is ready when it smells of earth.');

Search it

MATCH finds the rows, and ORDER BY rank puts the best ones first:

SELECT title FROM notes WHERE notes MATCH 'frost OR compost' ORDER BY rank;
[["Tomatoes"], ["Compost"]]

The text after MATCH is a small language of its own:

tomato seedsBoth words, anywhere in the row
"last frost"The two words together, in that order
frost OR compostEither word
tomato NOT indoorsThe first word without the second
tom*Any word that starts with tom
title: water*Only in the title column

Show where it matched

snippet() returns a short piece of the text around the match, with the matched words marked. Its arguments are the table, the number of the column (counting from 0), what to put before and after a match, what to put where text was cut, and how many words to show.

SELECT title, snippet(notes, 1, '<b>', '</b>', '...', 6)
FROM notes WHERE notes MATCH 'frost';
[["Tomatoes", "...Plant out after the last <b>frost</b>."]]

highlight() does the same for the whole column.

Make the title count for more

rank scores every column alike. To say that a word in the title matters ten times as much as one in the body, order by bm25() with a weight for each column:

SELECT title FROM notes WHERE notes MATCH 'water*' ORDER BY bm25(notes, 10.0, 1.0);
[["Watering"]]

Match words that are nearly the same

As it stands, a search for tomato finds only the first note. The second says "tomatoes", which is another word to the index.

A tokenizer decides what counts as the same word. porter cuts English words down to their stem, so that "tomato" and "tomatoes", or "water" and "watering", are one word:

CREATE VIRTUAL TABLE stemmed USING fts5(title, body, tokenize = 'porter');
INSERT INTO stemmed SELECT title, body FROM notes;

SELECT title FROM stemmed WHERE stemmed MATCH 'tomato' ORDER BY title;
[["Tomatoes"], ["Watering"]]

The other one worth knowing is trigram, which matches any run of three or more characters inside a word. It suits names, codes and part numbers, where people type the middle of something.

Search a table you already have

If the text is already in an ordinary table, the index can point at that table without keeping a second copy of the text. Three triggers keep the two in step:

CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT, body TEXT);

CREATE VIRTUAL TABLE posts_fts USING fts5(
  title, body, content = 'posts', content_rowid = 'id');

CREATE TRIGGER posts_insert AFTER INSERT ON posts BEGIN
  INSERT INTO posts_fts (rowid, title, body) VALUES (new.id, new.title, new.body);
END;
CREATE TRIGGER posts_delete AFTER DELETE ON posts BEGIN
  INSERT INTO posts_fts (posts_fts, rowid, title, body)
  VALUES ('delete', old.id, old.title, old.body);
END;
CREATE TRIGGER posts_update AFTER UPDATE ON posts BEGIN
  INSERT INTO posts_fts (posts_fts, rowid, title, body)
  VALUES ('delete', old.id, old.title, old.body);
  INSERT INTO posts_fts (rowid, title, body) VALUES (new.id, new.title, new.body);
END;

From then on you write to posts as before and search through the index, joining back for whatever columns you want:

INSERT INTO posts (title, body) VALUES ('Hello', 'The first post.'), ('Again', 'A second post.');
UPDATE posts SET body = 'The first post, edited.' WHERE id = 1;

SELECT posts.id, posts.title
FROM posts_fts JOIN posts ON posts.id = posts_fts.rowid
WHERE posts_fts MATCH 'edited';
[[1, "Hello"]]

For rows that were in the table before the index existed, run this once:

INSERT INTO posts_fts (posts_fts) VALUES ('rebuild');

From your program

A search is one request. Send what the person typed as a parameter, never pasted into the SQL:

curl https://api.served.dev/v1/databases/garden/query \
  -H "Authorization: Bearer $SERVED_KEY" \
  -d '{"sql": "SELECT title FROM notes WHERE notes MATCH ? ORDER BY rank LIMIT 20",
       "args": ["last frost"]}'

People type things that mean something in the search language, such as a quote mark or a hyphen, and FTS5 answers those with a syntax error. If you want plain words and nothing else, put each word in double quotes before you send it: "last" "frost".

The index goes with the file

The index is part of the database. When you download the file, the index comes with it, and it works in any SQLite that has FTS5, which is nearly all of them.

Served is hosted SQLite. Real SQLite behind an HTTP API, $5 a month, and the file is yours to download whenever you like.

Get started Read the docs