similarity-search-patterns

similarity-search-patterns is a skill for Claude Code, Codex from NOMARJ/sigil. It costs 30 tokens per session (3,778 once invoked), scanned A, a copy of similarity-search-patterns, Apache-2.0.

A guide to building similarity search with vector databases, which compare numerical representations to find semantically related items.

In plain words
What is it for?
Use it for semantic search, RAG retrieval, recommendation systems, and searches that combine meaning with exact terms.
Why use it?
It helps select distance measures and index types, combine semantic and keyword matching, and keep retrieval efficient at larger sizes.

Skill for Claude CodeCodex

Written for no agent in particular: nothing here depends on one. Also seen: positional $N argument.

Good fit Use it for semantic search, RAG retrieval, recommendation systems, and searches that combine meaning with exact terms.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/nomarj/sigil/similarity-search-patterns
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add NOMARJ/sigil --skill similarity-search-patterns
Clone the repo
git clone --depth 1 https://github.com/NOMARJ/sigil

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for similarity-search-patterns

README.md
[![agentmods](https://agentmods.dev/badge/skills/nomarj/sigil/similarity-search-patterns/github.svg)](https://agentmods.dev/skills/nomarj/sigil/similarity-search-patterns)
Your own site
<a href="https://agentmods.dev/skills/nomarj/sigil/similarity-search-patterns"><img src="https://agentmods.dev/badge/skills/nomarj/sigil/similarity-search-patterns/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for similarity-search-patterns

Your own site · 80×15
<a href="https://agentmods.dev/skills/nomarj/sigil/similarity-search-patterns"><img src="https://agentmods.dev/badge/skills/nomarj/sigil/similarity-search-patterns.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 30 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 3,778 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 1 finding. A grade says what 26 rules found in the file — not that it is safe.
Origin 100% copy Near-identical to another mod in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00030 $0.03778
Opus 5 $0.00015 $0.01889
Sonnet 5 $0.00006 $0.00756
Haiku 4.5 $0.00003 $0.00378

Measured 9d ago against content hash 054d53f2d1ce, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-12, from the pricing page.

Security

Grade A, and why

similarity-search-patterns scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 9d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

rows = await conn.fetch(query, *params)
Origin

This is a copy

100% identical to similarity-search-patterns — 14 lines differ, which has more behind it and is treated as the original. This page carries a canonical link to it rather than competing with it.

packs/data/skills/llm/similarity-search-patterns/SKILL.md · 561 lines

How it starts

The opening of the file, as written. The whole thing — 561 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Similarity Search Patterns

Patterns for implementing efficient similarity search in production systems.

When to Use This Skill

  • Building semantic search systems
  • Implementing RAG retrieval
  • Creating recommendation engines
  • Optimizing search latency
  • Scaling to millions of vectors
  • Combining semantic and keyword search

Core Concepts

1. Distance Metrics

| Metric | Formula | Best For | | ------------------ | ------------------ | --------------------- | --- | -------------- | | Cosine | 1 - (A·B)/(‖A‖‖B‖) | Normalized embeddings | | Euclidean (L2) | √Σ(a-b)² | Raw embeddings | | Dot Product | A·B | Magnitude matters | | Manhattan (L1) | Σ | a-b | | Sparse vectors |

2. Index Types

┌─────────────────────────────────────────────────┐
│                 Index Types                      │
├─────────────┬───────────────┬───────────────────┤
│    Flat     │     HNSW      │    IVF+PQ         │
│ (Exact)     │ (Graph-based) │ (Quantized)       │
├─────────────┼───────────────┼───────────────────┤
│ O(n) search │ O(log n)      │ O(√n)             │
│ 100% recall │ ~95-99%       │ ~90-95%           │
│ Small data  │ Medium-Large  │ Very Large        │
└─────────────┴───────────────┴───────────────────┘

Templates

Template 1: Pinecone Implementation

from pinecone import Pinecone, ServerlessSpec
from typing import List, Dict, Optional
import hashlib

class PineconeVectorStore:
    def __init__(
        self,
        api_key: str,
        index_name: str,
        dimension: int = 1536,
        metric: str = "cosine"
    ):
        self.pc = Pinecone(api_key=api_key)

        # Create index if not exists
        if index_name not in self.pc.list_indexes().names():
            self.pc.create_index(
                name=index_name,
                dimension=dimension,
                metric=metric,
                spec=ServerlessSpec(cloud="aws", region="us-east-1")
            )

        self.index = self.pc.Index(index_name)

    def upsert(
        self,
        vectors: List[Dict],
        namespace: str = ""
    ) -> int:
        """
        Upsert vectors.
        vectors: [{"id": str, "values": List[float], "metadata": dict}]
        """
        # Batch upsert
        batch_size = 100
        total = 0

        for i in range(0, len(vectors), batch_size):
            batch = vectors[i:i + batch_size]
            self.index.upsert(vectors=batch, namespace=namespace)
            total += len(batch)

        return total

    def search(
        self,
        query_vector: List[float],
        top_k: int = 10,
        namespace: str = "",
        filter: Optional[Dict] = None,
        include_metadata: bool = True
    ) -> List[Dict]:
        """Search for similar vectors."""
        results = self.index.query(
            vector=query_vector,
            top_k=top_k,
            namespace=namespace,
            filter=filter,
            include_metadata=include_metadata
        )

        return [
            {
                "id": match.id,
                "score": match.score,
                "metadata": match.metadata
            }
            for match in results.matches
        ]

    def search_with_rerank(
        self,
        query: str,
        query_vector: List[float],
        top_k: int = 10,
        rerank_top_n: int = 50,
        namespace: str = ""
    ) -> List[Dict]:
        """Search and rerank results."""
        # Over-fetch for reranking
        initial_results = self.search(
            query_vector,
            top_k=rerank_top_n,
            namespace=namespace
        )

        # Rerank with cross-encoder or LLM
        reranked = self._rerank(query, initial_results)

        return reranked[:top_k]

    def _rerank(self, query: str, results: List[Dict]) -> List[Dict]:
        """Rerank results using cross-encoder."""
        from sentence_transformers import CrossEncoder

        model = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')

        pairs = [(query, r["metadata"]["text"]) for r in results]
        scores = model.predict(pairs)

        for result, score in zip(results, scores):
            result["rerank_score"] = float(score)

        return sorted(results, key=lambda x: x["rerank_score"], reverse=True)

    def delete(self, ids: List[str], namespace: str = ""):
        """Delete vectors by ID."""
        self.index.delete(ids=ids, namespace=namespace)

    def delete_by_filter(self, filter: Dict, namespace: str = ""):
        """Delete vectors matching filter."""
        self.index.delete(filter=filter, namespace=namespace)

Read the full file on GitHub · 561 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 9d ago First seen · 561 lines · 30 tokens per session scan A 054d53f2d1ce

Subscribe to this mod's changes

similarity-search-patterns is a skill published in the GitHub repository NOMARJ/sigil (5 stars, last pushed 6d ago), licensed Apache-2.0. It adds 30 tokens to every session and 3,778 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 1 finding (makes network calls). It is 100% identical to similarity-search-patterns, differing in 14 lines, and is treated as a copy.

Related

Other skills, from other repositories