f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
160 lines
5.6 KiB
Markdown
160 lines
5.6 KiB
Markdown
---
|
|
id: wiki-2026-0508-search
|
|
title: Search
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Search Algorithm, Information Retrieval, Lookup]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [search, algorithms, ir, retrieval, ai]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: python
|
|
framework: 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)
|
|
```python
|
|
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
|
|
```python
|
|
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
|
|
```python
|
|
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
|
|
```python
|
|
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
|
|
- 부모: [[Information Retrieval]]
|
|
- 변형: [[MCTS]]
|
|
- 응용: [[RAG]]
|
|
- Adjacent: [[Search Space]] · [[Reranker]]
|
|
|
|
## 🤖 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 정리 |
|