Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计提醒

postgres-semantic-searchPostgres semantic 搜索

Agent Skill

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。它适合让 Agent 分析 schema、编写 SQL、排查查询问题、整理索引或生成迁移建议。使用时需要明确数据库类型、连接环境和目标表,区分只读分析与写入变更;涉及删除、更新、迁移和批量导入时,应优先 dry-run、备份或事务保护,避免误操作。

总安装

2,252

周安装

92

GitHub Stars

29

下载量

721
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:postgres-semantic-search(Postgres semantic 搜索)
来源仓库:https://github.com/laguagu/claude-code-nextjs-skills
仓库路径:skills/postgres-semantic-search
安装命令:
npx skills add https://github.com/laguagu/claude-code-nextjs-skills --skill postgres-semantic-search
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/laguagu/claude-code-nextjs-skills --skill postgres-semantic-search

简介

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。

  • 适合分析 schema、编写 SQL、排查查询问题或生成索引优化建议。
  • 使用时需明确数据库类型和连接环境,区分只读分析与写入操作。
  • 涉及删除、更新、迁移或批量导入时,应优先 dry-run、备份或使用事务保护。
  • 建议结合语义向量扩展如 pgvector 使用,确保搜索功能具备实际可用性。

SKILL.md

PostgreSQL Semantic Search

Quick Start

1. Setup

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE documents (
    id SERIAL PRIMARY KEY,
    content TEXT NOT NULL,
    embedding vector(1536)  -- 1536-dim embedding
    -- Or: embedding halfvec(3072)  -- 3072-dim embedding (halfvec = 50% memory)
);

2. Basic Semantic Search

SELECT id, content, 1 - (embedding <=> query_vec) AS similarity
FROM documents
ORDER BY embedding <=> query_vec
LIMIT 10;

3. Add Index (> 10k documents)

CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);

Docker Quick Start

# pgvector with PostgreSQL 17
docker run -d --name pgvector-db \
  -e POSTGRES_PASSWORD=postgres \
  -p 5432:5432 \
  pgvector/pgvector:pg17

# Or PostgreSQL 18 (latest)
docker run -d --name pgvector-db \
  -e POSTGRES_PASSWORD=postgres \
  -p 5432:5432 \
  pgvector/pgvector:pg18

# ParadeDB (includes pgvector + pg_search + BM25)
docker run -d --name paradedb \
  -e POSTGRES_PASSWORD=postgres \
  -p 5432:5432 \
  paradedb/paradedb:latest

Connect: psql postgresql://postgres:postgres@localhost:5432/postgres

Cheat Sheet

Distance Operators

embedding <=> query  -- Cosine distance (1 - similarity)
embedding <-> query  -- L2/Euclidean distance
embedding <#> query  -- Negative inner product

Common Queries

-- Top 10 similar (cosine)
SELECT * FROM docs ORDER BY embedding <=> $1 LIMIT 10;

-- With similarity score
SELECT *, 1 - (embedding <=> $1) AS similarity FROM docs ORDER BY 2 DESC LIMIT 10;

-- With threshold
SELECT * FROM docs WHERE embedding <=> $1 < 0.3 ORDER BY 1 LIMIT 10;

-- Preload index (run on startup)
SELECT 1 FROM docs ORDER BY embedding <=> $1 LIMIT 1;

Index Quick Reference

-- HNSW (recommended)
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops);

-- With tuning
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops)
WITH (m = 24, ef_construction = 200);

-- Query-time recall
SET hnsw.ef_search = 100;

-- Iterative scan for filtered queries (pgvector 0.8+)
SET hnsw.iterative_scan = relaxed_order;
SET ivfflat.iterative_scan = on;

Decision Trees

Choose Search Method

Query type?
├─ Conceptual/meaning-based → Pure vector search
├─ Exact terms/names → Pure keyword search (FTS)
├─ Fuzzy/typo-tolerant → pg_trgm trigram similarity
├─ Autocomplete/prefix → pg_trgm + prefix index
├─ Substring (LIKE/ILIKE) → pg_trgm GIN index
└─ Mixed/unknown → Hybrid search
    ├─ Simple setup → FTS + RRF (no extra extensions)
    ├─ Better ranking → BM25 + RRF (pg_search extension)
    └─ Full-featured → ParadeDB (Elasticsearch alternative)

