|
| 1 | +# Postgres + pgvector Backend |
| 2 | + |
| 3 | +The Postgres backend stores embeddings, metadata, and full-text content in a single relational database using the [pgvector](https://github.com/pgvector/pgvector) extension. This gives you ACID transactions, hybrid search (dense vectors + BM25 in one query), and JSONB metadata filtering — all without a separate vector service. |
| 4 | + |
| 5 | +## Prerequisites |
| 6 | + |
| 7 | +| Requirement | Minimum version | |
| 8 | +|---|---| |
| 9 | +| PostgreSQL | 14+ (15+ recommended for `HNSW` index type) | |
| 10 | +| pgvector extension | 0.5.0+ (`CREATE EXTENSION vector`) | |
| 11 | +| Node.js | 18+ (uses the `pg` npm package) | |
| 12 | + |
| 13 | +## Quick start — Docker |
| 14 | + |
| 15 | +```bash |
| 16 | +docker run -d \ |
| 17 | + --name agentos-pgvector \ |
| 18 | + -e POSTGRES_PASSWORD=wunderland \ |
| 19 | + -p 5432:5432 \ |
| 20 | + pgvector/pgvector:pg16 |
| 21 | + |
| 22 | +# Verify |
| 23 | +psql postgresql://postgres:wunderland@localhost:5432/postgres \ |
| 24 | + -c "CREATE EXTENSION IF NOT EXISTS vector; SELECT extversion FROM pg_extension WHERE extname='vector';" |
| 25 | +``` |
| 26 | + |
| 27 | +The `pgvector/pgvector` image ships with the extension pre-installed. No manual compilation needed. |
| 28 | + |
| 29 | +## Manual setup |
| 30 | + |
| 31 | +If you are using an existing Postgres instance (self-hosted or managed), install pgvector manually: |
| 32 | + |
| 33 | +```sql |
| 34 | +-- Run as a superuser or a user with CREATE EXTENSION privilege. |
| 35 | +CREATE EXTENSION IF NOT EXISTS vector; |
| 36 | +``` |
| 37 | + |
| 38 | +AgentOS creates its own tables on first use. The schema looks like: |
| 39 | + |
| 40 | +```sql |
| 41 | +CREATE TABLE IF NOT EXISTS "<prefix>my_collection" ( |
| 42 | + id TEXT PRIMARY KEY, |
| 43 | + embedding vector(1536), -- pgvector column |
| 44 | + metadata_json JSONB, -- GIN-indexed for filtering |
| 45 | + text_content TEXT, -- raw text for hybrid search |
| 46 | + tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', COALESCE(text_content, ''))) STORED, |
| 47 | + created_at BIGINT NOT NULL, |
| 48 | + updated_at BIGINT |
| 49 | +); |
| 50 | + |
| 51 | +-- Indexes created automatically: |
| 52 | +-- 1. HNSW index for approximate nearest neighbor search |
| 53 | +-- 2. GIN index on metadata_json for JSONB filtering |
| 54 | +-- 3. GIN index on tsv for full-text search |
| 55 | +``` |
| 56 | + |
| 57 | +## Configuration |
| 58 | + |
| 59 | +```typescript |
| 60 | +import { PostgresVectorStore } from '@framers/agentos/rag/implementations/vector_stores/PostgresVectorStore'; |
| 61 | + |
| 62 | +const store = new PostgresVectorStore({ |
| 63 | + id: 'my-pg-store', |
| 64 | + type: 'postgres', |
| 65 | + connectionString: 'postgresql://postgres:wunderland@localhost:5432/agent_memory', |
| 66 | + poolSize: 10, // Connection pool size (default: 10) |
| 67 | + defaultDimension: 1536, // Default embedding dimensions (default: 1536) |
| 68 | + similarityMetric: 'cosine', // 'cosine' | 'euclidean' | 'dotproduct' |
| 69 | + tablePrefix: 'agent1_', // Optional prefix for multi-tenancy |
| 70 | +}); |
| 71 | + |
| 72 | +await store.initialize(); |
| 73 | +``` |
| 74 | + |
| 75 | +### Configuration options |
| 76 | + |
| 77 | +| Option | Type | Default | Description | |
| 78 | +|---|---|---|---| |
| 79 | +| `connectionString` | `string` | **required** | Standard Postgres connection URI | |
| 80 | +| `poolSize` | `number` | `10` | Max concurrent connections in the pool | |
| 81 | +| `defaultDimension` | `number` | `1536` | Embedding vector dimensions for new collections | |
| 82 | +| `similarityMetric` | `string` | `'cosine'` | Distance function: `cosine`, `euclidean`, or `dotproduct` | |
| 83 | +| `tablePrefix` | `string` | `''` | Table name prefix for multi-tenant deployments | |
| 84 | + |
| 85 | +## Hybrid search |
| 86 | + |
| 87 | +The Postgres backend is the only backend that supports true **single-query hybrid search**: pgvector HNSW for dense vectors and PostgreSQL tsvector for BM25 lexical matching, fused with Reciprocal Rank Fusion (RRF) in a single SQL statement. |
| 88 | + |
| 89 | +```typescript |
| 90 | +const results = await store.hybridSearch( |
| 91 | + 'my_collection', |
| 92 | + queryEmbedding, |
| 93 | + 'natural language query text', |
| 94 | + { |
| 95 | + topK: 10, |
| 96 | + rrfK: 60, // RRF constant (default: 60) |
| 97 | + }, |
| 98 | +); |
| 99 | +``` |
| 100 | + |
| 101 | +How it works internally: |
| 102 | + |
| 103 | +1. **Dense CTE**: Finds top candidates by pgvector HNSW distance (`<=>` for cosine). |
| 104 | +2. **Lexical CTE**: Finds top candidates by `ts_rank()` against the `tsvector` column. |
| 105 | +3. **Fusion CTE**: Merges both result sets with `1/(k + rank_dense) + 1/(k + rank_lexical)`. |
| 106 | +4. **Final join**: Fetches full documents for the top fused results. |
| 107 | + |
| 108 | +This avoids two separate queries and application-level fusion. |
| 109 | + |
| 110 | +## Multi-tenancy via schema isolation |
| 111 | + |
| 112 | +For SaaS deployments where each tenant needs isolated data: |
| 113 | + |
| 114 | +```typescript |
| 115 | +// Tenant A |
| 116 | +const storeA = new PostgresVectorStore({ |
| 117 | + // ... |
| 118 | + tablePrefix: 'tenant_a_', |
| 119 | +}); |
| 120 | + |
| 121 | +// Tenant B |
| 122 | +const storeB = new PostgresVectorStore({ |
| 123 | + // ... |
| 124 | + tablePrefix: 'tenant_b_', |
| 125 | +}); |
| 126 | +``` |
| 127 | + |
| 128 | +Each prefix creates a separate set of tables: `"tenant_a_my_collection"`, `"tenant_a__collections"`, etc. Alternatively, use Postgres schemas (`SET search_path`) for stronger isolation. |
| 129 | + |
| 130 | +## Cloud providers |
| 131 | + |
| 132 | +Any managed Postgres with pgvector works. Just set the connection string: |
| 133 | + |
| 134 | +| Provider | Connection string example | |
| 135 | +|---|---| |
| 136 | +| **Neon** | `postgresql://user:pass@ep-cool-grass-123456.us-east-2.aws.neon.tech/neondb?sslmode=require` | |
| 137 | +| **Supabase** | `postgresql://postgres:pass@db.xyzabc.supabase.co:5432/postgres` | |
| 138 | +| **AWS RDS** | `postgresql://postgres:pass@mydb.cluster-xyz.us-east-1.rds.amazonaws.com:5432/mydb` | |
| 139 | +| **Google Cloud SQL** | `postgresql://postgres:pass@/mydb?host=/cloudsql/project:region:instance` | |
| 140 | +| **Azure Flexible Server** | `postgresql://postgres:pass@myserver.postgres.database.azure.com:5432/mydb?sslmode=require` | |
| 141 | + |
| 142 | +All of these support pgvector. Neon and Supabase have it pre-installed. For RDS, enable the `pgvector` extension in the parameter group. |
| 143 | + |
| 144 | +## Troubleshooting |
| 145 | + |
| 146 | +### `ERROR: could not open extension control file "vector"` |
| 147 | + |
| 148 | +pgvector is not installed. On managed services, check that the extension is enabled in your database configuration. For self-hosted: |
| 149 | + |
| 150 | +```bash |
| 151 | +# Ubuntu/Debian |
| 152 | +sudo apt install postgresql-16-pgvector |
| 153 | + |
| 154 | +# macOS (Homebrew) |
| 155 | +brew install pgvector |
| 156 | +``` |
| 157 | + |
| 158 | +Then run `CREATE EXTENSION vector;` as a superuser. |
| 159 | + |
| 160 | +### `ERROR: different vector dimensions` |
| 161 | + |
| 162 | +You changed `defaultDimension` after creating a collection. pgvector enforces dimension constraints at the column level. Drop and recreate the collection, or create a new collection with the correct dimension. |
| 163 | + |
| 164 | +### Connection refused / timeout |
| 165 | + |
| 166 | +- Verify the connection string host, port, and credentials. |
| 167 | +- Check that `pg_hba.conf` allows connections from your IP. |
| 168 | +- For Docker: ensure `-p 5432:5432` is set and the container is running. |
| 169 | +- For cloud: check firewall / security group rules. |
| 170 | + |
| 171 | +### Pool exhaustion (`too many clients already`) |
| 172 | + |
| 173 | +Increase `poolSize` in the config, or reduce concurrent usage. The default of 10 is usually sufficient for single-agent deployments. Multi-agent setups may need 20-50. |
0 commit comments