๐Ÿค–AI/ML

Semantic Search

Semantic Search

Meaning-based search. Searches by understanding context and intent rather than keywords. Finds relevant documents with embeddings and vector similarity.

๐Ÿ“– Detailed Explanation

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.

๐Ÿ’ป Code Example

# 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. ์ฃผ๊ธฐ์  ์žฌ์ธ๋ฑ์‹ฑ: ๋ฐ์ดํ„ฐ ๋ณ€๊ฒฝ ์‹œ ์ž„๋ฒ ๋”ฉ ์—…๋ฐ์ดํŠธ ํ•„์š”

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In a RAG system design meeting
"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."
๐Ÿ’ฌ In an Interview
"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%."
๐Ÿ’ฌ In a discussion on improving search quality
"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

โš ๏ธ Common Mistakes & Cautions

โŒ
Using different embedding models for queries and documents

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 an entire long document at once

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.

โœ…
The right way

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).

๐Ÿ”— Related Terms

๐Ÿ“š Learn More