---
title: "Database Vector Stores"
description: "Database Vector Stores provide persistent indexing, metadata filtering, and approximate nearest neighbor (ANN) retrieval capabilities across relational databases, distributed search engines, in-mem..."
last_updated: "2026-10-11T17:37:10.218815+00:00"
canonical_url: "https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/vector-stores/database-vector-stores"
---


## Overview

Database Vector Stores provide persistent indexing, metadata filtering, and approximate nearest neighbor (ANN) retrieval capabilities across relational databases, distributed search engines, in-memory data structures, and graph analytics systems. Within Mem0, these database backends handle the storage and querying of long-term memory embeddings alongside associated payloads, user tenant contexts, and timestamps. Unlike standalone [Embedded Vector Stores](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/vector-stores/embedded-vector-stores) or managed [Cloud Vector Backends](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/vector-stores/cloud-vector-backends), database vector stores integrate embedding storage directly into existing enterprise data systems like PostgreSQL via `pgvector`, Elasticsearch, OpenSearch, Redis, Valkey, Apache Cassandra, Amazon Neptune Analytics, Oracle AI Vector Search, MongoDB, Azure AI Search, and Baidu Mochow.


The primary design challenge solved by these drivers is bridging multi-dimensional vector math with structured relational tables, document schemas, or inverted indices. Because different engines handle vector indexing via distinct internal mechanisms—such as PostgreSQL native `vector` data types, Elasticsearch `dense_vector` fields with HNSW graphs, or Redis Hash keys with RediSearch modules—each backend abstracts the connection lifecycle, schema initialization, parameter binding, and query filtering into a unified `VectorStore` interface.


```mermaid
flowchart TD
    A["Memory Core Engine"] --> B["VectorStore Interface"]
    B --> C["Relational DBs<br>(pgvector, Azure MySQL, Oracle)"]
    B --> D["Search Engines<br>(Elasticsearch, OpenSearch, Azure AI Search)"]
    B --> E["In-Memory & KV<br>(Redis, Valkey)"]
    B --> F["Distributed & Graph<br>(Cassandra, Neptune Analytics, Milvus, Baidu)"]
```


## Relational Database Integrations: pgvector, Azure MySQL, and Oracle DB

Relational database integrations extend traditional SQL tables with native or JSON-serialized vector storage and similarity operators. 

In PGVector, tables are initialized with a `UUID` primary key, a `vector` data type column sized to `embeddingModelDims`, and a `JSONB` payload column. During nearest neighbor search, `pgvector` executes queries using the `<->` cosine distance operator, sorting results and bounding output sizes with `LIMIT $2`. Parameterized filters are dynamically constructed via `buildFilterConditions()`, translating metadata JSON path lookups into SQL expressions with strict parameter indexing to prevent injection.


For Azure MySQL, embeddings and JSON payloads are stored as JSON columns and evaluated via application-level `cosineSimilarity()` loops over fetched rows, since MySQL handles vector distance sorting in memory after fetching candidate sets.


Oracle AI Vector Search utilizes Oracle 23.4+ native `VECTOR` data types and `JSON` payload columns inside relational tables. Search operations invoke `VECTOR_DISTANCE(vector, :query_vec, ...)` combined with `ORDER BY distance FETCH APPROX FIRST :max_rows ROWS ONLY`. When executing filtered searches, Oracle conditionally omits index hints or injects `VECTOR_INDEX_TRANSFORM` depending on filter presence.


```mermaid
sequenceDiagram
    participant App as Memory Client
    participant PG as PGVector Store
    participant DB as PostgreSQL Engine
    App->>PG: search(queryVector, topK, filters)
    PG->>DB: SELECT id, vector <=> $1::vector, payload WHERE ... ORDER BY distance LIMIT $2
    DB-->>PG: Result rows with distance and JSONB payload
    PG-->>App: Normalized VectorStoreResult[] array
```


| Provider | Vector Storage Format | Index / Distance Mechanism | Metadata / Filter Strategy |
| :--- | :--- | :--- | :--- |
| **pgvector** | `vector(dims)` column | HNSW / DiskANN via `<->` operator | JSONB operators (`payload->>'key'`) |
| **Azure MySQL** | `JSON` column | Application-level `cosineSimilarity()` | `JSON_EXTRACT(payload, ?)` |
| **Oracle DB** | `VECTOR(dims)` column | HNSW / IVF neighbor graph via `VECTOR_DISTANCE` | Oracle JSON relational duality / bind vars |


