Thai Search Without Word Splitting: SQLite FTS5 Trigram
Thai has no spaces between words, so a search engine that splits words on whitespace gets Thai sentences wrong from the first step. My approach was not to find a smarter word segmenter, but to stop segmenting words altogether and move the hard work to the query side.
1-minute summary
- Symptom / problem
- Searching for a word mid-sentence in Thai with SQLite FTS5 finds nothing, because the default tokenizer does not know Thai word boundaries
- Who should read
- People building Thai content search on a website with SQLite
- Fix in short
- Switch to a trigram tokenizer with BM25, then handle five things on the query side, such as terms shorter than 3 characters, numbers attached to units, and sentences without spaces
I needed to index a client's web content so a chatbot could search it through an MCP tool before answering customers. The content included tour packages, services, articles, terms and conditions, reviews, and team pages, almost all in Thai. It had to be fast, require no additional service to maintain, and need no Thai word segmenter installed. I chose SQLite FTS5 because it is a single file that python can read directly, then found that searches missed words plainly present on the pages.
The sample data, page titles, and prices in this article are all fictional. The table structure, weights, and query preparation rules are what I actually use. I reran the results in the code blocks with sqlite3 in memory before writing this. Anyone following along should get the same results.
Symptoms: the word is on the page, but MATCH cannot find it
For the first version, I created an FTS5 table without specifying a tokenizer, which meant using the default unicode61. My thinking was that this site's Thai content had a fair number of spaces between phrases, so ordinary FTS would probably be good enough. It only found words that happened to sit next to a space or at a boundary. The same words in the middle of sentences disappeared from the results.
Here is the smallest example: three document rows, searched with two tokenizers and compared with LIKE.
import sqlite3
rows = [
("ทัวร์ทะเลสาบ 8 วัน", "โปรแกรมเที่ยวทะเลสาบแบบส่วนตัวเดินทางได้ทุกวันราคาเริ่มต้น 59,000 บาทต่อท่าน"),
("บริการรถพร้อมคนขับ", "รถตู้พร้อมคนขับพูดไทยได้รับส่งสนามบินและเที่ยววันเดียว"),
("เอกสารยื่นวีซ่า", "รายการเอกสารที่ต้องเตรียมก่อนนัดหมายศูนย์ยื่น"),
]
db = sqlite3.connect(":memory:")
db.execute("CREATE VIRTUAL TABLE t_uni USING fts5(title, text)") # unicode61
db.execute("CREATE VIRTUAL TABLE t_tri USING fts5(title, text, tokenize='trigram')")
for r in rows:
db.execute("INSERT INTO t_uni VALUES (?,?)", r)
db.execute("INSERT INTO t_tri VALUES (?,?)", r)
for q in ["ทะเลสาบ", "ราคา", "คนขับ", "สนามบิน", "รถ"]:
n_uni = db.execute("SELECT count(*) FROM t_uni WHERE t_uni MATCH ?", (f'"{q}"',)).fetchone()[0]
n_tri = db.execute("SELECT count(*) FROM t_tri WHERE t_tri MATCH ?", (f'"{q}"',)).fetchone()[0]
n_like = db.execute("SELECT count(*) FROM t_uni WHERE title || text LIKE ?", (f"%{q}%",)).fetchone()[0]
print(f"{q:<10} unicode61={n_uni} trigram={n_tri} LIKE={n_like}")
ทะเลสาบ unicode61=1 trigram=1 LIKE=1
ราคา unicode61=0 trigram=1 LIKE=1
คนขับ unicode61=0 trigram=1 LIKE=1
สนามบิน unicode61=0 trigram=1 LIKE=1
รถ unicode61=0 trigram=0 LIKE=1
The first line is the trap: unicode61 finds ทะเลสาบ in one row, which makes it look usable. But the next three words all return zero, even though every one is present in the content. The last line shows a limitation of trigram itself, which I will return to in the query section.
Root cause: unicode61 does not segment Thai words; it splits at above-base vowels
I initially guessed that a Thai sentence without spaces would become a single token. That was only half right. When I inspected the actual tokens with fts5vocab, the picture was worse.
CREATE VIRTUAL TABLE x USING fts5(s);
INSERT INTO x VALUES ('เที่ยวทะเลสาบ');
CREATE VIRTUAL TABLE xv USING fts5vocab(x, 'row');
SELECT term FROM xv;
-- ยวทะเลสาบ
-- เท
unicode61 treats letters and numbers as token content and everything else as separators. Thai above-base vowels, below-base vowels, and tone marks are combining marks rather than letters, so they count as separators too. The word เที่ยวทะเลสาบ is split at the vowel mark ี and the tone mark ่, producing เท and ยวทะเลสาบ, neither of which is a word. Searching for ทะเลสาบ produces the query token ทะเลสาบ, which does not match ยวทะเลสาบ, so the result is zero. The row found in the example above matches because its title is ทัวร์ทะเลสาบ, and the cancellation mark in ทัวร์ happens to act as a separator.
In other words, what unicode61 does to Thai is not word segmentation. It cuts at mark positions, which have no relationship to word boundaries. Whether a search finds a word depends on which vowels it is spelled with and what the preceding word ends with.
The options at that point were to use LIKE '%คำ%', which found everything but provided no ranking, so the first ten results could be any rows and the bot could not use them to answer customers; or to segment Thai words before indexing, which meant installing a segmentation library, maintaining a dictionary, and still getting incorrect splits for proper names missing from that dictionary. I took a third option: the trigram tokenizer already included with FTS5.
Split at separators
- Suited to languages with spaces between words
- Thai: splits at above-base vowels and tone marks
- Misses words inside sentences
- Small index
Every 3-character span
- No word boundaries or dictionary needed
- Finds words inside sentences, with BM25
- Queries must be at least 3 characters long
- Larger index; does not handle spelling variations
Index structure: roughly 800-character chunks, with BM25 weighting titles 4 to 1
A web page is too long to send to the model in full, so I split it into chunks first, following paragraph boundaries, at roughly 800 characters with a 120-character overlap so sentences crossing a boundary do not disappear from both sides. Paragraphs exceeding the limit are split at the space closest to that limit.
CREATE TABLE docs (id TEXT PRIMARY KEY, type TEXT, title TEXT, url TEXT,
countries TEXT, meta TEXT, text TEXT, prices TEXT);
CREATE TABLE chunks (id INTEGER PRIMARY KEY, doc_id TEXT, type TEXT, title TEXT,
url TEXT, countries TEXT, chunk_no INTEGER, text TEXT);
CREATE VIRTUAL TABLE chunks_fts USING fts5(
title, text, content='chunks', content_rowid='id', tokenize='trigram');
CREATE INDEX chunks_doc ON chunks(doc_id);
-- หลัง insert ครบทุกแถว
INSERT INTO chunks_fts(chunks_fts) VALUES ('optimize');
The docs table stores full documents and metadata, while chunks holds what is actually searched. The FTS table points back to chunks through content=, so the text is not stored twice. The tradeoff is that I have to insert into the FTS table alongside the main table every time, which is not a problem because this index is rebuilt in full on every run, with no individual row updates.
CHUNK, OVERLAP = 800, 120
def chunks_of(text: str, size: int = CHUNK, overlap: int = OVERLAP) -> list[str]:
text = text.strip()
if len(text) <= size:
return [text] if text else []
paras = []
for p in text.split("\n"):
p = p.strip()
while len(p) > size: # ย่อหน้ายาวเกิน: ตัดที่ช่องว่างใกล้เพดาน
cut = p.rfind(" ", int(size * 0.6), size)
cut = cut if cut > 0 else size
paras.append(p[:cut].strip())
p = p[cut:].strip()
if p:
paras.append(p)
out, cur = [], ""
for p in paras:
if cur and len(cur) + 1 + len(p) > size:
out.append(cur)
cur = cur[-overlap:] + "\n" + p # หางของ chunk ก่อนหน้าติดมาด้วย
else:
cur = (cur + "\n" + p) if cur else p
if cur.strip():
out.append(cur)
return out
One small detail that helps a lot is appending the document's country names to the chunk's title column. Someone typing only a country name therefore matches a heavily weighted column, without relying on that country name appearing in every chunk's body.
Search uses the BM25 built into FTS5, with a higher weight for titles than body text.
SELECT c.doc_id, c.title, c.url, c.text,
bm25(chunks_fts, 4.0, 1.0) AS score
FROM chunks_fts
JOIN chunks c ON c.id = chunks_fts.rowid
WHERE chunks_fts MATCH ?
ORDER BY score
LIMIT ?;
The two numbers after the table name are column weights in declaration order: title gets 4.0 and text gets 1.0. A title match therefore pushes a document ahead of a match in the body text. Document type and country filters are appended to WHERE as ordinary type IN (...) and countries LIKE conditions.
FTS5's bm25() returns negative numbers. The best-matching row has the lowest value, so ORDER BY score must sort in ascending order. If you add DESC out of habit from other search systems, the weakest matches come first, with no error to warn you. The results just look odd.
The hard work moves to the query side
Once I switched to trigram, the index side was done, but the problem moved to the text people type, which cannot go straight into MATCH for five reasons.
- A term must be at least 3 characters long. The word รถ in the example above returns zero rows even though it exists in the documents, because a 2-character word cannot produce a single trigram. Terms shorter than 3 must be dropped.
- Some punctuation is FTS5 syntax. Passing
ทัวร์ (ส่วนตัว)directly producesfts5: syntax error near "ทัวร์", whileวีซ่า:ด่วนproducesno such column: วีซ่าbecause:specifies a column. I have to remove quotation marks, parentheses,* ^ ~ + :, and similar characters first, then wrap every term in quotation marks myself. - Numbers and units: people type
8 วัน,8วัน, and8วันไหม. If these are split into8andวัน, the number is dropped for being too short. I therefore capture numbers followed by วัน, คืน, คน, or ท่าน as a single phrase, and produce both forms when they are typed without a space. - Long Thai sentences without spaces, such as ทัวร์ทะเลสาบ8วัน, become a single term that is very unlikely to match a document. I therefore keep a lexicon of known words for this project (countries, cities, and service types). If a Thai token exceeds 6 characters, I look for words from the lexicon inside it and extract them as additional terms.
- The same name can have multiple spellings. People transliterate the same mountain's name in two different ways, and some type it in English. trigram does nothing to help here because it compares characters literally. I need synonym groups: finding one member adds the whole group.
Point 5 was the one I misjudged at first. I thought trigram would tolerate some spelling variation because it matches 3 characters at a time. But changing just one vowel in a transliterated word makes every trigram crossing that position fail to match, and a quoted phrase must match every trigram in sequence. The result is no match.
import re
SYNONYMS = [{"ทะเลสาบ", "lake"}, {"วีซ่า", "visa"}]
STOP = {"ไหม", "มั้ย", "ครับ", "ค่ะ", "ขอ", "หน่อย", "อยาก"}
LEXICON = sorted({"ทัวร์", "ทะเลสาบ", "ราคา", "วีซ่า", "สนามบิน", "คนขับ", "ส่วนตัว"},
key=len, reverse=True)
THAI = re.compile(r"[\u0e00-\u0e7f]")
def terms(query: str) -> list[str]:
q = re.sub(r"[\"'`(),.;:!?/\\\[\]{}<>|+*^~=#@]", " ", query.lower())
toks, found, i = q.split(), [], 0
while i < len(toks):
t = toks[i]
if re.fullmatch(r"\d+", t) and i + 1 < len(toks): # "8 วัน" เป็นวลีเดียว
unit = re.match(r"(วัน|คืน|คน|ท่าน)", toks[i + 1])
found.append(t + " " + (unit.group(1) if unit else toks[i + 1]))
i += 2
continue
m = re.fullmatch(r"(\d+)(วัน|คืน|คน|ท่าน)[\u0e00-\u0e7f]*", t) # "8วัน", "8วันไหม"
if m:
found += [m.group(1) + " " + m.group(2), m.group(1) + m.group(2)]
else:
found.append(t)
i += 1
out = []
for t in found:
if t in STOP:
continue
out.append(t)
if THAI.search(t) and len(t) > 6: # ไทยยาวไม่เว้นวรรค: ดึงคำที่รู้จักออกมา
rest = t
for w in LEXICON:
if w in rest:
out.append(w)
rest = rest.replace(w, " ")
for g in SYNONYMS:
if t in g or any(w in t for w in g if len(w) >= 4 and THAI.search(w)):
out.extend(sorted(g))
seen, res = set(), []
for t in out:
t = t.strip()
if len(t) >= 3 and t not in seen: # trigram ต้องการอย่างน้อย 3 ตัวอักษร
seen.add(t)
res.append(t)
return res[:24]
def fts_query(query: str) -> str:
return " OR ".join('"' + t.replace('"', '""') + '"' for t in terms(query))
The lexicon is sorted from longest to shortest before scanning, because shorter words contained in longer ones would otherwise take the match first. The 24-term cap prevents long questions from expanding through synonyms until the query becomes slow and the scores become a mess. Running this against the three-row sample index above produces these results.
ทัวร์ทะเลสาบ 8วันไหม (ราคา)
=> "ทัวร์ทะเลสาบ" OR "ทะเลสาบ" OR "ทัวร์" OR "lake" OR "8 วัน" OR "8วัน" OR "ราคา"
[('ทัวร์ทะเลสาบ 8 วัน', -3.816)]
ขอ ราคา รถ หน่อย
=> "ราคา"
[('ทัวร์ทะเลสาบ 8 วัน', -0.461)]
ทัวร์ทะเลสาบ8วัน
=> "ทัวร์ทะเลสาบ8วัน" OR "ทะเลสาบ" OR "ทัวร์" OR "lake"
[('ทัวร์ทะเลสาบ 8 วัน', -1.7)]
The second line is the cost of this approach. รถ is dropped because it is short, leaving only ราคา and returning a tour document instead of the car service page. If every query term is shorter than 3 characters, my search returns an empty result with a note that the query is too short and asks for a word of at least 3 characters. It does not send an empty expression into MATCH and fail. The third line is the case with no spaces at all: the first whole term matches nothing, but the words extracted from the lexicon find the same document as the spaced version.
Rebuild the whole index, then swap the file in one operation
The index is not updated row by row. Each run exports web content as a jsonl file, one document per line, then builds an entirely new SQLite file. The workflow looks like this.
import os, sqlite3, time
from pathlib import Path
def swap_in(tmp: Path, dest: Path) -> None:
for _ in range(20): # ตัวอ่านอาจถือไฟล์เก่าอยู่ชั่วครู่
try:
os.replace(tmp, dest) # atomic: ตัวอ่านเห็นไฟล์เก่าหรือไฟล์ใหม่ ไม่มีครึ่ง ๆ
return
except PermissionError:
time.sleep(1)
raise RuntimeError(f"could not replace {dest} (in use)")
def open_index(dest: Path) -> sqlite3.Connection:
return sqlite3.connect(f"file:{dest}?mode=ro", uri=True) # เปิดอ่านอย่างเดียวทุกครั้งที่ค้น
The search side opens the file read-only for each query instead of keeping a connection open. Once the file is swapped, the next query automatically gets the new index. The bot does not need to restart. The builder prints a one-line summary at the end of each run: document count, chunk count, documents containing prices, file size in MB, and elapsed time. I scheduled it to run every Monday at 04:30.
schtasks /Create /TN "bot-index-refresh" /TR "C:\bot\refresh_index.bat" /SC WEEKLY /D MON /ST 04:30
On the first run, I built the index from the database on my development machine. Everything in the search results was correct except the url column, which pointed to http://localhost/.... The bot's answers during early testing included those links. An index is a copy of the data where it was exported. Export from the wrong place, and every link is wrong too. The builder now has a mode that fetches the corpus directly from production. The server-side export file is created with umask 077 and deleted immediately after downloading.
Prices: do not let the model do the arithmetic
Beyond search, I added lines containing prices to the index. During indexing, the builder scans every line of a page. Any line containing a number followed by a currency is stored separately in the document's prices column, along with the amount, currency, unit (per person, per night, per vehicle), and customer group (adult, child). The current run collected these from 549 pages.
The reason is that I do not want the model reading prices from text and multiplying numbers itself. The bot's calculation tool reads numbers from this column and calculates them in code. The model only chooses which tool to call and which document to use. I wrote separately about keeping the bot's session from seeing unrelated material on the machine in Answering customers with a Claude CLI bot.
Testing: queries with and without spaces must return the same document
The query preparation rules are code I change often. Every synonym addition or lexicon expansion can break existing behavior. I cover them with pytest. This is the most important check.
def top_doc(query: str) -> str:
rows = search(query, limit=5) # ฟังก์ชันค้นตัวเดียวกับที่บอทเรียก
assert rows, f"ไม่มีผลค้นสำหรับ {query!r}"
return rows[0]["doc_id"]
def test_spaced_and_unspaced_hit_same_doc():
assert top_doc("ทัวร์ทะเลสาบ 8 วัน") == top_doc("ทัวร์ทะเลสาบ8วัน")
def test_fts_syntax_chars_do_not_raise():
for q in ['ทัวร์ (ส่วนตัว)', 'วีซ่า:ด่วน', '"ราคา', 'a*b^c']:
search(q) # ต้องไม่โยน sqlite3.OperationalError
def test_short_query_is_rejected_politely():
assert search("รถ") == []
- Create an FTS5 table with
tokenize='trigram', then usefts5vocabto inspect the actual tokens at least once. Do not guess what the tokenizer does to Thai. - Split chunks at paragraph boundaries, roughly 800 characters long with a small overlap, and put frequently searched terms (country names, types) in the title column.
- Weight the columns in
bm25(), thenORDER BYin ascending order. - Strip FTS syntax from queries, wrap terms in quotation marks, and drop terms shorter than 3 characters.
- Capture numbers with units, extract lexicon words from sentences typed without spaces, add synonyms, and cap the term count.
- Build the index from production data into a temporary file, then use
os.replaceto replace the live file. - Cover it with tests comparing queries with and without spaces.
Remaining limitations
trigram does not understand language; it matches characters. Short words such as รถ and ตั๋ว cannot be searched without other words alongside them. Spelling variations require manually written synonym groups, and the lexicon and synonyms are specific to the project: moving to another website means rebuilding them. For an index covering one website and refreshed once a week, I can accept these limitations because there is nothing extra to maintain beyond a single file. The web database's charset is a separate problem. If an index is not being used during a JOIN, see A charset mismatch silently disables an index instead. Personally, I will look at other options if the content grows beyond this scale or I need semantic search, depending on the size of the job. If I have left any gaps in the explanation, I will come back and fill them in later.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first