Choose Index Type

Document count?
├─ < 10,000 → No index needed
├─ 10k - 1M → HNSW (best recall)
└─ > 1M → IVFFlat (less memory) or HNSW

Choose Vector Type

Choose by dimensions, not by provider — the column type only depends on embedding size and pgvector's HNSW index limits.

Embedding dimensions (N)?
├─ N ≤ 2000  → vector(N)   — HNSW indexable directly
├─ 2000 < N ≤ 4000 → halfvec(N) — vector(N)'s HNSW limit is 2000; halfvec extends to 4000
└─ N > 4000  → vector(N) without HNSW, or quantize via dimensionality reduction

Common embedding dimensions are 1536 and 3072, but sizes vary by provider and model — check the provider's docs for the embedding you're using.

For multilingual / non-English content, prefer multilingual-tuned embedding models (look for "multilingual" in the model name). Models tuned only on English may handle compound words and inflection poorly.

Storage vs. index trick for 2000 < N ≤ 4000: keep the column as vector(N) (full float4, useful for future re-embedding or re-ranking experiments) and *only* cast at index creation and query time. This preserves precision on disk while staying within HNSW's dimension limit.

CREATE INDEX ON docs USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops);
-- Query must cast identically so the planner picks the index:
SELECT * FROM docs ORDER BY embedding::halfvec(3072) <=> $1 LIMIT 10;

If storage is tight or you never plan to re-embed, use halfvec(N) as the column type directly.

Measure before adopting

Every optimization in this skill (hybrid fusion, reranking, query expansion, embedding-model swaps) *can* regress on a specific corpus. Vendor and paper benchmarks are usually English, general-domain. Real counter-examples observed in production:

  • Query expansion (HyDE) regressing Hit@5 by tens of points on a domain corpus.
  • A widely recommended reranker regressing Hit@5 double-digits on multilingual text.

Rule: build a domain eval set (evaluation.md), then A/B each change. Adopt with ≥ +3 pp Hit@5 and p95 latency within budget; reject otherwise.

Operators

OperatorDistanceUse Case
<=>CosineText embeddings (default)
<->L2/EuclideanImage embeddings
<#>Inner productNormalized vectors

SQL Functions

Semantic Search

  • match_documents(query_vec, threshold, limit) - Basic search
  • match_documents_filtered(query_vec, metadata_filter, threshold, limit) - With JSONB filter
  • match_chunks(query_vec, threshold, limit) - Search document chunks

Fuzzy Search (pg_trgm)

  • fuzzy_search_trigram(query_text, threshold, limit) - Trigram similarity search
  • autocomplete_search(prefix, limit) - Prefix + fuzzy autocomplete
  • hybrid_search_fuzzy_semantic(query_text, query_vec, limit, rrf_k) - Fuzzy + vector RRF
  • weighted_fts_search(query_text, language, limit) - FTS with title/content weighting

Hybrid Search (FTS)

  • hybrid_search_fts(query_vec, query_text, limit, rrf_k, language) - FTS + RRF
  • hybrid_search_weighted(query_vec, query_text, limit, sem_weight, kw_weight) - Linear combination
  • hybrid_search_fallback(query_vec, query_text, limit) - Graceful degradation

Hybrid Search (BM25)

  • hybrid_search_bm25(query_vec, query_text, limit, rrf_k) - BM25 + RRF
  • hybrid_search_bm25_highlighted(...) - With snippet highlighting
  • hybrid_search_chunks_bm25(...) - For RAG with chunks

Re-ranking (Optional)

Two-stage retrieval improves precision: fast recall → precise rerank with a cross-encoder. Use when results need higher precision and you have <50 candidates after initial retrieval.

Key rule: rerankers must be wrapped so a failure (missing key, HTTP error, timeout) returns null and the caller falls back to original retrieval order — never let a reranker outage break search.

For provider comparison, generic Promise<T | null> wrapper, and self-hosted options, see reranking.md.

Multilingual / non-English content tips

