Files
2nd/10_Wiki/Topics/Other/Search.md
T
2026-05-10 22:08:15 +09:00

5.8 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-search Search 10_Wiki/Topics verified self
Search Algorithm
Information Retrieval
Lookup
none A 0.9 applied
search
algorithms
ir
retrieval
ai
2026-05-10 pending
language framework
python search-algorithms

Search

매 한 줄

"매 search = 매 space 의 매 traverse 를 매 objective 의 만족 까지". 매 algorithmic search (BFS/DFS/A*) 부터 매 information retrieval (lexical + semantic) 까지 매 unify 하는 매 abstraction. 매 2026 년 의 search 는 매 vector embedding + LLM rerank + agent loop 의 매 hybrid stack.

매 핵심

매 search 의 두 의미

  • Algorithmic search: 매 state space 의 매 traverse — 매 BFS, DFS, A*, MCTS.
  • Information retrieval (IR): 매 corpus 에서 매 query 에 매 relevant document 추출 — 매 BM25, dense vector, hybrid.

매 modern stack (2026 IR)

  • 매 indexing: BM25 (lexical) + dense embedding (semantic, e.g., voyage-3, text-embedding-3-large).
  • 매 retrieval: hybrid (BM25 + ANN) → reciprocal rank fusion (RRF).
  • 매 rerank: cross-encoder (e.g., Cohere Rerank 3, BGE-reranker) — top-100 → top-10.
  • 매 generative answer: LLM (Claude Opus 4.7 / GPT-5) 의 매 retrieved context 의 매 grounded answer.
  • 매 agent loop: 매 multi-hop — 매 search → 매 reason → 매 search again.

매 응용

  1. RAG: 매 LLM 의 매 long-tail knowledge 보강.
  2. Code search: 매 codebase semantic + AST search.
  3. Pathfinding: 매 robotics, game AI.
  4. Game tree: 매 chess/go 의 매 minimax + MCTS.
  5. Web search: 매 Google, Bing, Perplexity, Exa, Tavily.

💻 패턴

Pattern 1: Hybrid retrieval (BM25 + dense)

from rank_bm25 import BM25Okapi
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

class HybridRetriever:
    def __init__(self, docs, embeddings, embed_fn):
        self.docs = docs
        self.bm25 = BM25Okapi([d.split() for d in docs])
        self.embs = embeddings
        self.embed_fn = embed_fn

    def search(self, query, k=10, alpha=0.5):
        bm25_scores = self.bm25.get_scores(query.split())
        q_emb = self.embed_fn(query)
        dense_scores = cosine_similarity([q_emb], self.embs)[0]
        # 매 normalize + weighted combine.
        bm25_n = (bm25_scores - bm25_scores.min()) / (bm25_scores.ptp() + 1e-9)
        dense_n = (dense_scores - dense_scores.min()) / (dense_scores.ptp() + 1e-9)
        scores = alpha * dense_n + (1 - alpha) * bm25_n
        top = np.argsort(-scores)[:k]
        return [(self.docs[i], scores[i]) for i in top]

Pattern 2: Reciprocal rank fusion

def rrf(rankings: list[list[int]], k=60):
    """매 rankings: 각 retriever 의 매 doc-id ordered list."""
    scores = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking):
            scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)

Pattern 3: LLM rerank

import anthropic

client = anthropic.Anthropic()

async def llm_rerank(query: str, candidates: list[str], top_k=5):
    prompt = f"""Rate each document 1-10 for relevance to query.

Query: {query}

Documents:
{chr(10).join(f'[{i}] {c[:300]}' for i, c in enumerate(candidates))}

Output JSON: {{"scores": [{{"id": 0, "score": 8.5}}, ...]}}"""
    msg = await client.messages.create(
        model="claude-opus-4-7",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
    )
    import json, re
    data = json.loads(re.search(r"\{.*\}", msg.content[0].text, re.S).group())
    ranked = sorted(data["scores"], key=lambda x: -x["score"])[:top_k]
    return [candidates[r["id"]] for r in ranked]

Pattern 4: Agent search loop

async def agent_search(question, max_steps=5):
    context = []
    for step in range(max_steps):
        plan = await llm.plan(question, context)
        if plan.action == "answer":
            return plan.answer
        if plan.action == "search":
            results = await retriever.search(plan.query, k=5)
            context.extend(results)
    return await llm.answer(question, context)

매 결정 기준

상황 Approach
매 keyword-heavy queries BM25 우위
매 semantic / paraphrase Dense embedding 우위
매 high-stakes accuracy Hybrid + cross-encoder rerank
매 multi-hop reasoning Agent loop (search-reason-search)
매 small corpus (<10k) In-memory FAISS / numpy
매 large corpus (>1M) Pinecone / Weaviate / Qdrant / pgvector

기본값: hybrid (BM25 + dense, RRF fusion) + 매 cross-encoder rerank top-100 → 10.

🔗 Graph

🤖 LLM 활용

언제: 매 RAG pipeline 의 매 retrieval / rerank / 매 agent search. 언제 X: 매 known-key direct lookup — 매 hash table 의 매 LLM 사용 X.

안티패턴

  • Dense-only: 매 keyword 의 매 정확 매칭 의 의미 — BM25 보강 필요.
  • No reranker: top-10 직접 LLM context — 매 noise 많음.
  • Unbounded agent loop: 매 max_steps 없는 agent — 매 cost 폭발.

🧪 검증 / 중복

  • Verified (Lin et al. Pretrained Transformers for Text Ranking 2021; RRF Cormack 2009).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — Search 의 algorithmic + IR 두 의미, 2026 hybrid stack, BM25/dense/RRF/rerank/agent loop 정리