Vector Search for AI Applications
This guide uses DuckDB's VSS (Vector Similarity Search) core extension. Thanks to its contributors.
Semantic search finds rows by meaning instead of by keyword: "How do I log in?" finds the article titled "Authentication". It is the retrieval half of RAG (Retrieval Augmented Generation), where an AI agent fetches relevant context before it answers. flAPI turns a vector query into a REST endpoint and an MCP tool.
How it fits together
flAPI does not compute embeddings. Your loader embeds the documents, and your client (or a trusted backend) embeds the question and sends the vector to flAPI.
Vector search options
| Option | Status with flAPI v26.11.25 (DuckDB 2.0.1) | Best for |
|---|---|---|
Built-in array functions (array_cosine_distance, array_distance, array_inner_product) | always available | small tables; exact results by full scan |
vss core extension (HNSW index) | verified: installs, builds a cosine HNSW index on a persistent database | up to millions of vectors, approximate top-k |
faiss community extension | published for DuckDB 2.0.1, not tested with flAPI | very large collections; see its upstream docs |
Setup
The table and its index live in flAPI's DuckDB database, so give it a file (db_path). HNSW indexes on a persistent database need DuckDB's hnsw_enable_experimental_persistence setting; flAPI passes duckdb: keys through to DuckDB:
project-name: kb-search
template:
path: ./sqls
duckdb:
db_path: ./kb.duckdb
hnsw_enable_experimental_persistence: true
connections:
vector-db:
init: |
INSTALL vss;
LOAD vss;
CREATE TABLE IF NOT EXISTS document_embeddings (
id VARCHAR PRIMARY KEY,
content TEXT,
category VARCHAR,
embedding FLOAT[1536] -- the dimension of your embedding model
);
CREATE INDEX IF NOT EXISTS embedding_idx
ON document_embeddings USING HNSW (embedding) WITH (metric = 'cosine');
initruns once, at startup.IF NOT EXISTSmakes it safe to run on every start.- The index uses the cosine metric, so queries must order by
array_cosine_distance(...), ascending, with aLIMIT, for DuckDB to use it. A query that orders byarray_cosine_similarity(...) DESCgives the same ranking but scans the whole table. vssis a core extension: plainINSTALL vss;fetches it.
Example 1: Knowledge-base search
Step 1: Load the embeddings
The loader is a separate job, not part of flAPI. Run it while flAPI is stopped: the server holds the lock on kb.duckdb for as long as it runs.
import duckdb
import openai
documents = [
{"id": "doc1", "category": "account", "content": "How to reset your password: go to settings..."},
{"id": "doc2", "category": "api", "content": "API authentication uses JWT tokens..."},
{"id": "doc3", "category": "ops", "content": "Database backups run daily at 2am..."},
]
con = duckdb.connect("kb.duckdb")
for doc in documents:
emb = openai.embeddings.create(input=doc["content"], model="text-embedding-3-small").data[0].embedding
con.execute(
"INSERT OR REPLACE INTO document_embeddings (id, content, category, embedding) VALUES (?, ?, ?, ?)",
[doc["id"], doc["content"], doc["category"], emb],
)
con.close()
The Python duckdb package must be a 2.0.x release: flAPI's DuckDB 2.0.1 writes database files that DuckDB 1.x cannot open, and the other way round only works for files 1.x created.
Step 2: The search endpoint
The query vector is long, so it travels in a JSON body. A POST endpoint is treated as a write; with operation.returns-data: true it answers the rows of a final SELECT that follows another statement (a single SELECT in a POST returns no rows in v26.11.25, #271):
url-path: /search/semantic
method: POST
operation:
returns-data: true
template-source: semantic_search.sql
connection: [vector-db]
request:
- field-name: embedding
field-in: body
description: Query embedding as a JSON array string, e.g. "[0.1,0.2,...]"
required: true
validators:
- type: string
min: 100
max: 200000
regex: '^\[[-0-9.eE, ]+\]$' # only a JSON array of numbers
- field-name: category
field-in: body
required: false
validators:
- type: enum
allowedValues: [account, api, ops]
- field-name: top_k
field-in: body
required: false
validators:
- type: int
min: 1
max: 50
SET VARIABLE query_emb = CAST({{ params.embedding }} AS FLOAT[1536]);
SELECT
d.id,
d.content,
d.category,
1 - array_cosine_distance(d.embedding, getvariable('query_emb')) AS similarity
FROM document_embeddings d
WHERE 1=1
{{#params.category}}
AND d.category = '{{{ params.category }}}'
{{/params.category}}
ORDER BY array_cosine_distance(d.embedding, getvariable('query_emb'))
LIMIT {{#params.top_k}}{{{ params.top_k }}}{{/params.top_k}}{{^params.top_k}}10{{/params.top_k}};
embeddingis outside any section, so it is bound: the long vector never becomes SQL text. Theregexvalidator still rejects anything that is not a list of numbers.categoryis inside a section, so it is pasted as text behind anenumvalidator;top_klikewise, behind anintvalidator withmax: 50.- A
LIMITis right here: this is a POST, which is not paginated, and top-k is the point of the query. In a paginated GET template, aLIMITwould break?offset=. - A metadata filter combined with the HNSW index can return fewer than
top_krows, because the index finds the nearest vectors first and the filter runs after.
Step 3: Call it
import openai, requests
question = "How do I authenticate with the API?"
emb = openai.embeddings.create(input=question, model="text-embedding-3-small").data[0].embedding
resp = requests.post(
"http://localhost:8080/search/semantic",
json={"embedding": str(emb), "top_k": 5},
)
for doc in resp.json()["data"]:
print(f"{doc['similarity']:.2f}: {doc['content'][:80]}")
Example 2: Hybrid search (vectors + keywords)
Combine the semantic score with a keyword match. Every value the template uses is a declared, validated field:
request:
- field-name: embedding
field-in: body
required: true
validators:
- type: string
min: 100
max: 200000
regex: '^\[[-0-9.eE, ]+\]$'
- field-name: keywords
field-in: body
required: false
validators:
- type: string
max-length: 100
SET VARIABLE query_emb = CAST({{ params.embedding }} AS FLOAT[1536]);
SET VARIABLE kw = {{ params.keywords }};
SELECT
d.id,
d.content,
(1 - array_cosine_distance(d.embedding, getvariable('query_emb')))
+ CASE WHEN getvariable('kw') IS NOT NULL
AND d.content ILIKE '%' || getvariable('kw') || '%' THEN 0.2 ELSE 0 END AS score
FROM document_embeddings d
ORDER BY score DESC
LIMIT 20;
Both values are bound. Absent, keywords binds NULL and the keyword bonus switches off. This query ranks by a computed score, so it scans the table instead of using the index; that is fine for tens of thousands of rows.
Example 3: RAG for AI agents (MCP)
An mcp-tool: block makes the same endpoint an MCP tool that Claude or another agent can call:
url-path: /rag/search
method: POST
operation:
returns-data: true
template-source: semantic_search.sql
connection: [vector-db]
mcp-tool:
name: search_knowledge_base
description: |
Search the company knowledge base by meaning. Use it to find documentation
or policies relevant to the user's question.
request:
- field-name: embedding
field-in: body
required: true
validators:
- type: string
min: 100
max: 200000
regex: '^\[[-0-9.eE, ]+\]$'
- field-name: category
field-in: body
required: false
validators:
- type: enum
allowedValues: [account, api, ops]
- field-name: top_k
field-in: body
required: false
validators:
- type: int
min: 1
max: 50
An agent rarely holds an embedding itself; a tool that takes raw text needs a backend that embeds it first. Protect the tool with MCP authentication; see MCP Overview.
Restrict results to the caller
Filter on auth.*, which flAPI sets from the credentials it checked, never on a body field the caller sends. Write the filter without a section, so an anonymous request matches only public rows:
WHERE (d.visibility = 'public' OR d.owner = '{{{ auth.username }}}')
Performance
- Index or scan. The HNSW index answers
ORDER BY array_cosine_distance(col, <vector>) LIMIT kapproximately and fast. Anything else (a computed score, a sort by similarityDESC) scans every row exactly. - Index parameters.
CREATE INDEX ... USING HNSW (embedding) WITH (metric = 'cosine', M = 16, ef_construction = 200); see the VSS docs for the full list and their trade-offs. - Memory. HNSW indexes live in memory. Size
duckdb.max_memoryfor the index plus your queries. - Dimension. Smaller embeddings (384 to 768 dimensions) are faster to index and compare than 1536 or 3072.
Distance metrics
| Function | Range | Lower or higher is closer | Index metric |
|---|---|---|---|
array_cosine_distance(a, b) | 0 to 2 | lower | cosine |
array_distance(a, b) (Euclidean) | 0 to ∞ | lower | l2sq |
array_negative_inner_product(a, b) | −∞ to ∞ | lower | ip |
array_cosine_similarity(a, b) | −1 to 1 | higher | (no index; use the distance) |
For normalised embeddings such as OpenAI's, cosine and inner product rank the same way.
Embedding models
| Model | Dimension | Notes |
|---|---|---|
OpenAI text-embedding-3-small | 1536 | inexpensive, good general quality |
OpenAI text-embedding-3-large | 3072 | higher quality, larger index |
Cohere embed-v3 | 1024 | multilingual variants |
| Sentence Transformers (open source) | 384 to 768 | runs locally, no per-call cost |
Check current prices with the provider. Whatever you choose, the loader and the client must use the same model, and the FLOAT[n] in the table must match its dimension.
Best practices
- Embed on a trusted side. If the search is a security boundary, do not let arbitrary clients supply vectors; embed the question in a backend you control.
- Rate-limit the endpoint:
rate-limit: {enabled: true, max: 60, interval: 60}on the endpoint. - Validate the vector: length bounds and a numbers-only
regex, as above. - Use hybrid search for production RAG: vectors miss exact identifiers, keywords miss paraphrases.
Troubleshooting
- The index is not used (slow queries). Order by
array_cosine_distance(...)ascending with aLIMIT, and make sure the index metric matches the function. Conversion Erroron the vector. The array length differs fromFLOAT[1536], or the string is not a JSON array; check the model and the client.- The loader cannot open
kb.duckdb. flAPI is running and holds the lock. Stop it, load, start it. - A request returns
500with only arequest_id. The DuckDB error is in the server log under that id (Observability).
Next steps
- Vector Search RAG example: a complete RAG implementation
- MCP Overview: MCP tools for AI agents
- SQL Templating: bound parameters and sections
- Write Operations: how POST endpoints answer