## Search Engines: Elasticsearch, OpenSearch, and Azure AI Search

Distributed search and retrieval engines leverage inverted indices alongside vector quantization and HNSW graphs to execute hybrid keyword and semantic searches.


Elasticsearch and OpenSearch store embeddings in `dense_vector` or `knn_vector` fields configured with `nmslib` or native engines using cosine similarity. When inserting documents, payloads are flattened into `metadata` objects. During vector search, queries construct a `knn` block specifying `query_vector`, `k`, and `num_candidates` (typically `topK * 2`). Metadata filters are validated against a strict regex (`/^[a-zA-Z_][a-zA-Z0-9_]*$/`) and injected into the KNN filter block as boolean term queries.


Azure AI Search configures indices with `SearchField` vector definitions (supporting `Collection(Edm.Single)` or `Collection(Edm.Half)` precision) and optional Scalar or Binary Quantization compression profiles (`ScalarQuantizationCompression`, `BinaryQuantizationCompression`). Filtering is performed via OData filter expressions generated by `_build_filter_expression()`.


> [!NOTE]
> OpenSearch and Elasticsearch require explicit index settings (`index.knn: true` in OpenSearch; `dense_vector` mapping with `index: true` in Elasticsearch) to enable approximate nearest neighbor indexing. Without these settings, searches fall back to exact brute-force scans across all documents.


| Search Backend | Vector Mapping Type | Default Distance / Metric | Filter Execution Mechanism |
| :--- | :--- | :--- | :--- |
| **Elasticsearch** | `dense_vector` | `cosine` | `knn.filter` boolean term clauses |
| **OpenSearch** | `knn_vector` | `cosinesimil` | QueryDSL bool / term filters on `payload` |
| **Azure AI Search** | `Collection(Edm.Single)` | Cosine via HNSW profile | OData filter expression (`eq`, `and`) |


## In-Memory & Key-Value Stores: Redis and Valkey

In-memory data stores like Redis and Valkey employ RediSearch and RedisVL modules to index hash structures containing binary-encoded floating-point vector embeddings.


The `RedisDB` and `ValkeyDB` drivers store entries as Redis Hashes using keys prefixed with `mem0:{collection_name}:{id}`. Float32 arrays are converted to raw byte buffers (`np.array(vector, dtype=np.float32).tobytes()` in Python or `Buffer.from(new Float32Array(query).buffer)` in TypeScript) before persistence.


Schema definitions declare fields such as `memory_id`, `hash`, `agent_id`, `run_id`, `user_id` as `TAG` types, `memory` and `metadata` as `TEXT` or `TAG`, `created_at` as `NUMERIC`, and `embedding` as a `VECTOR` attribute using FLAT or HNSW algorithms.


```typescript
// Example: Building a Valkey / Redis pre-filter expression
export function buildRedisFilterExpr(filters?: SearchFilters): string {
  if (!filters) return "*";
  const conditions = Object.entries(toSnakeCase(filters))
    .filter(([, value]) => value !== null && value !== undefined)
    .map(([key, value]) => `@${key}:{${escapeRedisTagValue(value)}}`);
  return conditions.length > 0 ? conditions.join(" ") : "*";
}
```

> [!CAUTION]
> Tag filter values in RediSearch must be escaped via `escapeTagValue()` or `escapeRedisTagValue()` to neutralize special characters such as `*`, `|`, and whitespace. Unescaped tag values alter query syntax and can allow tenant-isolation filter bypasses.


## Distributed & Graph Backends: Cassandra, Neptune Analytics, Milvus, and Baidu Mochow

Distributed and specialized graph stores handle massive memory throughput using custom partition keys and vector-optimized storage engines.


- **Apache Cassandra**: Stores vectors as `list<float>` and payloads as JSON text inside tables structured under configurable keyspaces (default `mem0`). Search queries scan rows in pages (`PAGE_SIZE = 500`), normalize vectors, apply in-memory metadata filters, and maintain top-K results via `pushTopResult()`.
- **Amazon Neptune Analytics**: Operates as a serverless graph database where memory entities are stored as graph vertices with label `MEM0_VECTOR_{collection_name}` and identifier `~id`. Vector upserts and similarity searches execute Cypher procedures such as `CALL neptune.algo.vectors.upsert(n, embedding)` and `CALL neptune.algo.vectors.topKByEmbeddingWithFiltering(...)`.
- **Milvus / Zilliz**: Configures collections with `AUTOINDEX` for float vectors and `SPARSE_INVERTED_INDEX` with built-in `BM25` functions for hybrid sparse-dense retrieval over auto-tokenized `text` fields.
- **Baidu Mochow**: Utilizes typed tables (`STRING` id, `FLOAT_VECTOR` vector, `JSON` metadata) with HNSW vector indices and `BM25SearchRequest` full-text capabilities.


