Describe and explain in detail how is main, NON-graph storage is organized in mem0
Assistant
Based on the repository content, I'll explain how the main non-graph storage is organized in mem0. The system uses a vector store-based approach with multiple implementation options and a consistent interface.
Here's a detailed breakdown:
Core Storage Architecture
The storage system consists of two main layers:
Vector stores for efficient similarity search and retrieval
A SQLite-based history tracking system for maintaining memory changes
Vector Store Implementations
Mem0 supports multiple vector store backends through a factory pattern. The supported vector stores are:
Qdrant
ChromaDB
PostgreSQL with pgvector
[Redacted Person]
Azure AI Search
Redis
Elasticsearch
Each implementation must conform to the VectorStoreBase interface and provides the following core operations:
insert: Add vectors with associated payloads and IDs
search: Find similar vectors with optional filters
delete: Remove vectors by ID
update: Modify existing vectors or their payloads
get: Retrieve specific vectors by ID
list: Get all vectors with optional filtering
Data Model
The basic memory item structure (from base.py) includes:
The system maintains a history of memory changes using SQLite (memory/storage.py) with the following schema:
sql
CREATE TABLE history (
id TEXT PRIMARY KEY,
memory_id TEXT,
old_memory TEXT,
new_memory TEXT,
new_value TEXT,
event TEXT,
created_at DATETIME,
updated_at DATETIME,
is_deleted INTEGER
)
Factory Pattern
User
Is it possible to re-implement the storage model in the way that uses vector storage, but the custom one built upon SQLite (so vector embeddings are stored in SQLite database) without reducing the accuracy of the search?
Assistant
User
Please try now to fully implement this using either Python or Rust with interfaces to Python; optionally, you can try to use C, but the main environment where this will be used is Python so it is recommended to use Python for full, detailed production-ready implementation
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Configurable vector dimensions and distance metrics
Configuration
Storage configuration is handled through Pydantic models that include:
Vector store-specific settings
Embedding model dimensions
Connection parameters
Optional compression settings (for some implementations)
The system is designed to be modular and extensible, allowing new vector store implementations to be added by implementing the common interface defined in the VectorStoreBase class.
This architecture provides several benefits:
Flexibility in choosing storage backend based on needs
Consistent interface across different implementations
Built-in history tracking for auditing and versioning
Support for both local and cloud-based storage solutions
Scalability through various backend options
Easy extension through the factory pattern
The combination of vector stores for efficient similarity search and SQLite for history tracking provides a robust foundation for memory storage and retrieval in the mem0 system.
Yes, it's possible to implement a custom vector storage using SQLite while maintaining search accuracy. Here's how it could be done:
Database Schema Design
sql
-- Vectors table
CREATE TABLE vectors (
id TEXT PRIMARY KEY,
vector BLOB, -- Store vector as serialized binary
created_at DATETIME,
updated_at DATETIME
);
-- Metadata table
CREATE TABLE metadata (
vector_id TEXT REFERENCES vectors(id),
key TEXT,
value TEXT,
PRIMARY KEY (vector_id, key)
);
-- Optional: Index table for faster lookups
CREATE TABLE vector_index (
vector_id TEXT REFERENCES vectors(id),
dimension INTEGER,
value REAL,
PRIMARY KEY (dimension, vector_id)
);
Vector Storage Implementation
Here's a conceptual implementation that could be added as a new vector store class:
python
class SQLiteVectorStore(VectorStoreBase):
def __init__(self, db_path, embedding_dims):
self.conn = sqlite3.connect(db_path)
self.embedding_dims = embedding_dims
self._create_tables()
def _create_tables(self):
# Create the schema above
pass
def _vector_to_blob(self, vector):
return np.array(vector, dtype=np.float32).tobytes()
def _blob_to_vector(self, blob):
return np.frombuffer(blob, dtype=np.float32)
def insert(self, vectors, payloads=None, ids=None):
with self.conn:
for vid, vec, payload in zip(ids, vectors, payloads):
# Store vector
self.conn.execute(
"INSERT INTO vectors (id, vector) VALUES (?, ?)",
(vid, self._vector_to_blob(vec))
)
# Store metadata
if payload:
for key, value in payload.items():
self.conn.execute(
"INSERT INTO metadata (vector_id, key, value) VALUES (?, ?, ?)",
(vid, key, json.dumps(value))
)
def search(self, query, limit=5, filters=None):
# Efficient cosine similarity implementation
query_vec = np.array(query, dtype=np.float32)
# Using a CTE for vector similarity calculation
sql = """
WITH vector_similarities AS (
SELECT
v.id,
[Redacted Person],
(
-- Cosine similarity implementation in SQL
-- dot_product(query, vector) / (norm(query) * norm(vector))
) as similarity
FROM vectors v
WHERE 1=1
"""
if filters:
sql += " AND v.id IN (SELECT vector_id FROM metadata WHERE "
sql += " AND ".join(f"key = ? AND value = ?" for _ in filters)
sql += ")"
sql += " ORDER BY similarity DESC LIMIT ?"
# Execute search with optimizations
results = self.conn.execute(sql, [...]).[Redacted Person]()
return [self._format_result(r) for r in results]
Optimizations for Search Performance
To maintain search accuracy and performance, several techniques can be implemented:
python
class SQLiteVectorStore(VectorStoreBase):
def _create_index_tables(self):
"""Create auxiliary tables for approximate nearest neighbor search"""
# LSH (Locality Sensitive Hashing) tables
self.conn.execute("""
CREATE TABLE IF NOT EXISTS lsh_buckets (
bucket_id TEXT,
vector_id TEXT,
hash_value TEXT,
PRIMARY KEY (bucket_id, vector_id)
)
""")
def _compute_lsh_hash(self, vector):
"""Compute LSH hash for vector using random projections"""
# Implementation of LSH hashing
pass
def search(self, query, limit=5, filters=None):
# Two-stage search:
# 1. Use LSH to find candidate set
query_hash = self._compute_lsh_hash(query)
candidates = self._get_lsh_candidates(query_hash)
# 2. Compute exact distances only for candidates
return self._exact_search(query, candidates, limit, filters)
Performance Enhancements
python
class SQLiteVectorStore(VectorStoreBase):
def __init__(self, db_path, embedding_dims):
self.conn = sqlite3.connect(db_path)
# Enable memory-mapped I/O for better performance
self.conn.execute("PRAGMA mmap_size = [Redacted PhoneNumber]")
# Use Write-Ahead Logging for better concurrency
self.conn.execute("PRAGMA journal_mode = WAL")
# Increase cache size
self.conn.execute("PRAGMA cache_size = -2000000") # 2GB cache
def _create_indexes(self):
"""Create indexes for faster searches"""
# B-tree index on metadata
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_metadata
ON metadata(vector_id, key, value)
""")
# Index for LSH buckets
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_lsh_buckets
ON lsh_buckets(hash_value)
""")
Batch Operations Support
python
class SQLiteVectorStore(VectorStoreBase):
def insert_batch(self, vectors, payloads=None, ids=None, batch_size=1000):
with self.conn:
for i in range(0, len(vectors), batch_size):
batch_vectors = vectors[i:i + batch_size]
batch_ids = ids[i:i + batch_size]
batch_payloads = payloads[i:i + batch_size]
self.conn.executemany(
"INSERT INTO vectors (id, vector) VALUES (?, ?)",
[(id, self._vector_to_blob(vec))
for id, vec in zip(batch_ids, batch_vectors)]
)
This implementation would provide several advantages:
Single Database: All data (vectors, metadata, history) in one SQLite database
Transactional Safety: SQLite's ACID properties
No External Dependencies: Just Python standard library and NumPy
Portable: Single file database
Flexible: Easy to modify and extend
Memory Efficient: Streaming large datasets possible
The main challenge would be maintaining search performance with large datasets, but this can be addressed through:
Proper indexing strategies
LSH for approximate nearest neighbor search
SQLite optimization settings
Batch operations
Memory-mapped I/O
Careful query optimization
The accuracy would be maintained since you're still storing the full vectors and can compute exact distances when needed, while using approximation techniques like LSH for initial candidate selection in large datasets.
I'll create a production-ready Python implementation of SQLite-based vector storage. I'll break this into multiple files for better organization.
First, let's create the core vector store implementation:
python
# sqlite_vector_store/core.py
import sqlite3
import numpy as np
from typing import List, Dict, Optional, Tuple, Any
import json
from datetime import datetime
import logging
from pathlib import Path
import mmap
from dataclasses import dataclass
import threading
from concurrent.futures import ThreadPoolExecutor
import pickle
logger = logging.getLogger(__name__)
@[Redacted Person]
class SearchResult:
id: str
score: float
payload: Dict[str, Any]
vector: Optional[np.ndarray] = None
class SQLiteVectorStore:
def __init__(
self,
db_path: str,
dimension: int,
index_params: Optional[Dict] = None,
cache_size_mb: int = 2000,
mmap_size_gb: int = 30,
n_jobs: int = -1
):
"""Initialize SQLite Vector Store
Args:
db_path: Path to SQLite database
dimension: Vector dimension
index_params: LSH parameters for approximate search
cache_size_mb: SQLite cache size in MB
mmap_size_gb: Memory map size in GB
n_jobs: Number of worker threads (-1 for CPU count)
"""
self.db_path = Path(db_path)
self.dimension = dimension
self.index_params = index_params or {
"n_planes": 8, # Number of LSH planes
"n_tables": 4, # Number of LSH tables
}
self.n_jobs = n_jobs if n_jobs > 0 else max(1, len(os.sched_getaffinity(0)) - 1)
# Thread-local SQLite connections
self._local = threading.local()
# Initialize database
self._init_db(cache_size_mb, mmap_size_gb)
# Initialize LSH projections
self._init_lsh()
@property
def conn(self) -> sqlite3.Connection:
"""Get thread-local database connection"""
if not [Redacted Person](self._local, "conn"):
self._local.conn = self._create_connection()
return self._local.conn
def _create_connection(self) -> sqlite3.Connection:
"""Create new SQLite connection with optimized settings"""
conn = sqlite3.connect(self.db_path)
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA synchronous = NORMAL")
conn.execute("PRAGMA temp_store = MEMORY")
conn.execute(f"PRAGMA cache_size = -{self.cache_size_mb * 1024}")
conn.execute(f"PRAGMA mmap_size = {self.mmap_size_gb * 1024 * 1024 * 1024}")
return conn
def _init_db(self, cache_size_mb: int, mmap_size_gb: int):
"""Initialize database schema"""
self.cache_size_mb = cache_size_mb
self.mmap_size_gb = mmap_size_gb
with self.conn as conn:
# Create tables
conn.executescript("""
CREATE TABLE IF NOT EXISTS vectors (
id TEXT PRIMARY KEY,
vector BLOB NOT NULL,
norm REAL NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS metadata (
vector_id TEXT REFERENCES vectors(id) ON DELETE CASCADE,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (vector_id, key)
);
CREATE TABLE IF NOT EXISTS lsh_tables (
table_id INTEGER,
vector_id TEXT REFERENCES vectors(id) ON DELETE CASCADE,
hash_val BLOB NOT NULL,
PRIMARY KEY (table_id, hash_val, vector_id)
);
CREATE INDEX IF NOT EXISTS idx_lsh_lookup
ON lsh_tables(table_id, hash_val);
CREATE INDEX IF NOT EXISTS idx_metadata_lookup
ON metadata(key, value);
""")
def _init_lsh(self):
"""Initialize LSH projection planes"""
rng = np.random.default_rng(42)
self.lsh_planes = [
rng.standard_normal((self.index_params["n_planes"], self.dimension))
for _ in range(self.index_params["n_tables"])
]
def _vector_to_blob(self, vector: np.ndarray) -> bytes:
"""Convert vector to binary blob"""
return pickle.dumps(vector, protocol=4)
def _blob_to_vector(self, blob: bytes) -> np.ndarray:
"""Convert binary blob to vector"""
return pickle.loads(blob)
def _compute_lsh_hashes(self, vector: np.ndarray) -> List[bytes]:
"""Compute LSH hashes for vector"""
vector = vector / np.linalg.norm(vector)
hashes = []
for planes in self.lsh_planes:
projections = planes @ vector
hash_bits = (projections > 0).astype(np.uint8)
hashes.append(hash_bits.tobytes())
return hashes
def insert(
self,
vectors: List[np.ndarray],
ids: List[str],
payloads: Optional[List[Dict]] = None,
batch_size: int = 1000
):
"""Insert vectors into store
Args:
vectors: List of vectors to insert
ids: List of vector IDs
payloads: Optional list of metadata payloads
batch_size: Batch size for insertion
"""
if payloads is None:
payloads = [{} for _ in vectors]
with self.conn as conn:
for i in range(0, len(vectors), batch_size):
batch_vectors = vectors[i:i+batch_size]
batch_ids = ids[i:i+batch_size]
batch_payloads = payloads[i:i+batch_size]
# Insert vectors
vector_data = [
(id, self._vector_to_blob(vec), float(np.linalg.norm(vec)))
for id, vec in zip(batch_ids, batch_vectors)
]
conn.executemany(
"INSERT OR REPLACE INTO vectors (id, vector, norm) VALUES (?, ?, ?)",
vector_data
)
# Insert metadata
metadata = [
(id, k, json.dumps(v))
for id, payload in zip(batch_ids, batch_payloads)
for [Redacted Person], v in payload.items()
]
if metadata:
conn.executemany(
"INSERT OR REPLACE INTO metadata (vector_id, key, value) VALUES (?, ?, ?)",
metadata
)
# Insert LSH hashes
lsh_data = [
(table_id, id, hash_val)
for id, vec in zip(batch_ids, batch_vectors)
for table_id, hash_val in enumerate(self._compute_lsh_hashes(vec))
]
conn.executemany(
"INSERT OR REPLACE INTO lsh_tables (table_id, vector_id, hash_val) VALUES (?, ?, ?)",
[Redacted Person]_[Redacted Person]
)
def search(
self,
query: np.ndarray,
limit: int = 10,
filters: Optional[Dict[str, Any]] = None,
exact: bool = False
) -> List[SearchResult]:
"""Search for similar vectors
Args:
query: Query vector
limit: Number of results to return
filters: Optional metadata filters
exact: Whether to perform exact search
Returns:
List