Files
2nd/10_Wiki/Topic_General/From_Other/Search.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

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 정리 |