Semantic Search
Semantic Search
Meaning-based search. Searches by understanding context and intent rather than keywords. Finds relevant documents with embeddings and vector similarity.
Semantic Search
Meaning-based search. Searches by understanding context and intent rather than keywords. Finds relevant documents with embeddings and vector similarity.
Semantic Search is a search technique that understands the meaning and intent of a query to find relevant documents. Whereas traditional keyword search looking for "car repair" returns only documents containing exactly those words, Semantic Search also finds semantically related documents such as "vehicle maintenance," "auto shop," and "motorcycle inspection." This provides search results much closer to the "relevance" that users have in mind.
The core technology is embedding, which converts text into vectors. Queries and documents are mapped into the same vector space, and distance is measured with Cosine Similarity or Dot Product. Just as "king" and "queen" are close in vector space while "king" and "apple" are far apart, semantic similarity is expressed as geometric distance. Dense vectors of 768 to 1536 dimensions are typically used.
BERT (2018) and Sentence-BERT (2019) mark the beginning of modern Semantic Search. Earlier TF-IDF and BM25 were based on word frequency and could not understand synonyms or context. Searching for "bank interest rate" would also return "river bank," for example. Today, commercial embedding APIs such as OpenAI Embeddings (text-embedding-3-small/large), Cohere Embed, and Voyage AI, together with vector DBs such as Pinecone, Weaviate, Qdrant, and Milvus, form a rich ecosystem.
It is a core component of RAG (Retrieval-Augmented Generation), responsible for providing relevant information to the LLM. It is widely used in customer support chatbots, internal document search, product recommendation systems, plagiarism/duplicate detection, and legal precedent search. Combining Hybrid Search (BM25 + Semantic) captures both keyword precision and semantic understanding, so it is recommended in production environments. Techniques such as Reciprocal Rank Fusion (RRF) effectively merge the two sets of search results. Multimodal search (image + text) extends on the same principle.
# Semantic Search ๊ตฌํ ์์
from openai import OpenAI
import numpy as np
from typing import List
client = OpenAI()
def get_embedding(text: str) -> List[float]:
"""ํ
์คํธ๋ฅผ ๋ฒกํฐ๋ก ๋ณํ"""
response = client.embeddings.create(
input=text,
model="text-embedding-3-small"
)
return response.data[0].embedding
def cosine_similarity(a: List[float], b: List[float]) -> float:
"""์ฝ์ฌ์ธ ์ ์ฌ๋ ๊ณ์ฐ"""
a, b = np.array(a), np.array(b)
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
# ๋ฌธ์ ๋ฐ์ดํฐ๋ฒ ์ด์ค (์ค์ ๋ก๋ ๋ฒกํฐ DB ์ฌ์ฉ)
documents = [
"์ธ๊ณต์ง๋ฅ์ ์ปดํจํฐ๊ฐ ์ธ๊ฐ์ฒ๋ผ ํ์ตํ๊ณ ํ๋จํ๋ ๊ธฐ์ ์
๋๋ค.",
"๋จธ์ ๋ฌ๋์ ๋ฐ์ดํฐ์์ ํจํด์ ํ์ตํ๋ AI์ ํ ๋ถ์ผ์
๋๋ค.",
"๋ฅ๋ฌ๋์ ์ ๊ฒฝ๋ง์ ์ฌ๋ฌ ์ธต์ผ๋ก ์์ ๋ณต์กํ ํจํด์ ํ์ตํฉ๋๋ค.",
"์์ฐ์ด ์ฒ๋ฆฌ๋ ์ปดํจํฐ๊ฐ ์ธ๊ฐ์ ์ธ์ด๋ฅผ ์ดํดํ๋ ๊ธฐ์ ์
๋๋ค.",
"์ค๋ ์์ธ ๋ ์จ๋ ๋ง๊ณ ๊ธฐ์จ์ 15๋์
๋๋ค."
]
# ๋ฌธ์ ์๋ฒ ๋ฉ (์ฌ์ ๊ณ์ฐ)
doc_embeddings = [get_embedding(doc) for doc in documents]
def semantic_search(query: str, top_k: int = 3) -> List[tuple]:
"""Semantic Search ์คํ"""
query_embedding = get_embedding(query)
# ๋ชจ๋ ๋ฌธ์์ ์ ์ฌ๋ ๊ณ์ฐ
scores = [
(doc, cosine_similarity(query_embedding, emb))
for doc, emb in zip(documents, doc_embeddings)
]
# ์ ์ฌ๋ ๋์ ์์ผ๋ก ์ ๋ ฌ
scores.sort(key=lambda x: x[1], reverse=True)
return scores[:top_k]
# ๊ฒ์ ์์
query = "AI๊ฐ ์ค์ค๋ก ๋ฐฐ์ฐ๋ ๋ฐฉ๋ฒ"
results = semantic_search(query)
print(f"Query: {query}\n")
for doc, score in results:
print(f"[{score:.3f}] {doc}")
# ์ถ๋ ฅ:
# [0.892] ๋จธ์ ๋ฌ๋์ ๋ฐ์ดํฐ์์ ํจํด์ ํ์ตํ๋ AI์ ํ ๋ถ์ผ์
๋๋ค.
# [0.856] ์ธ๊ณต์ง๋ฅ์ ์ปดํจํฐ๊ฐ ์ธ๊ฐ์ฒ๋ผ ํ์ตํ๊ณ ํ๋จํ๋ ๊ธฐ์ ์
๋๋ค.
# [0.823] ๋ฅ๋ฌ๋์ ์ ๊ฒฝ๋ง์ ์ฌ๋ฌ ์ธต์ผ๋ก ์์ ๋ณต์กํ ํจํด์ ํ์ตํฉ๋๋ค.
# ํค์๋ ๊ฒ์์ด์๋ค๋ฉด "AI", "์ค์ค๋ก", "๋ฐฐ์ฐ๋"์ด ์์ด์ ๊ฒฐ๊ณผ๊ฐ ์์์ ๊ฒ!
# === Hybrid Search ๊ตฌํ (BM25 + Semantic) ===
from rank_bm25 import BM25Okapi
import numpy as np
class HybridSearch:
def __init__(self, documents: List[str], alpha: float = 0.5):
"""
alpha: semantic weight (1-alpha = BM25 weight)
"""
self.documents = documents
self.alpha = alpha
# BM25 ์ธ๋ฑ์ค
tokenized_docs = [doc.split() for doc in documents]
self.bm25 = BM25Okapi(tokenized_docs)
# Semantic ์๋ฒ ๋ฉ
self.doc_embeddings = [get_embedding(doc) for doc in documents]
def search(self, query: str, top_k: int = 5) -> List[tuple]:
# BM25 ์ ์
tokenized_query = query.split()
bm25_scores = self.bm25.get_scores(tokenized_query)
bm25_scores = bm25_scores / (bm25_scores.max() + 1e-8) # ์ ๊ทํ
# Semantic ์ ์
query_emb = get_embedding(query)
semantic_scores = np.array([
cosine_similarity(query_emb, doc_emb)
for doc_emb in self.doc_embeddings
])
# Hybrid ์ ์ (๊ฐ์ค ํฉ)
hybrid_scores = self.alpha * semantic_scores + (1 - self.alpha) * bm25_scores
# ์ ๋ ฌ ๋ฐ ๋ฐํ
indices = np.argsort(hybrid_scores)[::-1][:top_k]
return [(self.documents[i], hybrid_scores[i]) for i in indices]
# Pinecone ๋ฒกํฐ DB ์ฌ์ฉ ์์
from pinecone import Pinecone
pc = Pinecone(api_key="your-api-key")
index = pc.Index("my-semantic-index")
# ๋ฌธ์ ์
๋ก๋ (์๋ฒ ๋ฉ + ๋ฉํ๋ฐ์ดํฐ)
vectors = [
{"id": f"doc_{i}", "values": get_embedding(doc), "metadata": {"text": doc}}
for i, doc in enumerate(documents)
]
index.upsert(vectors=vectors)
# ์ฟผ๋ฆฌ
query_embedding = get_embedding("๋จธ์ ๋ฌ๋ ํ์ต ๋ฐฉ๋ฒ")
results = index.query(vector=query_embedding, top_k=5, include_metadata=True)
for match in results.matches:
print(f"[{match.score:.3f}] {match.metadata['text']}")
# === ๋ฌธ์ ์ฒญํน ์ ๋ต ===
def chunk_documents(text: str, chunk_size: int = 500, overlap: int = 100) -> List[str]:
"""๋ฌธ์๋ฅผ ์ ์ ํ ํฌ๊ธฐ๋ก ์ฒญํน (overlap์ผ๋ก ๋ฌธ๋งฅ ์ ์ง)"""
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunk = text[start:end]
chunks.append(chunk)
start += chunk_size - overlap # ๊ฒน์นจ ์ ์ฉ
return chunks
# === ์๋ฒ ๋ฉ ๋ชจ๋ธ ๋น๊ต ===
# text-embedding-3-small (OpenAI): 1536์ฐจ์, $0.02/1M ํ ํฐ
# text-embedding-3-large (OpenAI): 3072์ฐจ์, $0.13/1M ํ ํฐ
# multilingual-e5-large: ์คํ์์ค, ํ๊ตญ์ด ์ง์ ์ฐ์
# BGE-M3: ๋ค๊ตญ์ด + sparse/dense ํ์ด๋ธ๋ฆฌ๋
# === Reranking (2๋จ๊ณ ๊ฒ์) ===
# 1๋จ๊ณ: ๋น ๋ฅธ ๋ฒกํฐ ๊ฒ์์ผ๋ก ํ๋ณด 100๊ฐ ์ถ์ถ
# 2๋จ๊ณ: Cross-encoder๋ก ์ ๋ฐ ์ฌ์์
from sentence_transformers import CrossEncoder
reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
# ํ๋ณด ๋ฌธ์ ์ฌ์์
query = "ํ์ด์ฌ ๋ฆฌ์คํธ ์ ๋ ฌ ๋ฐฉ๋ฒ"
candidates = ["๋ฆฌ์คํธ.sort() ๋ฉ์๋ ์ฌ์ฉ", "sorted() ํจ์ ํ์ฉ", "๋ฐฐ์ด ๋ณํฉ ์ ๋ ฌ"]
scores = reranker.predict([(query, doc) for doc in candidates])
# rerank๋ ๊ฒฐ๊ณผ ๋ฐํ
# === ํ๊ฐ ๋ฉํธ๋ฆญ ===
def evaluate_search(queries, ground_truth, search_fn, k=10):
"""๊ฒ์ ํ์ง ํ๊ฐ (Recall@k, MRR)"""
recalls = []
mrrs = []
for query, relevant_ids in zip(queries, ground_truth):
results = search_fn(query, top_k=k)
result_ids = [r['id'] for r in results]
# Recall@k
found = len(set(result_ids) & set(relevant_ids))
recalls.append(found / len(relevant_ids))
# MRR (Mean Reciprocal Rank)
for i, rid in enumerate(result_ids):
if rid in relevant_ids:
mrrs.append(1 / (i + 1))
break
else:
mrrs.append(0)
return {
"Recall@k": sum(recalls) / len(recalls),
"MRR": sum(mrrs) / len(mrrs)
}
# === ํ๋ก๋์
ํ ===
# 1. ๋ฐฐ์น ์๋ฒ ๋ฉ: GPU ํ์ฉ์ผ๋ก 100๋ฐฐ ์ด์ ๋น ๋ฆ
# 2. ์ธ๋ฑ์ค ์ค๋ฉ: ๋๊ท๋ชจ ๋ฌธ์๋ ์ฌ๋ฌ ์ธ๋ฑ์ค๋ก ๋ถ์ฐ
# 3. ์บ์ฑ: ์์ฃผ ์ฐ๋ ์ฟผ๋ฆฌ ์๋ฒ ๋ฉ์ ์บ์
# 4. ANN ์๊ณ ๋ฆฌ์ฆ: HNSW, IVF๋ก ๊ทผ์ฌ ๊ฒ์ (99% ์ ํ๋, 10๋ฐฐ ๋น ๋ฆ)
# 5. ์ฃผ๊ธฐ์ ์ฌ์ธ๋ฑ์ฑ: ๋ฐ์ดํฐ ๋ณ๊ฒฝ ์ ์๋ฒ ๋ฉ ์
๋ฐ์ดํธ ํ์
"We'll do document search with Semantic Search and store the embeddings in Pinecone. We fetch the top-5 chunks per query and put them in the LLM context. With Hybrid Search, keyword lookups like proper nouns work well too."
"Semantic Search maps queries and documents into the same embedding space and searches by vector similarity. Unlike keyword search such as BM25, it understands synonyms and context. In a real project, we applied it to automatic classification of customer inquiries and improved search accuracy by 40%."
"Even if a user types 'I want a refund,' the 'refund policy' and 'return procedure' documents should come up. That's impossible with keyword matching, so we need Semantic Search. However, for exact codes like 'SKU-12345' BM25 is better, so it's best to go with Hybrid."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
If you embed queries with model A and documents with model B, the vector spaces differ and the similarity becomes meaningless. Always use the same model.
Embedding a long document all at once dilutes its meaning. Split it into chunks of 500-1000 characters and add overlap so that the context is not cut off.
We recommend the same embedding model, appropriate chunking (512 tokens + 100 tokens of overlap), and a Hybrid Search (BM25 + Semantic) combination. Filter out anything below the similarity threshold (for example, 0.7).