26 min read · AI for business · AI basics

A salesperson types "can I send it back?" into the document system, but the company policy says "customers can return products within 7 days". The words "send it back" are not in the document at all, so a word-based search says nothing was found, even though the answer is already in the system. This article walks through a small semantic search built with Python and numpy. It is a single example that runs on your own machine, and every number comes from the program's real output.
All data in this article is made up: the company "Siam Partstech", the product codes, the policies and the questions were written by the author for teaching. They are not data or projects of any customer. The test results come from running the attached program on 2026-11-21 against 18 documents and 18 questions. That is a very small set, useful for seeing the principle, not a number to quote as the accuracy of a real system.
The problem: word search fails when writer and searcher use different words
Traditional search matches characters or words. If the searcher uses a word the document does not contain, nothing is found. This happens wherever text is written by many people, for example:
- Sales searches the internal policy documents: asks "I changed my mind, can I send it back?" The document says "product return".
- Customer service searches the repair manual: the customer says "the machine is running warm". The manual says "motor overheating".
- Product catalog: the customer types "12 VDC sensor for use in a control cabinet". The product data says "for use in a control panel".
Thai makes this problem worse because there are no spaces between words. Word-based search has to segment the words correctly first, and there are many synonyms. English mixed into a sentence, such as password, ERP or control cabinet, also makes one query a mix of several languages.
Embeddings solve this with a direct idea: convert every piece of text into a vector (a list of numbers) using a model trained so that texts with close meaning get close vectors. Then search by measuring the distance between the question vector and the document vectors.
How it works: from text to a cosine score
- Split each document into small chunks, each about one topic.
- Send each chunk to the embedding model to get a fixed-length vector, and store it (once, when building the index).
- When a question arrives, send it to the same model to get the question vector.
- Compute the cosine similarity between the question vector and every chunk, sort from highest to lowest, and take the top k.
If every vector is normalized to length 1, cosine similarity is simply the dot product, so in numpy it is one line. The closer the value is to 1, the more similar the texts. One caution: scores from different models cannot be compared. A 0.6 from one model does not mean the same as a 0.6 from another, and vectors from different models cannot be compared with each other.
| Keyword search | Semantic search (vector) | |
|---|---|---|
| What is compared | Matching characters or words | Vectors of meaning |
| Strong at | Product codes, document numbers, proper names | Spoken-style questions, synonyms, cross-language queries |
| Fails when | The user uses different words from the document | Codes that must match exactly, numbers, negation |
| Needs a model | No | Yes (run it yourself or call an API) |
| Explains its result | Easy (which word matched) | Harder (only the score is visible) |
Hands-on example: a small program that runs on your machine
All the code is in the folder examples/embedding-vector-search-business. It uses only standard Python and numpy, with nothing else to install. It is split into 4 files to read in this order: embed.py (the embedding generator), corpus.py (the made-up data), search.py (search and evaluation) and test_search.py (a check that the logic does not break).
Step 1: two embedding generators
The program has two backends you can switch between. The first is ollama, which calls the bge-m3 model running locally through Ollama's HTTP API at /api/embed. You send the texts as a list and get back 1024-dimensional vectors. bge-m3 is a multilingual model that supports more than 100 languages and texts up to 8192 tokens, according to its model page on Hugging Face. The second is hash, a fully offline fallback. It counts every run of 3 consecutive characters (character trigrams) and hashes them into a 512-dimensional vector.
"""Two embedding backends: real model via Ollama, and an offline lexical fallback."""
import json
import re
import urllib.request
import zlib
import numpy as np
OLLAMA_URL = "http://localhost:11434"
DIM = 512 # size of the fallback vector
def normalize(m):
"""Scale every row to length 1, so dot product == cosine similarity."""
m = np.asarray(m, dtype=np.float64)
n = np.linalg.norm(m, axis=1, keepdims=True)
return m / np.where(n == 0, 1, n)
def embed_hash(texts, n=3):
"""Offline fallback: hashed character n-grams. Lexical only, NOT semantic."""
out = np.zeros((len(texts), DIM))
for i, t in enumerate(texts):
t = re.sub(r"\s+", " ", t.lower())
for k in range(len(t) - n + 1):
out[i, zlib.crc32(t[k:k + n].encode()) % DIM] += 1 # crc32 = stable across runs
return normalize(out)
def embed_ollama(texts, model="bge-m3", url=OLLAMA_URL):
"""Real embeddings from a local Ollama server (POST /api/embed)."""
body = json.dumps({"model": model, "input": list(texts), "keep_alive": "5m"}).encode()
req = urllib.request.Request(url + "/api/embed", body, {"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=300) as r:
return normalize(json.load(r)["embeddings"])
def get_embedder(name):
return {"hash": embed_hash, "ollama": embed_ollama}[name]
def unload(model="bge-m3", url=OLLAMA_URL):
"""Free the model from memory (keep_alive 0)."""
body = json.dumps({"model": model, "input": "x", "keep_alive": 0}).encode()
urllib.request.urlopen(urllib.request.Request(
url + "/api/embed", body, {"Content-Type": "application/json"}), timeout=60).read()Be clear about this: the hash backend compares repeated characters, not meaning. It does not know that "send back" and "return a product" are related. It is there so the self-check can run without a model, and so that the real results show the difference between character matching and meaning-based search.
Step 2: made-up data and a question set with known answers
corpus.py has 18 short documents (product return policy, warranty, specs for sensors PX-4417-B/C, a PLC cabinet model CP-300, how to reset an ERP password, and so on) and 18 test questions. The author wrote the questions so they do not use the same words as the documents, and recorded which document each question should find. This question set is a tiny evaluation set. What makes the numbers credible is not that they look good, but that the correct answers were written down in advance.
QUERIES = [
("ซื้อไปแล้วอยากเปลี่ยนใจ ส่งกลับได้ไหม", "d01", "paraphrase"),
("เครื่องส่งเสียงดังและตัวเครื่องอุ่นจัด ต้องทำอย่างไร", "d08", "paraphrase"),
("ขอใบเสร็จแบบมีชื่อบริษัท", "d03", "paraphrase"),
("ลืม password เข้า ERP ไม่ได้", "d13", "Thai-English mix"),
("PX-4417-C", "d05", "part code"),
("เซนเซอร์ 12 VDC ใช้ใน control cabinet", "d05", "Thai-English mix"),
("ของส่งถึงเมื่อไหร่ และต้องจ่ายค่าส่งไหม", "d07", "paraphrase"),
("ป่วยต้องบอกใคร", "d10", "paraphrase"),
("ของเก่าที่ไม่ผลิตแล้วใช้อะไรแทน MG-220", "d17", "part code + paraphrase"),
("มีกล้องไว้ดูของเสียบนไลน์ผลิตไหม", "d14", "paraphrase"),
("ใครดูข้อมูลลูกค้าได้บ้าง", "d15", "paraphrase"),
("ขอซื้อของก่อนจ่ายเงินทีหลังได้ไหม", "d18", "paraphrase"),
("MG-230", "d17", "part code"),
("รุ่นไหนใช้ไฟ 24 VDC", "d04", "spec lookup"),
("ไฟตกแล้วเครื่องพัง เคลมได้ไหม", "d02", "negation trap"),
("วันเสาร์โทรหาฝ่ายขายได้ไหม", "d09", "paraphrase"),
("ทำไมต้องต่อสายดินก่อนเปิดตู้ควบคุม", "d06", "paraphrase"),
("ลาเพราะไม่สบายสี่วันต้องมีเอกสารอะไร", "d10", "paraphrase"),
]Step 3: search, ranking and the combined score
The Index class converts all documents to vectors when it is created. Then vector_scores multiplies the document vector matrix by the question vector once to get a score for every document. The search function picks the top k. If w_kw is set above 0, it adds the keyword score (keyword_score), which is the share of codes and numbers in the question that are found in the document. That is the simplest possible hybrid. The evaluate function computes hit@k (in how many questions the correct document is in the top k) and MRR (the average of 1 divided by the rank of the correct document; the closer to 1, the better).
class Index:
def __init__(self, docs, backend="hash"):
self.ids = list(docs)
self.texts = [docs[i] for i in self.ids]
self.embed = get_embedder(backend)
self.vecs = self.embed(self.texts) # (n_docs, dim), unit length
def vector_scores(self, query):
return self.vecs @ self.embed([query])[0] # cosine = dot of unit vectors
@staticmethod
def keyword_score(query, text):
"""Share of the query's Latin/number tokens (e.g. PX-4417-C) found in the text."""
toks = re.findall(r"[A-Za-z0-9][A-Za-z0-9\-]*", query.lower())
if not toks:
return 0.0
low = text.lower()
return sum(t in low for t in toks) / len(toks)
def search(self, query, k=3, w_kw=0.0):
"""w_kw=0 -> pure vector. w_kw>0 -> vector + w_kw * keyword (hybrid)."""
s = self.vector_scores(query)
if w_kw:
s = s + w_kw * np.array([self.keyword_score(query, t) for t in self.texts])
order = np.argsort(-s)[:k]
return [(self.ids[i], float(s[i])) for i in order]
def evaluate(index, queries, k=3, w_kw=0.0):
"""hit@k = share of queries whose expected doc is in the top k; MRR = mean 1/rank."""
hits, rr = 0, 0.0
for q, want, _ in queries:
ranked = [d for d, _ in index.search(q, k=len(index.ids), w_kw=w_kw)]
rank = ranked.index(want) + 1
hits += rank <= k
rr += 1 / rank
n = len(queries)
return hits / n, rr / nStep 4: run it and read the results
The run commands are in the README: python3 demo.py --backend ollama (needs Ollama with bge-m3) or --backend hash (offline). The result below is the real output of the ollama backend, run on 2026-11-21, with no manual edits.
backend=ollama docs=18 dim=1024
== top-3 per query (pure vector) ==
Q [paraphrase] ซื้อไปแล้วอยากเปลี่ยนใจ ส่งกลับได้ไหม (expected d01)
0.614 d01 <-- expected นโยบายการคืนสินค้า: ลูกค้าคืนสินค้าได้ภา
0.541 d07 ค่าขนส่ง: ส่งฟรีเมื่อสั่งซื้อครบ 5,000 บ
0.496 d18 การสั่งซื้อแบบเครดิต: ลูกค้าองค์กรขอเครด
Q [paraphrase] เครื่องส่งเสียงดังและตัวเครื่องอุ่นจัด ต้องทำอย่างไร (expected d08)
0.667 d08 <-- expected ถ้ามอเตอร์ร้อนเกินไปให้หยุดเครื่องทันที
0.461 d06 ตู้ควบคุม PLC รุ่น CP-300 มีช่อง I/O 16
0.423 d04 เซนเซอร์ตรวจจับระยะ PX-4417-B ใช้ไฟ 24 V
Q [paraphrase] ขอใบเสร็จแบบมีชื่อบริษัท (expected d03)
0.638 d03 <-- expected ขั้นตอนขอใบกำกับภาษี: แจ้งชื่อบริษัท เลข
0.600 d11 การเบิกค่าเดินทางไปพบลูกค้า: แนบใบเสร็จแ
0.590 d18 การสั่งซื้อแบบเครดิต: ลูกค้าองค์กรขอเครด
Q [Thai-English mix] ลืม password เข้า ERP ไม่ได้ (expected d13)
0.723 d13 <-- expected วิธีรีเซ็ตรหัสผ่านระบบ ERP: กด 'ลืมรหัสผ
0.539 d12 ซอฟต์แวร์ ERP ของบริษัทรองรับการออกใบเสน
0.490 d15 ข้อมูลลูกค้าเป็นความลับ ห้ามส่งออกนอกบริ
Q [part code] PX-4417-C (expected d05)
0.620 d05 <-- expected เซนเซอร์ตรวจจับระยะ PX-4417-C ใช้ไฟ 12 V
0.588 d04 เซนเซอร์ตรวจจับระยะ PX-4417-B ใช้ไฟ 24 V
0.352 d14 กล้องตรวจสอบชิ้นงาน (machine vision) รุ่
Q [Thai-English mix] เซนเซอร์ 12 VDC ใช้ใน control cabinet (expected d05)
0.616 d05 <-- expected เซนเซอร์ตรวจจับระยะ PX-4417-C ใช้ไฟ 12 V
0.515 d04 เซนเซอร์ตรวจจับระยะ PX-4417-B ใช้ไฟ 24 V
0.509 d06 ตู้ควบคุม PLC รุ่น CP-300 มีช่อง I/O 16
Q [paraphrase] ของส่งถึงเมื่อไหร่ และต้องจ่ายค่าส่งไหม (expected d07)
0.720 d07 <-- expected ค่าขนส่ง: ส่งฟรีเมื่อสั่งซื้อครบ 5,000 บ
0.584 d01 นโยบายการคืนสินค้า: ลูกค้าคืนสินค้าได้ภา
0.554 d16 บริการซ่อมนอกสถานที่: ช่างเข้าหน้างานภาย
Q [paraphrase] ป่วยต้องบอกใคร (expected d10)
0.617 d10 <-- expected การลาป่วย: พนักงานแจ้งหัวหน้างานก่อนเวลา
0.481 d15 ข้อมูลลูกค้าเป็นความลับ ห้ามส่งออกนอกบริ
0.470 d08 ถ้ามอเตอร์ร้อนเกินไปให้หยุดเครื่องทันที
Q [part code + paraphrase] ของเก่าที่ไม่ผลิตแล้วใช้อะไรแทน MG-220 (expected d17)
0.749 d17 <-- expected อะไหล่ตัวเก่า MG-220 ที่เลิกผลิตแล้ว ให้
0.505 d02 การรับประกัน: มอเตอร์เกียร์ซีรีส์ MG-220
0.400 d08 ถ้ามอเตอร์ร้อนเกินไปให้หยุดเครื่องทันที
Q [paraphrase] มีกล้องไว้ดูของเสียบนไลน์ผลิตไหม (expected d14)
0.605 d14 <-- expected กล้องตรวจสอบชิ้นงาน (machine vision) รุ่
0.467 d06 ตู้ควบคุม PLC รุ่น CP-300 มีช่อง I/O 16
0.449 d08 ถ้ามอเตอร์ร้อนเกินไปให้หยุดเครื่องทันที
Q [paraphrase] ใครดูข้อมูลลูกค้าได้บ้าง (expected d15)
0.646 d15 <-- expected ข้อมูลลูกค้าเป็นความลับ ห้ามส่งออกนอกบริ
0.489 d18 การสั่งซื้อแบบเครดิต: ลูกค้าองค์กรขอเครด
0.483 d12 ซอฟต์แวร์ ERP ของบริษัทรองรับการออกใบเสน
Q [paraphrase] ขอซื้อของก่อนจ่ายเงินทีหลังได้ไหม (expected d18)
0.572 d18 <-- expected การสั่งซื้อแบบเครดิต: ลูกค้าองค์กรขอเครด
0.524 d07 ค่าขนส่ง: ส่งฟรีเมื่อสั่งซื้อครบ 5,000 บ
0.503 d11 การเบิกค่าเดินทางไปพบลูกค้า: แนบใบเสร็จแ
Q [part code] MG-230 (expected d17)
0.658 d17 <-- expected อะไหล่ตัวเก่า MG-220 ที่เลิกผลิตแล้ว ให้
0.469 d02 การรับประกัน: มอเตอร์เกียร์ซีรีส์ MG-220
0.331 d06 ตู้ควบคุม PLC รุ่น CP-300 มีช่อง I/O 16
Q [spec lookup] รุ่นไหนใช้ไฟ 24 VDC (expected d04)
0.550 d04 <-- expected เซนเซอร์ตรวจจับระยะ PX-4417-B ใช้ไฟ 24 V
0.509 d05 เซนเซอร์ตรวจจับระยะ PX-4417-C ใช้ไฟ 12 V
0.473 d06 ตู้ควบคุม PLC รุ่น CP-300 มีช่อง I/O 16
Q [negation trap] ไฟตกแล้วเครื่องพัง เคลมได้ไหม (expected d02)
0.519 d02 <-- expected การรับประกัน: มอเตอร์เกียร์ซีรีส์ MG-220
0.498 d08 ถ้ามอเตอร์ร้อนเกินไปให้หยุดเครื่องทันที
0.470 d01 นโยบายการคืนสินค้า: ลูกค้าคืนสินค้าได้ภา
Q [paraphrase] วันเสาร์โทรหาฝ่ายขายได้ไหม (expected d09)
0.669 d09 <-- expected เวลาทำการ: จันทร์ถึงศุกร์ 8:30-17:30 น.
0.507 d15 ข้อมูลลูกค้าเป็นความลับ ห้ามส่งออกนอกบริ
0.506 d01 นโยบายการคืนสินค้า: ลูกค้าคืนสินค้าได้ภา
Q [paraphrase] ทำไมต้องต่อสายดินก่อนเปิดตู้ควบคุม (expected d06)
0.685 d06 <-- expected ตู้ควบคุม PLC รุ่น CP-300 มีช่อง I/O 16
0.518 d08 ถ้ามอเตอร์ร้อนเกินไปให้หยุดเครื่องทันที
0.438 d05 เซนเซอร์ตรวจจับระยะ PX-4417-C ใช้ไฟ 12 V
Q [paraphrase] ลาเพราะไม่สบายสี่วันต้องมีเอกสารอะไร (expected d10)
0.689 d10 <-- expected การลาป่วย: พนักงานแจ้งหัวหน้างานก่อนเวลา
0.510 d11 การเบิกค่าเดินทางไปพบลูกค้า: แนบใบเสร็จแ
0.501 d18 การสั่งซื้อแบบเครดิต: ลูกค้าองค์กรขอเครด
== hybrid vs vector (k=3) ==
vector hit@3=1.00 MRR=1.000
hybrid w=0.5 hit@3=1.00 MRR=1.000
part-code queries, top-2 with scores (vector vs hybrid; the gap is what matters):
PX-4417-C vector d05 0.620, d04 0.588
PX-4417-C hybrid d05 1.120, d04 0.588
PX-4417-B vector d04 0.612, d05 0.566
PX-4417-B hybrid d04 1.112, d05 0.566
MG-230 vector d17 0.658, d02 0.469
MG-230 hybrid d17 1.158, d02 0.469
== chunking (max_chars=120, overlap=1) ==
[1] 115 chars: คู่มือติดตั้งตู้ควบคุม CP-300 ขั้นที่ 1 ตรวจสอบอุปกรณ์ในกล่องให้ครบตาม...
[2] 52 chars: และคู่มือ หากชิ้นใดขาดให้แจ้งฝ่ายขายก่อนเริ่มติดตั้ง...
[3] 116 chars: ขั้นที่ 2 ยึดตู้เข้ากับผนังด้วยสกรูอย่างน้อย 4 จุด ตรวจว่าผนังรับน้ำหน...
[4] 104 chars: ขั้นที่ 3 ต่อสายดินเข้ากับขั้วสายดินของตู้ก่อนต่อสายอื่นทุกเส้น แล้ววั...
[5] 87 chars: ขั้นที่ 4 ต่อสายไฟเข้า 24 VDC และสาย I/O ตามแผนผัง ตรวจขั้วให้ถูกต้องก...How to read the results
- For the first question, "I bought it and changed my mind, can I send it back?", bge-m3 ranks the product return policy (d01) first at 0.614, even though the word "return" is not in the question at all. The hash backend ranks this document 10th.
- Note that the documents ranked 2nd and 3rd by bge-m3 (shipping cost 0.541, loan 0.496) also score high. For this model on this set, the cosine score is not low when a document is unrelated. So a cutoff such as "trust it only above 0.5" must be set from your own data. Do not take numbers from this article.
- The question that mixes Thai and English, "I forgot my password and cannot log in to the ERP", returns the ERP password reset procedure (d13) in 1st place at 0.723, although the document says "รหัสผ่าน" (the Thai word for password), not "password".
- The trap question about negation, "the machine broke after a power surge, can I claim?", does return the warranty document (d02) in 1st place, but only just ahead of 2nd place, 0.519 against 0.498. And the content of d02 says power surge damage is "not covered". Finding the right document does not mean the answer is "yes, you can claim". The step that reads and concludes needs a person or an LLM that is careful about this, separate from the search step.
Comparison: the character-based fallback versus the meaning model
The numbers below come from output.txt (ollama) and output-hash.txt (hash) in the example folder, on the same 18 questions.
| backend | Vector dimensions | hit@3 | MRR (vector only) | MRR (hybrid w=0.5) |
|---|---|---|---|---|
| hash (characters, offline) | 512 | 0.89 | 0.677 | 0.714 |
| ollama bge-m3 (meaning) | 1024 | 1.00 | 1.000 | 1.000 |
Read it carefully: on this small set, bge-m3 put the correct document first in all 18 questions (MRR 1.000), while hash got the correct document first in only 9 and missed the top-3 criterion in two (the answer was at rank 10 and rank 4). But this is only 18 documents, which is very easy. With thousands of documents of similar content, real numbers will be lower, so you must measure again on your own documents.
The hash backend, which does not understand meaning, still reached 0.89 at top-3. Most questions in this set still share some characters with the documents, such as the code MG-220 or the word for "sales department". This is worth knowing: if your test set is written by copying from the documents, a system that does not understand meaning looks fine. The question set must use the wording that real users type.
Hybrid: when product codes must match exactly
Embedding models tend to place similar-looking product codes close together. Here is a real bge-m3 result when searching PX-4417-C: the correct document (d05) scores 0.620, but the sibling model PX-4417-B (d04) scores 0.588, a gap of only 0.032. With dozens of similar-looking models, a narrow gap like this risks swapping ranks. When the keyword score is added (w_kw = 0.5), the correct document scores 1.120 while d04 stays at 0.588, so the gap widens to 0.532.
On this small test set, hybrid does not change hit@3 for bge-m3 (1.00 both ways), because the model already ranks correctly. This says plainly that hybrid does not help in every case. The benefit visible in the real results is a wider score gap that does not depend on the model getting lucky. With the hash backend, MRR moves from 0.677 to 0.714.
A caution about the simple formula in the example: the keyword score is added directly, so the total can exceed 1, and the weight of 0.5 was set by hand, not tuned. Real work usually uses BM25 for the keyword side and then merges the rankings with Reciprocal Rank Fusion (RRF), which does not need scores on the same scale. Qdrant and pgvector (together with Postgres full-text search) each describe this method in their own documentation.
Chunking: cut long documents so they can be found
A whole long document turned into a single vector is an average picture of all its topics. A specific topic cannot be found, and models also have a length limit. The fix is to cut it into chunks that each cover one topic. The chunk function in search.py cuts by line first. If a line is too long, it cuts at spaces, then groups the pieces into chunks of at most max_chars with an overlap of 1 piece, so that a sentence straddling a cut is not lost.
def chunk(text, max_chars=120, overlap=1):
"""Split into lines (long lines into words), pack up to max_chars, repeat `overlap` piece."""
pieces = []
for line in text.split("\n"):
pieces += [line] if len(line) <= max_chars else line.split(" ")
pieces = [p for p in pieces if p]
chunks, cur = [], []
for p in pieces:
if cur and len(" ".join(cur + [p])) > max_chars:
chunks.append(" ".join(cur))
cur = cur[-overlap:] if overlap else []
if len(" ".join(cur + [p])) > max_chars:
cur = [] # overlap piece would overflow, drop it
cur.append(p)
if cur:
chunks.append(" ".join(cur))
return chunks
For the CP-300 cabinet installation manual in corpus.py, the program cut 5 chunks of 115, 52, 116, 104 and 87 characters (see the end of output.txt). This example sets max_chars to only 120 to make it easy to see. Real systems usually set several hundred to about a thousand characters, cut by section or paragraph when possible, and keep the file name and heading with every chunk to show the user the source for checking.
Three hypothetical scenarios
1. Searching internal company documents
Policies, procedures and announcements are spread across many files, and staff ask in spoken language. The main point to think about is permissions: if payroll documents and general manuals are in the same index, results must be filtered by the asker's permissions before they are shown, not after.
2. A product catalog with many codes
Some customers type a code, and some type a symptom or a use. Hybrid pays off most here. Codes must match exactly (see the PX-4417-B and -C example), while descriptions use vectors. Numeric specs, such as supply voltage, should be kept in separate fields for filtering, not left for the model to guess from text.
3. Customer service FAQ
The same question comes up often but is typed differently. Mapping questions to existing FAQ entries suits embeddings very well. When the top score is low, or close to the 2nd place, hand it to a person instead of guessing an answer.
Going further: vector databases, re-ranking and RAG
This example multiplies matrices directly in numpy, which works up to roughly tens of thousands of chunks (this figure is a rough rule that was not measured in this article, so test it on your own machine). When the data grows beyond that, or you need to filter by permission or date, and documents are updated often, use a vector database.
- pgvector: a PostgreSQL extension that stores vectors in the same tables as business data. It has cosine distance (the <=> operator) and HNSW and IVFFlat indexes. It suits cases where you already have Postgres. https://github.com/pgvector/pgvector
- Qdrant: a dedicated vector database. It supports dense + sparse vectors, payload filters, hybrid queries and RRF rank fusion. https://qdrant.tech/documentation/concepts/hybrid-queries/
- Re-ranking: first retrieve roughly 20-50 candidates in a coarse search, then use a cross-encoder to score each (question, chunk) pair again. It is slower but more accurate. See the retrieve & re-rank approach in sentence-transformers.
- RAG: pass the search results to an LLM to read and summarize into an answer. See the article on a chatbot that answers from company documents, linked at the end of this article.
Personal data and secrets: local models versus external APIs
Embedding means sending your text into a model. If you use an external provider's API, every document text and question leaves the company network. If the documents contain customer data, contracts or personal data, check the provider's policy and contract, and the conditions under personal data protection law, first. This article's example uses a model that runs locally through Ollama, so the text does not leave the machine. bge-m3 uses the MIT license, as stated on its model page.
Remember that the vectors themselves should be treated as just as sensitive as the originals, because in some cases the content can be partly guessed back. Store them and set permissions the same way as the source documents.
Common mistakes and a checklist
- Using different models for indexing and for searching: the vectors cannot be compared. You must re-index everything when you change the model.
- Not normalizing vectors and then using the dot product: scores are distorted by vector length.
- A test set written to mimic the documents: results look better than they are. Use questions that real users type.
- Treating a high score as a correct answer: see the negation example (power surge claim), where the right document was found but the answer is the opposite.
- Setting a cutoff from someone else's numbers: scores differ for every model and every data set. Measure it yourself.
- Not filtering by permissions: confidential documents leak into search results.
- Not keeping the source: users cannot trace which chunk came from which file.
Checklist before starting a real project: (1) collect 20-50 representative documents, (2) collect 30-100 real questions with correct answers, (3) try keyword search, vector search and hybrid, and measure hit@k and MRR, (4) decide between a local model and an external one, (5) define permissions and how documents are updated.
Measuring before going live
The file test_search.py is a self-check that runs on the offline backend. It checks that vectors have length 1 and results are repeatable, that the chunker does not cut beyond the length limit or lose text, that the codes PX-4417-B/C each find their own document, and that hybrid does not lower MRR. Running python3 test_search.py gave the result self-check OK on the day this article was written.
"""Self-check on the offline backend: python test_search.py"""
import numpy as np
from corpus import DOCS, LONG_DOC, QUERIES
from embed import embed_hash
from search import Index, chunk, evaluate
# 1. vectors are unit length and deterministic
v = embed_hash(["ทดสอบ abc", "ทดสอบ abc"])
assert np.allclose(np.linalg.norm(v, axis=1), 1) and np.allclose(v[0], v[1])
# 2. identical text scores ~1, unrelated text lower
assert abs(float(v[0] @ v[1]) - 1) < 1e-9
assert float(embed_hash(["ทดสอบ abc"])[0] @ embed_hash(["zzzzqqqq"])[0]) < 0.2
# 3. chunker: no chunk too long, no text lost, overlap present
cs = chunk(LONG_DOC, max_chars=120, overlap=1)
assert len(cs) > 1 and all(len(c) <= 120 for c in cs)
assert all(w in " ".join(cs) for w in ["ขั้นที่ 1", "ขั้นที่ 4", "CP-300"])
# 4. an exact part code finds its document; hybrid is not worse than vector on codes
idx = Index(DOCS, "hash")
assert idx.search("PX-4417-C", 1, w_kw=0.5)[0][0] == "d05"
assert idx.search("PX-4417-B", 1, w_kw=0.5)[0][0] == "d04"
# 5. metrics are valid and hybrid never lowers MRR here
h0, m0 = evaluate(idx, QUERIES, 3)
h1, m1 = evaluate(idx, QUERIES, 3, w_kw=0.5)
assert 0 <= h0 <= 1 and 0 < m0 <= 1 and m1 >= m0
print("self-check OK")Once live, keep users' questions (as permitted by law and consent) and look at which questions find nothing. Add them to the test set. Measure again every time you change the model, the chunking method or the hybrid weight. This is ongoing work, not a one-time job.
References
- BAAI/bge-m3 model card (Hugging Face) (accessed 2026-11-21)
- M3-Embedding: Multi-Linguality, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation (Chen et al.) (accessed 2026-11-21)
- Ollama API documentation (GitHub): /api/embed (accessed 2026-11-21)
- pgvector: vector similarity search for Postgres (GitHub) (accessed 2026-11-21)
- Qdrant documentation: Hybrid and Multi-Stage Queries (accessed 2026-11-21)
- Sentence Transformers: Retrieve & Re-Rank (accessed 2026-11-21)
- MTEB: Massive Text Embedding Benchmark (Muennighoff et al.) (accessed 2026-11-21)




