AI & Semantic Search

Vector Search

Find documents by meaning and similarity rather than exact keyword matches. AxioDB provides native, zero-dependency vector similarity search with full support for pure vector queries and hybrid filtered searches.

What is Vector Search?

Traditional database queries look for exact matches (e.g. status == "active"). Vector search converts text, images, or audio into arrays of numbers (embeddings) and finds records with the closest semantic meaning — even if they share zero words in common.

Pure vs. Hybrid Search

Pure Vector Search: Finds the overall most similar documents across your entire collection.
Hybrid Search: First filters documents using traditional criteria (user ID, dates, category), then ranks the remaining candidates by semantic similarity.

Where Can It Be Used?

🧠 Agent Episodic Memory

Give AI agents private, long-term memory that recalls relevant past dialogues and actions instantly.

🔍 Local RAG & Docs

Retrieve relevant knowledge base articles or code snippets based on user questions without external SaaS APIs.

🎯 Content Recommendation

Recommend "more like this" articles, products, or user profiles using behavioral embedding vectors.

🛡️ Duplicate Detection

Detect semantically identical support tickets, duplicate questions, or spam variants automatically.

Why AxioDB Vector Search?

• 100% Exact Recall: AxioDB uses Exact k-Nearest Neighbors (k-NN). Unlike approximate graph algorithms that can miss the true closest match, AxioDB guarantees mathematical ground truth.

• Instant Writes (< 1 ms): Documents with embeddings are written instantly with ACID locks. There is zero graph-building delay or background re-indexing queue.

• Zero Native Dependencies: Runs natively anywhere Node.js or Bun runs (Linux, macOS, Windows, Docker, Electron). No C++ compilers, Python sidecars, or external vector databases required.

• Automatic Score Attribution: Every matching document includes an exact _score attribute so your code can inspect match quality.

Syntax & Examples

1. Storing Vector Embeddings

Vectors are stored as standard arrays of numbers on any field name of your choice (e.g. embedding, vec).

javascript
1const { AxioDB } = require("axiodb");
2
3const db = new AxioDB();
4const myDB = await db.createDB("AgentDB");
5const memories = await myDB.createCollection("memories");
6
7// 1. Insert documents with vector embeddings (no schema needed)
8await memories.insertMany([
9 {
10 title: "TypeScript Guide",
11 category: "tech",
12 embedding: [0.12, 0.85, -0.34, 0.42] // e.g., generated via OpenAI, Ollama, etc.
13 },
14 {
15 title: "Coffee Brewing Basics",
16 category: "lifestyle",
17 embedding: [-0.65, 0.12, 0.78, -0.05]
18 },
19 {
20 title: "Node.js Concurrency",
21 category: "tech",
22 embedding: [0.15, 0.82, -0.30, 0.45]
23 }
24]);

2. Pure Vector Search

Use the shorthand collection.vectorSearch(field, vector, options) to find the closest matches across all documents.

javascript
1// 2. Pure Vector Search (Direct Collection Method)
2const queryVector = [0.14, 0.84, -0.32, 0.44];
3
4const results = await memories.vectorSearch("embedding", queryVector, {
5 topK: 2, // Return the top 2 closest documents
6 minScore: 0.80, // Only return results with >= 80% similarity
7 metric: "cosine" // Options: "cosine" (default), "dot", "euclidean"
8});
9
10console.log(results.data.documents);
11/*
12Output:
13[
14 {
15 title: "TypeScript Guide",
16 category: "tech",
17 _score: 0.9998
18 },
19 {
20 title: "Node.js Concurrency",
21 category: "tech",
22 _score: 0.9984
23 }
24]
25*/

3. Hybrid Search (Filter + Vector)

Chain .vectorSearch() into any standard .query() pipeline. AxioDB applies the query filters first, then calculates similarity on the matching set.

javascript
1// 3. Hybrid Search: Filter by metadata + Rank by vector similarity
2const queryVector = [0.14, 0.84, -0.32, 0.44];
3
4const results = await memories
5 .query({
6 category: "tech", // Regular filter
7 views: { $gte: 100 } // Any standard AxioDB query operator
8 })
9 .vectorSearch("embedding", queryVector, {
10 topK: 5,
11 metric: "cosine"
12 })
13 .exec();
14
15console.log(results.data.documents);

4. Pagination & Projection

Use Skip() and Limit() to paginate through vector results, and setProject() to select specific fields.

javascript
1// 4. Pagination & Projection with Vector Search
2const results = await memories
3 .query({ category: "tech" })
4 .vectorSearch("embedding", queryVector)
5 .Skip(5) // Skip first 5 matches
6 .Limit(5) // Return next 5 matches
7 .setProject({ title: 1, _score: 1 }) // Keep only title and similarity score
8 .exec();

5. AI Agent Episodic Memory Pattern

