Skip to main content

Vector Search for AI Applications

Extension credit

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​

OptionStatus with flAPI v26.11.25 (DuckDB 2.0.1)Best for
Built-in array functions (array_cosine_distance, array_distance, array_inner_product)always availablesmall tables; exact results by full scan
vss core extension (HNSW index)verified: installs, builds a cosine HNSW index on a persistent databaseup to millions of vectors, approximate top-k
faiss community extensionpublished for DuckDB 2.0.1, not tested with flAPIvery 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:

flapi.yaml
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');
  • init runs once, at startup. IF NOT EXISTS makes it safe to run on every start.
  • The index uses the cosine metric, so queries must order by array_cosine_distance(...), ascending, with a LIMIT, for DuckDB to use it. A query that orders by array_cosine_similarity(...) DESC gives the same ranking but scans the whole table.
  • vss is a core extension: plain INSTALL vss; fetches it.

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.

load_embeddings.py
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):

sqls/semantic_search.yaml
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
sqls/semantic_search.sql
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}};
  • embedding is outside any section, so it is bound: the long vector never becomes SQL text. The regex validator still rejects anything that is not a list of numbers.
  • category is inside a section, so it is pasted as text behind an enum validator; top_k likewise, behind an int validator with max: 50.
  • A LIMIT is right here: this is a POST, which is not paginated, and top-k is the point of the query. In a paginated GET template, a LIMIT would break ?offset=.
  • A metadata filter combined with the HNSW index can return fewer than top_k rows, because the index finds the nearest vectors first and the filter runs after.

Step 3: Call it​

client.py
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:

sqls/hybrid_search.yaml (request)
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
sqls/hybrid_search.sql
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:

sqls/rag_search.yaml
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 k approximately and fast. Anything else (a computed score, a sort by similarity DESC) 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_memory for the index plus your queries.
  • Dimension. Smaller embeddings (384 to 768 dimensions) are faster to index and compare than 1536 or 3072.

Distance metrics​

FunctionRangeLower or higher is closerIndex metric
array_cosine_distance(a, b)0 to 2lowercosine
array_distance(a, b) (Euclidean)0 to ∞lowerl2sq
array_negative_inner_product(a, b)−∞ to ∞lowerip
array_cosine_similarity(a, b)−1 to 1higher(no index; use the distance)

For normalised embeddings such as OpenAI's, cosine and inner product rank the same way.

Embedding models​

ModelDimensionNotes
OpenAI text-embedding-3-small1536inexpensive, good general quality
OpenAI text-embedding-3-large3072higher quality, larger index
Cohere embed-v31024multilingual variants
Sentence Transformers (open source)384 to 768runs 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​

  1. 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.
  2. Rate-limit the endpoint: rate-limit: {enabled: true, max: 60, interval: 60} on the endpoint.
  3. Validate the vector: length bounds and a numbers-only regex, as above.
  4. 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 a LIMIT, and make sure the index metric matches the function.
  • Conversion Error on the vector. The array length differs from FLOAT[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 500 with only a request_id. The DuckDB error is in the server log under that id (Observability).

Next steps​

🍪 Cookie Settings