```mermaid
graph LR
    subgraph Cassandra
        C1["Scan Rows (Paged)"] --> C2["Normalize Vector & Parse Payload"]
        C2 --> C3["Filter & pushTopResult()"]
    end
    subgraph Neptune
        N1["Cypher Query Generation"] --> N2["neptune.algo.vectors.topKByEmbeddingWithFiltering"]
        N2 --> N3["Parse Node & Score Output"]
    end
    subgraph Milvus
        M1["Dense Vectors (AUTOINDEX)"] --> M2["Sparse Vectors (BM25 Function)"]
        M2 --> M3["Hybrid Search Result Ranking"]
    end
```


```typescript
async search(
  query: number[],
  topK: number = 5,
  filters?: SearchFilters,
): Promise<VectorStoreResult[]> {
  await this.initialize();
  this.assertVectorDimension(query, "Query");

  const scored: VectorStoreResult[] = [];
  await this.scanRows(
    `
      SELECT id, vector, payload
      FROM ${this.keyspace}.${this.collectionName}
    `,
    async (row) => {
      const vector = this.normalizeVector(row.vector);
      const payload = this.parsePayload(row.payload);
      if (!vector || vector.length !== this.dimension) {
        return;
      }
      const item: CassandraVector = {
        id: String(row.id),
        vector,
        payload,
      };
      if (!this.filterVector(item, filters)) {
        return;
      }
      this.pushTopResult(
        scored,
        {
          id: item.id,
          payload: item.payload,
          score: this.cosineSimilarity(query, item.vector),
        },
        topK,
      );
    },
    Math.max(topK, CassandraDB.PAGE_SIZE),
  );

  return scored;
}
```

## Configuration, Connection Management, and Lazy Loading

Database vector store initializers implement lazy connection loading to prevent optional peer dependencies (such as `@elastic/elasticsearch`, `pymongo`, `cassandra-driver`, `redis`, or `oracledb`) from breaking base package imports when a provider is not actively in use.


Clients and connection pools are initialized on demand during the first call to `initialize()`, which caches its execution promise (`_initPromise`) to prevent race conditions during concurrent startup sequences.


```typescript
// Example: Lazy peer loading pattern in OpenSearch and Elasticsearch
async initialize(): Promise<void> {
  if (!this._initPromise) {
    this._initPromise = this._doInitialize();
  }
  return this._initPromise;
}
```

| Configuration Property | Target Stores | Purpose & Default Behavior |
| :--- | :--- | :--- |
| `collection_name` / `tableName` | All Stores | Namespace or table identifier (defaults to `mem0` or `memories`) |
| `embeddingModelDims` / `dimension` | All Stores | Vector dimensionality (defaults to `1536`) |
| `autoRefresh` | OpenSearch | Controls `indices.refresh()` post-insert (default `false` for Serverless compatibility) |
| `useAzureCredential` | Azure MySQL, Azure AI Search | Authenticates via `@azure/identity` DefaultAzureCredential |


## Error Handling, Sanitization, and Security Invariants

Database vector stores enforce strict input sanitization and parameter binding guards to protect against injection attacks and malformed embeddings.


- **Filter Key Validation**: Drivers such as Elasticsearch, OpenSearch, pgvector, and Baidu enforce strict regular expression validation on filter keys (`/^[a-zA-Z_][a-zA-Z0-9_]*$/`) to prevent arbitrary query injection through metadata keys.
- **Operator Blocking**: MongoDB drivers reject filter values that contain dictionaries (`$ne`, `$gt`, etc.) to prevent NoSQL query operator injection.
- **Dimension Checking**: Insert and search operations validate that input vector lengths match configured embedding dimensions before issuing database commands.


> [!WARNING]
> Bypassing filter key validation or passing unvalidated user input directly into MongoDB query objects or SQL string templates can permit query manipulation. Always use the provided validation helpers (`_validate_filter`, `validateFilterValue`) prior to query construction.


## Related

- [Vector Store Architecture](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/vector-stores/vector-store-architecture)
- [Cloud Vector Backends](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/vector-stores/cloud-vector-backends)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/llms.txt) for all pages in this wiki.
