Official Node.js examples for SochDB - the high-performance embedded database for AI applications. This repository demonstrates SochDB integration patterns in JavaScript/TypeScript.
sochdb-nodejs-examples/
βββ basic/ # Basic key-value operations and SQL
βββ rag/ # Complete RAG (Retrieval-Augmented Generation) system
- Node.js 18+ installed
- SochDB Node.js SDK:
@sochdb/sochdb
npm install @sochdb/sochdbDemonstrates fundamental SochDB operations in Node.js.
Features:
- Database initialization
- PUT/GET operations
- Path-based operations
- Prefix scanning
- SQL table creation and queries
- Proper resource cleanup
Files:
basic_kv.js- Key-value operationssql_check.js- SQL interface usage
cd basic
npm install
node basic_kv.js
node sql_check.jsExample Output:
Node.js SDK Test
================
β
Database opened
β
Put: test_key -> test_value
β
Get: test_key = test_value
β
Path: users/alice/email = alice@example.com
β
Scan: Found 2 items with prefix 'tenants/acme/'
β
Database closed
π All Node.js SDK tests passed!
What you'll learn:
- Opening and closing databases
- Storing and retrieving data
- Working with path-based keys
- Scanning with prefixes
- Executing SQL queries
- Error handling in async/await
Stats: β ~1 second runtime | Perfect for learning SochDB basics
Complete production-ready RAG pipeline with document processing and query execution.
Architecture:
Document β Chunking β Embedding β SochDB Storage
Query β Embedding β Vector Search β Context Assembly β LLM Generation
Features:
- Document ingestion and preprocessing
- Text chunking with configurable size/overlap
- Azure OpenAI embeddings integration
- SochDB vector storage with HNSW index
- Semantic search for context retrieval
- Query generation with retrieved context
- Production-ready error handling
Components:
src/documents.js- Document loading and managementsrc/chunking.js- Text splitting strategiessrc/embeddings.js- Azure OpenAI embeddings clientsrc/vectorStore.js- SochDB vector operationssrc/generation.js- LLM answer generationsrc/rag.js- End-to-end RAG pipelinedemo.js- Interactive demonstration
-
Configure Environment:
cd rag cp .env.example .env # Edit .env with your Azure OpenAI credentials
-
Install Dependencies:
npm install
-
Run the Demo:
node demo.js
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_API_KEY=your-api-key
AZURE_OPENAI_DEPLOYMENT=gpt-4
AZURE_OPENAI_EMBEDDING_DEPLOYMENT=text-embedding-ada-002
AZURE_OPENAI_API_VERSION=2024-02-15-preview- Async/Await Patterns: Modern JavaScript async operations
- Error Handling: Comprehensive try-catch patterns
- Vector Search: HNSW index for fast similarity search
- Chunking Strategies: Configurable chunk size and overlap
- Azure Integration: Production-ready OpenAI client usage
- Context Assembly: Token-aware context building
- Clean Architecture: Modular, maintainable code structure
Stats: π Vector Embeddings + HNSW Search | Production-ready RAG pipeline
Advanced Agent Memory System demonstrating long-term persistence and semantic recall.
Features:
- Long-term memory with vector embeddings.
- SharedDatabase Singleton for connection stability.
- Auto-Retry Logic for robust IPC handling.
- 100% Recall Accuracy via prompt engineering.
- LangGraph integration (Checkpointer + Memory Tools).
Files:
agent.ts- ReAct agent with enhanced system prompt.memory.ts- Vector storage implementation.test_agent.ts- 60-turn stress test runner.
cd langgraph-memory
npm install
npm testStats:
- β 100% Recall Accuracy (15/15 successful recalls)
- β‘ ~280ms avg latency (190ms min, 820ms max)
- π 100% Stability (60/60 turns, auto-recovery from connection drops)
- π§ 29 memory searches across 60-turn conversation
"Where's my order?" Support Bot showcasing SochDB's "Dual Nature": Real Database + Agent Memory.
Scenario: User asks "My order is late. Can you reroute or replace it?"
What the Agent Does:
- SQL: Pulls operational truth (Order Status, ETA) from
orderstable. - Memory: Checks User Prefs (
replacements_over_refunds) from KV store. - RAG: Retrieves "Late Shipment Policy" from Vector Store.
- TOON: Formats context efficiently (e.g.
orders[3]{id,status}: ...). - ACID: Executes a Transaction to update order status and create a ticket atomically.
Key Outcome: The agent uses ~40% fewer tokens for context (via TOON) and takes safe, transactional actions.
cd support-agent
npm install
npm run seed
npm startStats:
- β 100% Response Accuracy (Correctly identified delayed order, applied policy, respected user prefs)
- π 19.2% Token Savings: 120 tokens (JSON) β 97 tokens (TOON)
// JSON: 120 tokens [{"id":103,"item":"USB-C Hub","status":"DELAYED",...}] // TOON: 97 tokens orders[3]{id,item,status,eta,destination,total}: 103,USB-C Hub,DELAYED,2023-10-10,Seattle, WA,35
- π Unified Store: SQL + KV + Vectors in one database
- β‘ ACID Transactions: Safe, atomic updates to orders + tickets
- Embedded Mode: Run SochDB directly in your Node.js app (FFI)
- IPC Mode: Connect to SochDB server via Unix sockets
- Async/Await: Full Promise-based API
- Vector Search: Built-in HNSW index
- SQL Support: Execute SQL queries (via IPC mode)
- Path Operations: Hierarchical key organization
- Transactions: ACID guarantees with group commits
const { Database } = require('@sochdb/sochdb');
// Open database
const db = await Database.open('./my_database');
// Put key-value
await db.put(Buffer.from('key'), Buffer.from('value'));
// Get value
const value = await db.get(Buffer.from('key'));
// Scan with prefix
for await (const [key, value] of db.scanPrefix(Buffer.from('prefix:'))) {
console.log(key.toString(), value.toString());
}
// Close database
await db.close();// Execute SQL (IPC mode required)
const result = await db.execute(`
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT
)
`);
// Insert data
await db.execute(`
INSERT INTO users (id, name, email)
VALUES (1, 'Alice', 'alice@example.com')
`);
// Query data
const rows = await db.query('SELECT * FROM users');The basic examples include built-in verification:
cd basic
node basic_kv.js
# Should output: π All Node.js SDK tests passed!We welcome contributions! Please submit Pull Requests with:
- New example implementations
- Improvements to existing examples
- Documentation enhancements
- Bug fixes
Apache License 2.0 - see the LICENSE file for details.
- sochdb/sochdb - Main SochDB repository
- sochdb/sochdb-python-examples - Python examples
- sochdb/sochdb-golang-examples - Go examples
- sochdb/sochdb-examples - Multi-language examples
- Chatbots: Store conversation history with semantic search
- RAG Systems: Document Q&A with context retrieval
- Caching: High-performance key-value cache
- Agent Memory: Long-term memory for AI agents
- Analytics: Store and query structured data
- Session Management: User session storage with TTL