When the corpus is non-English (Finnish, German, French, Spanish, etc.):

  • FTS language config: pass the matching language to to_tsvector(language, text) to apply the built-in snowball stemmer (e.g., 'finnish' handles opiskelija → opiskelij). For mixed-language corpora, use 'simple' and rely on prefix/trigram fallbacks instead.
  • Combine stemmer + unaccent for accent-insensitive matching ("café" matches "cafe"). See hybrid-search.md → Custom FTS configuration for the 3-step DDL pattern.
  • Prefix tsquery for languages with rich inflection (no full morphology engine required): CREATE OR REPLACE FUNCTION prefix_tsquery(p text) RETURNS tsquery LANGUAGE sql IMMUTABLE AS $$ SELECT to_tsquery('simple', string_agg(word || ':*', ' & ')) FROM regexp_split_to_table(lower(regexp_replace(p, '[^\w\s-]', ' ', 'g')), '\s+') AS word WHERE length(word) >= 2 $$; Matches kartta, karttaa, karttoja from a single kartta:* token.
  • Compound-word fallback: pair semantic search with pg_trgm similarity to catch compound-word misses (e.g., a query for "ammattikorkea" should still find "ammattikorkeakoulu").
  • BM25 stemmer in ParadeDB: tokenize with {"type": "default", "stemmer": "<language>"} — a raw tokenizer only matches full fields.
  • Multilingual embeddings: prefer models explicitly trained on your target language(s). English-only embeddings often miss inflected forms and compound words. The gap can be large — multilingual-tuned embeddings have been observed to beat general-purpose English-tuned ones by 10+pp Hit@5 on non-English retrieval. Benchmark your specific language + domain before committing.

References

Scripts

Common Patterns

TypeScript Integration (Supabase)

// Semantic search
const { data } = await supabase.rpc('match_documents', {
  query_embedding: embedding,
  match_threshold: 0.7,
  match_count: 10
});

// Hybrid search
const { data } = await supabase.rpc('hybrid_search_fts', {
  query_embedding: embedding,
  query_text: userQuery,
  match_count: 10,
  rrf_k: 60,
  fts_language: 'simple'
});

Drizzle ORM

import { sql } from 'drizzle-orm';

const results = await db.execute(sql`
  SELECT * FROM match_documents(
    ${embedding}::vector(1536),
    0.7,
    10
  )
`);

Troubleshooting

SymptomCauseSolution
Index not used< 10k rows or planner choiceNormal for small tables, check with EXPLAIN
Slow first query (30-60s)HNSW cold-startSELECT pg_prewarm('idx_name') or preload query
Poor recallLow ef_searchSET hnsw.ef_search = 100 or higher
FTS returns nothingWrong language configUse 'simple' for mixed/unknown languages
Memory error on index buildmaintenance_work_mem too lowIncrease to 2GB+
Cosine similarity > 1Vectors not normalizedNormalize before insert or use L2
Slow insertsIndex overheadBatch inserts, consider IVFFlat
Fuzzy search slowMissing trigram indexCREATE INDEX USING gin (col gin_trgm_ops)
ILIKE '%x%' slowNo pg_trgm GIN indexEnable pg_trgm + create GIN trigram index
% operator errorpg_trgm not installedCREATE EXTENSION IF NOT EXISTS pg_trgm

Compatibility

  • pgvector: 0.8+ recommended (iterative scans, halfvec). Check pgvector releases.
  • pg_search: Check ParadeDB releases for latest.
  • PostgreSQL: 17+ recommended. pgvector supports 13-18.

Related Skills

NeedSkill
General Postgres performance, indexes, RLS, connection pooling/supabase-postgres-best-practices
Chatbot orchestration, session DB, tool calls, HITL, feedback/nextjs-chatbot
AI SDK v6 usage for embeddings and retrieval/ai-sdk-6

For ParadeDB-specific questions, always apply the Documentation Fetch Policy in references/paradedb.md — live docs at https://docs.paradedb.com/llms-full.txt are the authoritative source.

External Documentation

Core

Embedding providers

Reranker providers

Hosting / extensions

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.84%
按下载量换算251

Claude

32.08%
按下载量换算231

Cursor

19.73%
按下载量换算142

Gemini CLI

10.11%
按下载量换算73

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills