/nextjs-ai-skills:postgres-semantic-searchfrom nextjs-ai-skills
Builds and tunes PostgreSQL retrieval with pgvector, full-text search, pg_trgm, hybrid fusion, ParadeDB BM25, and reranking. Use for search/RAG implementation, weak results, filtered ANN scans, non-English corpora, or retrieval evaluation.
Ships in nextjs-ai-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Decisions, measured findings and silent failure modes for search built on Postgres, plus tested SQL building blocks in scripts/. Syntax the official docs cover well is left to them; what is here goes wrong without an error.
Change one thing at a time. Predefine the acceptance rule; by default require a gain beyond measured run-to-run spread on the affected query population, without a material loss on the other eval set. Inspect per-query wins/losses and require the agreed latency and cost budget to hold. The numerical findings below are corpus-specific observations, not universal performance guarantees.
vector(N) indexes up to 2,000;
up to 4,000 index a halfvec cast (or use a halfvec column); above that,
binary quantization or Matryoshka truncation.pg_search). Plain FTS with the fixes below is often enough.These return fewer rows, zero rows or plausible results, never an error.
pgvector (pgvector.md):
hnsw.ef_search (default 40). A larger
LIMIT, or a selective WHERE, silently returns fewer. Enable
hnsw.iterative_scan (off by default), or use partial indexes or partitions.ef_search can cost recall with no warning. Raise it until
recall against exact search stops moving. If EXPLAIN shows a seq scan,
tuning does nothing, and the seq scan may be the faster plan.MATERIALIZED CTE, other filters
inside it.SET is per connection. Behind a transaction pooler use SET LOCAL in the
same transaction, or a function-level SET.1 - (a <#> b) is not cosine similarity.Keyword (keyword-search.md):
plainto_tsquery and unquoted plain input to websearch_to_tsquery
AND bare terms, so long questions can match nothing. For plain-input
retrieval, consider OR and ts_rank_cd; preserve explicit web-search
quotes, OR and exclusions.unaccent merges distinct words in Finnish, Swedish, German or Turkish.
Fold only decorative accents, inside a text search configuration.% compares whole strings; use <% for prefixes and short queries
against long text.cl100k_base (text-embedding-3),
Finnish runs about 2.5 characters per token against 4 or more for English,
so an English-tuned character cap is about twice too generous. The endpoint
rejects the chunk and often fails the whole batch.finnish) lifted keyword-only search but not hybrid; a
dictionary lemmatizer did worse than the stemmer on spoken and domain text;
compound splitting flooded the arm. Re-measure on the target text.
Prefix matching never reaches the base form of an inflected query
(keyword-search.md).Details and measurements: hybrid-search.md.
Numbers, model trade-offs and adoption rules: reranking.md.
For a new sample database, use setup.sql, then indexes.sql and selected
function files. For an existing database, review/adapt them as migrations: they
assume documents(id, title, content, metadata, embedding vector(1536)) and
chunks(id, document_id, chunk_index, content, embedding): change the names
and dimension in every file together. Some function files drop older signatures;
review dependent objects before applying them. These are building blocks, not a
complete production migration/authorization policy. None sets hnsw.ef_search;
the caller does, to at least the vector arm's candidate count: by default
hybrid_search_chunks_bm25 and hybrid_search_fuzzy_semantic ask for 50,
so the default 40 silently trims them.
| File | Functions (real parameter names) |
|---|---|
| semantic_search.sql | match_documents(query_embedding, match_threshold, match_count), match_documents_filtered(query_embedding, filter_metadata, match_threshold, match_count), match_chunks(query_embedding, match_threshold, match_count); match_threshold NULL = plain top-k |
| hybrid_search_fts.sql | hybrid_search_fts(query_embedding, query_text, match_count, rrf_k, fts_language, vector_weight, keyword_weight); either input may be NULL |
| hybrid_search_bm25.sql | hybrid_search_bm25(...), hybrid_search_chunks_bm25(...): same parameters without fts_language; needs pg_search |
| fuzzy_search.sql | fuzzy_search_trigram(query_text, similarity_threshold, max_results), autocomplete_search(search_prefix, max_results), hybrid_search_fuzzy_semantic(query_text, query_embedding, max_results, rrf_k) |
| prefix_tsquery.sql | prefix_tsquery(p_config, p_text [, p_join]) |
| setup.sql, indexes.sql | Extensions, example tables, indexes |
Supabase .rpc() binds arguments by name, so a misspelled key fails at call
time. node-postgres sends a JS array as an array literal ({"0.1","0.2"}) and
Drizzle's sql template expands it into ($1, $2, ...); both fail with
invalid input syntax for type vector or a cast error, so send
JSON.stringify(embedding) and cast with ::vector:
const { data, error } = await supabase.rpc('hybrid_search_fts', {
query_embedding: embedding, // number[]
query_text: userQuery,
match_count: 10,
fts_language: 'simple',
});
// Drizzle or node-postgres: send the vector as text and cast it
await db.execute(sql`SELECT * FROM match_documents(${JSON.stringify(embedding)}::vector, NULL, 10)`);
SELECT extversion FROM pg_extension WHERE extname = 'vector'. 0.8.0+ for
iterative scans. Check current stable releases: 0.8.2 fixed a
buffer overflow in parallel HNSW builds, 0.8.3 and 0.8.4 HNSW vacuum
corruption and errors, 0.8.7 a buffer overflow in IVFFlat builds. Before
upgrading, read the
CHANGELOG;
releases ship as git tags only, so the Releases tab is empty.| Need | Skill |
|---|---|
| General Postgres schema, non-search indexes, RLS, pooling | supabase-postgres-best-practices (Supabase plugin or supabase/agent-skills) |
| Embedding calls through the AI SDK | ai-sdk |
references/evaluation.md (opens in a new tab)references/hybrid-search.md (opens in a new tab)references/keyword-search.md (opens in a new tab)references/pgvector.md (opens in a new tab)references/reranking.md (opens in a new tab)scripts/fuzzy_search.sql (opens in a new tab)scripts/hybrid_search_bm25.sql (opens in a new tab)scripts/hybrid_search_fts.sql (opens in a new tab)scripts/indexes.sql (opens in a new tab)scripts/prefix_tsquery.sql (opens in a new tab)scripts/semantic_search.sql (opens in a new tab)scripts/setup.sql (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
pgvector, full-text-search, hybrid-search, rag, postgresql-search
npx claudepluginhub laguagu/claude-code-nextjs-skills --plugin nextjs-ai-skills24 skills in this plugin
/agent-harness-reviewReviews an agent harness or agent design against Anthropic's agent and model prompting guidance (Opus 5.5, Fable 5.2), Cognition's context principles and 2026 research on skill routing and skill-induced failures. Covers when subagents or parallel agents pay off, how to brief them, how many skills, plugins, MCP servers and hooks load every session, tool design and proportionate verification. Use when auditing a Claude Code or Codex setup, deciding whether to add subagents or a multi-agent workflow, trimming a skill library, or designing an agent loop in an app. For writing a new skill or measuring a skill's trigger rate with evals, use skill-creator./ai-appBuilds full-stack Next.js AI applications with the AI SDK and the shadcn/ui AI Elements patterns. Use when creating a chatbot, agent dashboard or custom AI application./ai-elementsMaintains AI chat UI built from elements.ai-sdk.dev AI Elements components already copied into the project. Use when changing or debugging those components (conversations, messages, prompt inputs, attachments, reasoning, tool output, sources). New chat UI uses the shadcn/ui AI Elements patterns (`shadcn` skill)./ai-sdkAnswer questions about the AI SDK and help build AI-powered features. Use when developers ask about Vercel AI SDK, generateText, streamText, ToolLoopAgent, useChat, AI SDK providers, tools, structured output, embeddings or streaming, or want to add AI features to a TypeScript or JavaScript app. First identify the installed major version and route version-specific work: use ai-sdk-7 for AI SDK 7 features/migrations such as WorkflowAgent, HarnessAgent, reasoning, runtime/tools context, toolApproval, telemetry, realtime, or v6-to-v7 upgrades; for v6 code read the docs shipped in the installed package./ai-sdk-6Vercel AI SDK v6 development, for projects already on ai@6. Use when building or maintaining AI agents, chatbots, tool integrations, streaming apps, or structured output in a v6 codebase. New projects and ai@7 code use ai-sdk-7; an unknown version goes through ai-sdk. Covers ToolLoopAgent, useChat, generateText, streamText, tool approval, provider tools, MCP integration, and Output patterns./ai-sdk-7Vercel AI SDK v7 development and migration. Use when building or upgrading AI SDK 7 apps, especially ToolLoopAgent, WorkflowAgent, HarnessAgent, Claude Code/Codex/Pi harnesses, runtimeContext, toolsContext, toolApproval, telemetry, reasoning, file or skill uploads, realtime, video generation, or v6-to-v7 breaking changes. For version discovery, v6 code and general doc lookup use ai-sdk.Other plugins' skills for the same job