pgvector-semantic-search
Use this skill for setting up vector similarity search with pgvector for AI/ML embeddings, RAG applications, or semantic search. **Trigger when user asks to:** - Store or search vector embeddings in PostgreSQL - Set up semantic search, similarity search, or nearest neighbor search - Create HNSW or IVFFlat indexes for vectors - Implement RAG (Retrieval Augmented Generation) with PostgreSQL - Optimize pgvector performance, recall, or memory usage - Use binary quantization for large vector datasets **Keywords:** pgvector, embeddings, semantic search, vector similarity, HNSW, IVFFlat, halfvec, cosine distance, nearest neighbor, RAG, LLM, AI search Covers: halfvec storage, HNSW index configuration (m, ef_construction, ef_search), quantization strategies, filtered search, bulk loading, and performance tuning.
What this skill does
# pgvector for Semantic Search Semantic search finds content by meaning rather than exact keywords. An embedding model converts text into high-dimensional vectors, where similar meanings map to nearby points. pgvector stores these vectors in PostgreSQL and uses approximate nearest neighbor (ANN) indexes to find the closest matches quickly—scaling to millions of rows without leaving the database. Store your text alongside its embedding, then query by converting your search text to a vector and returning the rows with the smallest distance. This guide covers pgvector setup and tuning—not embedding model selection or text chunking, which significantly affect search quality. Requires pgvector 0.8.0+ for all features (`halfvec`, `binary_quantize`, iterative scan). ## Golden Path (Default Setup) Use this configuration unless you have a specific reason not to. - Embedding column data type: `halfvec(N)` where `N` is your embedding dimension (must match everywhere). Examples use 1536; replace with your dimension `N`. - Distance: cosine (`<=>`) - Index: HNSW (`m = 16`, `ef_construction = 64`). Use `halfvec_cosine_ops` and query with `<=>`. - Query-time recall: `SET hnsw.ef_search = 100` (good starting point from published benchmarks, increase for higher recall at higher latency) - Query pattern: `ORDER BY embedding <=> $1::halfvec(N) LIMIT k` This setup provides a strong speed–recall tradeoff for most text-embedding workloads. ## Core Rules - **Enable the extension** in each database: `CREATE EXTENSION IF NOT EXISTS vector;` - **Use HNSW indexes by default**—superior speed-recall tradeoff, can be created on empty tables, no training step required. Only consider IVFFlat for write-heavy or memory-bound workloads. - **Use `halfvec` by default**—store and index as `halfvec` for 50% smaller storage and indexes with minimal recall loss. - **Index after bulk loading** initial data for best build performance. - **Create indexes concurrently** in production: `CREATE INDEX CONCURRENTLY ...` - **Use cosine distance by default** (`<=>`): For non-normalized embeddings, use cosine. For unit-normalized embeddings, cosine and inner product yield identical rankings; default to cosine. - **Match query operator to index ops**: Index with `halfvec_cosine_ops` requires `<=>` in queries; `halfvec_l2_ops` requires `<->`; mismatched operators won't use the index. - **Always cast query vectors explicitly** (`$1::halfvec(N)`) to avoid implicit-cast failures in prepared statements. - **Always use the same embedding model for data and queries**. Similarity search only works when the model generating the vectors is the same. ## Type Rules - Store embeddings as `halfvec(N)` - Cast query vectors to `halfvec(N)` - Store binary quantized vectors as `bit(N)` in a generated column - Do not mix `vector` / `halfvec` / `bit` without explicit casts - Never call `binary_quantize()` on table columns inside `ORDER BY`; store it instead - Dimensions must match: a `halfvec(1536)` column requires query vectors cast as `::halfvec(1536)`. ## Standard Pattern ```sql -- Store and index as halfvec CREATE TABLE items ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, contents TEXT NOT NULL, embedding halfvec(1536) NOT NULL -- NOT NULL requires embeddings generated before insert, not async ); CREATE INDEX ON items USING hnsw (embedding halfvec_cosine_ops); -- Query: returns 10 closest items. $1 is the embedding of your search text. SELECT id, contents FROM items ORDER BY embedding <=> $1::halfvec(1536) LIMIT 10; ``` For other distance operators (L2, inner product, etc.), see the [pgvector README](https://github.com/pgvector/pgvector). ## HNSW Index The recommended index type. Creates a multilayer navigable graph with superior speed-recall tradeoff. Can be created on empty tables (no training step required). ```sql CREATE INDEX ON items USING hnsw (embedding halfvec_cosine_ops); -- With tuning parameters CREATE INDEX ON items USING hnsw (embedding halfvec_cosine_ops) WITH (m = 16, ef_construction = 64); ``` ### HNSW Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `m` | 16 | Max connections per layer. Higher = better recall, more memory | | `ef_construction` | 64 | Build-time candidate list. Higher = better graph quality, slower build | | `hnsw.ef_search` | 40 | Query-time candidate list. Higher = better recall, slower queries. Should be ≥ LIMIT. | **ef_search tuning (rough guidelines—actual results vary by dataset):** | ef_search | Approx Recall | Relative Speed | |-----------|---------------|----------------| | 40 | lower (~95% on some benchmarks) | 1x (baseline) | | 100 | higher | ~2x slower | | 200 | very-high | ~4x slower | | 400 | near-exact | ~8x slower | ```sql -- Set search parameter for session SET hnsw.ef_search = 100; -- Set for single query BEGIN; SET LOCAL hnsw.ef_search = 100; SELECT id, contents FROM items ORDER BY embedding <=> $1::halfvec(1536) LIMIT 10; COMMIT; ``` ## IVFFlat Index (Generally Not Recommended) Default to HNSW. Use IVFFlat only when HNSW’s operational costs matter more than peak recall. Choose IVFFlat if: - Write-heavy or constantly changing data AND you're willing to rebuild the index frequently - You rebuild indexes often and want predictable build time and memory usage - Memory is tight and you cannot keep an HNSW graph mostly resident - Data is partitioned or tiered, and this index lives on colder partitions Avoid IVFFlat if you need: - highest recall at low latency - minimal tuning - a “set and forget” index Notes: - IVFFlat requires data to exist before index creation. - Recall depends on `lists` and `ivfflat.probes`; higher probes = better recall, slower queries. Starter config: ```sql CREATE INDEX ON items USING ivfflat (embedding halfvec_cosine_ops) WITH (lists = 1000); SET ivfflat.probes = 10; ``` ## Quantization Strategies - Quantization is a memory decision, not a recall decision. - Use `halfvec` by default for storage and indexing. - Estimate HNSW index footprint as ~4–6 KB per 1536-dim `halfvec` (m=16) (order-of-magnitude); 3072-dim is ~2×; m=32 roughly doubles HNSW link/graph overhead. - If p95/p99 latency rises while CPU is mostly idle, the HNSW index is likely no longer resident in memory. - If `halfvec` doesn’t fit, use binary quantization + re-ranking. ### Guidelines for 1536-dim vectors Approximate `halfvec` capacity at `m=16`, 1536-dim (assumes RAM mostly available for index caching): | RAM | Approx max halfvec vectors | |-----|----------------------------| | 16 GB | ~2–3M vectors | | 32 GB | ~4–6M vectors | | 64 GB | ~8–12M vectors | | 128 GB | ~16–25M vectors | For 3072-dim embeddings, divide these numbers by ~2. For `m=32`, also divide capacity by ~2. If the index cannot fit in memory at this scale, use binary quantization. These are ranges, not guarantees. Validate by monitoring cache residency and p95/p99 latency under load. ### Binary Quantization (For Very Large Datasets) 32× memory reduction. Use with re-ranking for acceptable recall. ```sql -- Table with generated column for binary quantization CREATE TABLE items ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, contents TEXT NOT NULL, embedding halfvec(1536) NOT NULL, embedding_bq bit(1536) GENERATED ALWAYS AS (binary_quantize(embedding)::bit(1536)) STORED ); CREATE INDEX ON items USING hnsw (embedding_bq bit_hamming_ops); -- Query with re-ranking for better recall -- ef_search must be >= inner LIMIT to retrieve enough candidates SET hnsw.ef_search = 800; WITH q AS ( SELECT binary_quantize($1::halfvec(1536))::bit(1536) AS qb ) SELECT * FROM ( SELECT i.id, i.contents, i.embedding FROM items i, q ORDER BY i.embedding_bq <~> q.qb -- computes binary distance using index LIMIT 800 ) candidates ORDER BY candidates.embedding <=> $1::halfvec(1536) -- computes halfvec distance (no index), more accurate than binary LIMIT 10; ``` The 80× oversampling ratio (800 candidates for 10 results) i
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.