Store conversations and recall only the relevant past episodes matching the user's current intent:

javascript
1// 5. Example: Instant Episodic Memory for an AI Agent
2class AgentMemory {
3 constructor(collection) {
4 this.collection = collection;
5 }
6
7 // Store a conversation turn instantly
8 async record(userId, userMessage, embedding) {
9 await this.collection.insert({
10 userId,
11 message: userMessage,
12 embedding,
13 timestamp: Date.now()
14 });
15 }
16
17 // Recall the most relevant past thoughts or interactions
18 async recall(userId, currentTopicVector) {
19 const memory = await this.collection
20 .query({ userId })
21 .vectorSearch("embedding", currentTopicVector, {
22 topK: 3,
23 minScore: 0.75
24 })
25 .exec();
26
27 return memory.data.documents;
28 }
29}

6. AxioDB Cloud (TCP Client)

Search remote collections over AxioDB's high-performance binary TCP protocol (port 27019) using the official AxioDBCloud client:

javascript
1// 6. Vector Search with AxioDB Cloud (TCP Client)
2const { AxioDBCloud } = require("axiodb");
3
4// Connect to AxioDB TCP server (port 27019)
5const client = new AxioDBCloud("axiodb://127.0.0.1:27019", {
6 username: "admin", // Required if TCP server runs with TCPAuth: true
7 password: "password123"
8});
9await client.connect();
10
11// Open database and collection proxy
12const db = await client.createDB("AgentDB");
13const memories = await db.createCollection("memories");
14
15const queryVector = [0.14, 0.84, -0.32, 0.44];
16
17// Pure vector similarity search over TCP
18const results = await memories.vectorSearch("embedding", queryVector, {
19 topK: 5,
20 minScore: 0.80,
21 metric: "cosine"
22});
23
24console.log(results.documents);
25
26// Hybrid search over TCP (Query filter + vector ranking)
27const hybrid = await memories
28 .query({ category: "tech" })
29 .vectorSearch("embedding", queryVector, { topK: 5 })
30 .exec();
31
32console.log(hybrid.data.documents);

7. HTTP REST API

Integrate vector search into any language (Python, Go, Rust, cURL) via AxioDB's HTTP Fastify server (port 27018):

bash
1# 7. Vector Search via HTTP REST API (Port 27018)
2# Endpoint: POST /api/operation/vector-search/?dbName=<DB>&collectionName=<COLLECTION>
3curl -X POST "http://127.0.0.1:27018/api/operation/vector-search/?dbName=AgentDB&collectionName=memories" \
4 -H "Content-Type: application/json" \
5 -H "Authorization: Bearer <AUTH_TOKEN>" \
6 -d '{
7 "field": "embedding",
8 "vector": [0.14, 0.84, -0.32, 0.44],
9 "options": {
10 "topK": 5,
11 "minScore": 0.80,
12 "metric": "cosine"
13 }
14 }'

8. Model Context Protocol (MCP) Tool

Expose vector search directly to AI agents in Cursor, Claude Desktop, or Windsurf via AxioDB's built-in MCP server (axiodb_vector_search):

json
1// 8. MCP (Model Context Protocol) AI Agent Tool: axiodb_vector_search
2// Call from Cursor, Claude Desktop, or custom LLM agent via MCP port 27020:
3{
4 "name": "axiodb_vector_search",
5 "arguments": {
6 "sessionId": "active_session_token",
7 "dbName": "AgentDB",
8 "collectionName": "memories",
9 "field": "embedding",
10 "vector": [0.14, 0.84, -0.32, 0.44],
11 "options": {
12 "topK": 5,
13 "minScore": 0.80,
14 "metric": "cosine"
15 }
16 }
17}

Supported Similarity Metrics

MetricScore RangeBest Used ForSorting
cosine-1.0 to 1.0 (1.0 is identical)Text embeddings & semantic search (OpenAI, HuggingFace, Ollama)Highest score first (Descending)
dotUnboundedPre-normalized vectors (fastest computation)Highest score first (Descending)
euclidean0.0 to ∞ (0.0 is identical)Spatial data, computer vision, geometric distanceLowest score first (Ascending)

Limitations & Best Practices

  • Dataset Sizing: AxioDB's exact vector search is optimized for embedded apps, agent memory, and datasets up to tens of thousands of documents per collection.
  • Dimension Matching: All documents evaluated must have the same vector dimension as your query vector. Documents with missing or mismatched dimensions are automatically skipped safely.
  • Numeric Types: Vector elements must be finite numbers (integers or floats). Strings or NaN values inside vector arrays are safely filtered out.
  • Embedding Generation: AxioDB stores and searches vectors; use your favorite embedding model (e.g. text-embedding-3-small, local Ollama, or Transformers.js) to generate vectors before inserting.