pgvector
Store and search vector embeddings in PostgreSQL with pgvector — no separate vector database needed. Use when someone asks to "vector search in Postgres", "store embeddings", "pgvector", "similarity search", "RAG with Postgres", "semantic search in existing database", or "add AI search to my app without a separate vector DB". Covers vector columns, indexing (IVFFlat, HNSW), similarity search, and integration with ORMs.
What this skill does
# pgvector
## Overview
pgvector adds vector similarity search to PostgreSQL. Store embeddings alongside your regular data — no separate vector database, no data sync, no new infrastructure. Use your existing Postgres for semantic search, RAG, recommendations, and deduplication. Supports exact and approximate nearest neighbor search with IVFFlat and HNSW indexes.
## When to Use
- Adding semantic/vector search to an existing Postgres-backed app
- RAG (Retrieval-Augmented Generation) without running Pinecone/Qdrant/Weaviate
- Storing embeddings alongside relational data (users, products, documents)
- Recommendation systems based on content similarity
- Don't want to manage a separate vector database
## Instructions
### Setup
```sql
-- Enable the extension (available on Supabase, Neon, RDS, self-hosted)
CREATE EXTENSION IF NOT EXISTS vector;
```
### Schema Design
```sql
-- Store documents with embeddings alongside regular columns
CREATE TABLE documents (
id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
metadata JSONB DEFAULT '{}',
embedding vector(1536), -- OpenAI ada-002 dimension
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- HNSW index for fast approximate search (recommended)
CREATE INDEX ON documents
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- Or IVFFlat for lower memory usage
-- CREATE INDEX ON documents
-- USING ivfflat (embedding vector_cosine_ops)
-- WITH (lists = 100);
```
### Store Embeddings
```typescript
// ingest.ts — Generate and store embeddings
import { Pool } from "pg";
import OpenAI from "openai";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const openai = new OpenAI();
async function storeDocument(title: string, content: string, metadata: object = {}) {
// Generate embedding
const embeddingRes = await openai.embeddings.create({
model: "text-embedding-3-small",
input: content,
});
const embedding = embeddingRes.data[0].embedding;
// Store with embedding (pgvector accepts array format)
await pool.query(
`INSERT INTO documents (title, content, metadata, embedding)
VALUES ($1, $2, $3, $4)`,
[title, content, JSON.stringify(metadata), JSON.stringify(embedding)]
);
}
```
### Similarity Search
```typescript
// search.ts — Find similar documents by vector distance
async function semanticSearch(query: string, limit = 5, threshold = 0.7) {
// Embed the query
const embeddingRes = await openai.embeddings.create({
model: "text-embedding-3-small",
input: query,
});
const queryEmbedding = embeddingRes.data[0].embedding;
// Cosine similarity search
const result = await pool.query(
`SELECT id, title, content, metadata,
1 - (embedding <=> $1::vector) AS similarity
FROM documents
WHERE 1 - (embedding <=> $1::vector) > $2
ORDER BY embedding <=> $1::vector
LIMIT $3`,
[JSON.stringify(queryEmbedding), threshold, limit]
);
return result.rows;
// [{ id: 1, title: "...", content: "...", similarity: 0.89 }, ...]
}
```
### RAG with pgvector
```typescript
// rag.ts — Retrieval-Augmented Generation using pgvector
async function ragAnswer(question: string): Promise<string> {
// 1. Find relevant documents
const docs = await semanticSearch(question, 5);
// 2. Build context from retrieved documents
const context = docs.map((d) => `## ${d.title}\n${d.content}`).join("\n\n");
// 3. Generate answer with context
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{
role: "system",
content: `Answer based on the following context. If the context doesn't contain the answer, say so.\n\n${context}`,
},
{ role: "user", content: question },
],
});
return completion.choices[0].message.content!;
}
```
### With Drizzle ORM
```typescript
// schema.ts — pgvector with Drizzle ORM
import { pgTable, text, serial, jsonb, index, timestamp } from "drizzle-orm/pg-core";
import { customType } from "drizzle-orm/pg-core";
// Custom vector type for Drizzle
const vector = customType<{ data: number[]; driverData: string }>({
dataType: () => "vector(1536)",
toDriver: (value) => JSON.stringify(value),
});
export const documents = pgTable("documents", {
id: serial("id").primaryKey(),
title: text("title").notNull(),
content: text("content").notNull(),
embedding: vector("embedding"),
createdAt: timestamp("created_at").defaultNow(),
});
```
## Examples
### Example 1: Add semantic search to an existing app
**User prompt:** "I have a Postgres database with articles. Add semantic search so users can search by meaning, not just keywords."
The agent will add a vector column, generate embeddings for existing articles, create an HNSW index, and build a search endpoint that combines vector similarity with existing filters.
### Example 2: Document Q&A with RAG
**User prompt:** "Build a Q&A system over our internal docs using our existing Postgres database."
The agent will chunk documents, store embeddings in pgvector, and build a RAG pipeline that retrieves relevant chunks and generates answers.
## Guidelines
- **HNSW index for most cases** — faster queries, slightly more memory than IVFFlat
- **Cosine distance (`<=>`)** — best for normalized embeddings (OpenAI, Cohere)
- **L2 distance (`<->`)** — for non-normalized embeddings
- **Dimension must match model** — ada-002: 1536, text-embedding-3-small: 1536
- **Index after bulk insert** — create index after loading data, not before
- **Filter + vector search** — combine `WHERE` clauses with vector similarity
- **No separate infrastructure** — one less service to manage, deploy, and pay for
- **Supabase has it built-in** — `enable_extension('vector')` in dashboard
- **Chunk long documents** — 500-1500 tokens per chunk for best retrieval
- **Re-embed when you change models** — embeddings from different models aren't compatible
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.