Command Palette

Search for a command to run...

UnylyUnyly
Back to skills

pgvector

FreeNo executable scriptsNot checked

pgvector is a PostgreSQL extension that stores vector embeddings in ordinary tables and searches them by similarity, so no separate vector database is needed…

TerminalSkillsby TerminalSkills★ 221 GitHub stars

About this skill

pgvector

Overview

pgvector adds vector types, distance operators and approximate indexes to PostgreSQL. Embeddings sit next to your relational data, so filters, joins, transactions and backups work as usual. Types: vector (up to 16,000 dimensions stored, 2,000 indexable), halfvec (half precision, 4,000 indexable), bit (binary) and sparsevec. Distance operators: <-> L2, <=> cosine, <#> negative inner product, <+> L1, <~> Hamming, <%> Jaccard. Latest release at the time of writing: 0.8.7 (2026-10-01); 0.8.x fixed several HNSW and IVFFlat bugs, so use the newest patch your provider offers.

Without an index, search is exact (perfect recall). With HNSW or IVFFlat it is approximate: results can differ from the exact answer.

Instructions

Install and enable

Hosted Postgres usually has it already; run CREATE EXTENSION vector; once per database. Self-hosted options: the pgvector/pgvector Docker image (for example pgvector/pgvector:pg17), apt install postgresql-17-pgvector from the PGDG repository, Homebrew, or building the tagged source (git clone --branch v0.8.7 https://github.com/pgvector/pgvector.git && make && make install). Check the version with SELECT extversion FROM pg_extension WHERE extname = 'vector';.

Schema and index

CREATE TABLE documents (
  id         bigserial PRIMARY KEY,
  tenant_id  int NOT NULL,
  title      text NOT NULL,
  content    text NOT NULL,
  metadata   jsonb NOT NULL DEFAULT '{}',
  embedding  vector(1536) NOT NULL,      -- must equal the embedding model's output size
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);
CREATE INDEX ON documents (tenant_id);   -- supports exact filtered search

Pick the operator class that matches the operator you query with: vector_cosine_ops for <=>, vector_l2_ops for <->, vector_ip_ops for <#>. Use halfvec_cosine_ops on halfvec columns. HNSW has better speed/recall than IVFFlat but builds slower and uses more memory; it needs no training data, so it can be created on an empty table. IVFFlat (USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100)) must be built after the data is loaded, and its quality depends on that data. In production build with CREATE INDEX CONCURRENTLY and raise maintenance_work_mem so the HNSW graph fits in memory.

For embeddings above 2,000 dimensions, store halfvec (index up to 4,000) or index a cast expression: CREATE INDEX ON documents USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops); and query with the same cast.

Query

-- nearest 5 by cosine distance; similarity = 1 - distance
SELECT id, title, 1 - (embedding <=> $1) AS similarity
FROM documents
WHERE tenant_id = $2
ORDER BY embedding <=> $1
LIMIT 5;

An index is used only for ORDER BY embedding <=> $1 LIMIT n (an ORDER BY on the distance operator). Tune recall per query inside a transaction: SET LOCAL hnsw.ef_search = 100; (default 40) or, for IVFFlat, SET LOCAL ivfflat.probes = 10; (default 1).

Approximate indexes filter after the scan, so a selective WHERE can return fewer than LIMIT rows. Since 0.8.0, enable iterative scans: SET LOCAL hnsw.iterative_scan = relaxed_order; (or strict_order; ivfflat.iterative_scan = relaxed_order). Other options: a B-tree on the filter column, partial indexes for a few fixed values, or partitioning by tenant. Check with EXPLAIN (ANALYZE, BUFFERS).

Node.js

// db.ts - node-postgres with pgvector-node (npm install pg pgvector openai)
import pg from "pg";
import pgvector from "pgvector/pg";
import OpenAI from "openai";

export const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL,
});
pool.on("connect", (client) => pgvector.registerTypes(client));
const openai = new OpenAI(); // reads OPENAI_API_KEY

export async function embed(text: string): Promise<number[]> {
  const res = await openai.embeddings.create({ model: "text-embedding-3-small", input: text });
  return res.data[0].embedding; // 1536 dimensions
}

export async function storeDocument(tenantId: number, title: string, content: string) {
  await pool.query(
    "INSERT INTO documents (tenant_id, title, content, embedding) VALUES ($1, $2, $3, $4)",
    [tenantId, title, content, pgvector.toSql(await embed(content))],
  );
}

export async function semanticSearch(tenantId: number, query: string, limit = 5) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query("SET LOCAL hnsw.iterative_scan = relaxed_order");
    const { rows } = await client.query(
      `SELECT id, title, content, 1 - (embedding <=> $1) AS similarity
       FROM documents WHERE tenant_id = $2 ORDER BY embedding <=> $1 LIMIT $3`,
      [pgvector.toSql(await embed(query)), tenantId, limit],
    );
    await client.query("COMMIT");
    return rows;
  } finally {
    client.release();
  }
}
Full SKILL.md on GitHub

Install pgvector in Claude Code & Claude Desktop

Sign up to install this skill

Create a free account to reveal the install command and save the skill to your library.

  • Reveal the one-line install command
  • Save skills to your synced library
  • Get notified when skills update
Sign up freeI already have an account

Allowed tools

Tools this skill is permitted to call.

No restriction — this skill can use any tool.

Bundled files

_scores.json

FAQ

What does the pgvector skill do?

pgvector is a PostgreSQL extension that stores vector embeddings in ordinary tables and searches them by similarity, so no separate vector database is needed. Use when someone asks for "vector search in Postgres", "store embeddings", "pgvector", "similarity search", "RAG with Postgres", "semantic search in an existing database", or "HNSW vs IVFFlat". Covers vector columns, indexes, filtered search, and Node.js and Drizzle usage.

How do I install the pgvector skill?

Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.

Does the pgvector skill run scripts?

No, this skill is instructions only (SKILL.md) with no executable scripts.

Related skills

Compare pgvector with