Vector Database
Vector Database
A specialized database that stores high-dimensional vector embeddings and performs similarity search. Used for RAG, semantic search, and recommendation systems.
Vector Database
A specialized database that stores high-dimensional vector embeddings and performs similarity search. Used for RAG, semantic search, and recommendation systems.
A vector database is a specialized database that efficiently stores high-dimensional vector data and performs similarity-based search. Whereas traditional relational databases are optimized for exact value matching, vector databases specialize in finding "semantically similar" data. They convert text, images, audio, and other data into embedding vectors generated by AI models, store them, and quickly retrieve the vectors closest to a query vector.
The core technology of a vector database is the ANN (Approximate Nearest Neighbor) algorithm. Because finding the exact nearest neighbors among millions to hundreds of millions of high-dimensional vectors is computationally very expensive, approximate algorithms such as HNSW (Hierarchical Navigable Small World), IVF (Inverted File Index), and PQ (Product Quantization) are used. These algorithms sacrifice a small amount of accuracy to improve search speed by hundreds to thousands of times.
In practice, a vector database is a core component of a RAG (Retrieval-Augmented Generation) system. Documents are chunked and embedded, then stored in the vector database; document fragments similar to the user's question are then retrieved and provided to the LLM as context. Beyond this, it is also used in a variety of AI applications such as semantic search, image similarity search, recommendation systems, and duplicate detection.
Major vector databases include Pinecone (fully managed SaaS), Weaviate (open source, GraphQL API), Qdrant (high-performance, Rust-based), Milvus (large-scale distributed), and Chroma (for local development). There are also solutions that add vector capabilities to existing databases, such as pgvector for PostgreSQL and the vector search feature of Elasticsearch. When choosing, you should consider scalability, hosting options, metadata filtering, and whether hybrid search is supported.
Vector search example using Pinecone and OpenAI embeddings:
# Vector Database ํ์ฉ ์์ - Pinecone + OpenAI
# pip install pinecone-client openai
import os
from typing import List, Dict, Any
import hashlib
# Pinecone ํด๋ผ์ด์ธํธ (v3.0+)
from pinecone import Pinecone, ServerlessSpec
# OpenAI ์๋ฒ ๋ฉ
from openai import OpenAI
class VectorDBManager:
"""๋ฒกํฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค ๊ด๋ฆฌ ํด๋์ค"""
def __init__(self, pinecone_api_key: str, openai_api_key: str):
# ํด๋ผ์ด์ธํธ ์ด๊ธฐํ
self.pc = Pinecone(api_key=pinecone_api_key)
self.openai = OpenAI(api_key=openai_api_key)
self.embedding_model = "text-embedding-3-small"
self.dimension = 1536 # text-embedding-3-small ์ฐจ์
def create_index(self, index_name: str):
"""์ธ๋ฑ์ค ์์ฑ"""
# ๊ธฐ์กด ์ธ๋ฑ์ค ํ์ธ
existing_indexes = [idx.name for idx in self.pc.list_indexes()]
if index_name not in existing_indexes:
self.pc.create_index(
name=index_name,
dimension=self.dimension,
metric="cosine", # ์ฝ์ฌ์ธ ์ ์ฌ๋
spec=ServerlessSpec(
cloud="aws",
region="us-east-1"
)
)
print(f"Index '{index_name}' created successfully")
else:
print(f"Index '{index_name}' already exists")
return self.pc.Index(index_name)
def get_embedding(self, text: str) -> List[float]:
"""ํ
์คํธ๋ฅผ ์๋ฒ ๋ฉ ๋ฒกํฐ๋ก ๋ณํ"""
response = self.openai.embeddings.create(
input=text,
model=self.embedding_model
)
return response.data[0].embedding
def get_embeddings_batch(self, texts: List[str]) -> List[List[float]]:
"""๋ฐฐ์น ์๋ฒ ๋ฉ ์์ฑ"""
response = self.openai.embeddings.create(
input=texts,
model=self.embedding_model
)
return [item.embedding for item in response.data]
def upsert_documents(self, index, documents: List[Dict[str, Any]]):
"""
๋ฌธ์๋ฅผ ๋ฒกํฐ DB์ ์ฝ์
/์
๋ฐ์ดํธ
Args:
index: Pinecone ์ธ๋ฑ์ค
documents: [{"id": str, "text": str, "metadata": dict}, ...]
"""
# ์๋ฒ ๋ฉ ์์ฑ
texts = [doc["text"] for doc in documents]
embeddings = self.get_embeddings_batch(texts)
# ๋ฒกํฐ ์ค๋น
vectors = []
for doc, embedding in zip(documents, embeddings):
# ID ์์ฑ (์์ผ๋ฉด ํ
์คํธ ํด์)
doc_id = doc.get("id") or hashlib.md5(doc["text"].encode()).hexdigest()
vectors.append({
"id": doc_id,
"values": embedding,
"metadata": {
"text": doc["text"][:1000], # ๋ฉํ๋ฐ์ดํฐ ํฌ๊ธฐ ์ ํ
**doc.get("metadata", {})
}
})
# ๋ฐฐ์น ์
์ํธ (1000๊ฐ์ฉ)
batch_size = 100
for i in range(0, len(vectors), batch_size):
batch = vectors[i:i + batch_size]
index.upsert(vectors=batch)
print(f"Upserted {len(vectors)} documents")
def search(self, index, query: str, top_k: int = 5,
filter: Dict = None) -> List[Dict]:
"""
์ ์ฌ๋ ๊ฒ์
Args:
index: Pinecone ์ธ๋ฑ์ค
query: ๊ฒ์ ์ฟผ๋ฆฌ
top_k: ๋ฐํํ ๊ฒฐ๊ณผ ์
filter: ๋ฉํ๋ฐ์ดํฐ ํํฐ
Returns:
๊ฒ์ ๊ฒฐ๊ณผ ๋ฆฌ์คํธ
"""
# ์ฟผ๋ฆฌ ์๋ฒ ๋ฉ ์์ฑ
query_embedding = self.get_embedding(query)
# ๊ฒ์ ์คํ
results = index.query(
vector=query_embedding,
top_k=top_k,
include_metadata=True,
filter=filter
)
# ๊ฒฐ๊ณผ ์ ๋ฆฌ
formatted_results = []
for match in results.matches:
formatted_results.append({
"id": match.id,
"score": match.score,
"text": match.metadata.get("text", ""),
"metadata": match.metadata
})
return formatted_results
def hybrid_search(self, index, query: str, keyword_filter: str = None,
top_k: int = 5) -> List[Dict]:
"""
ํ์ด๋ธ๋ฆฌ๋ ๊ฒ์ (๋ฒกํฐ + ํค์๋)
"""
# ๋ฉํ๋ฐ์ดํฐ ํํฐ ๊ตฌ์ฑ
filter_dict = None
if keyword_filter:
filter_dict = {
"text": {"$contains": keyword_filter}
}
return self.search(index, query, top_k, filter_dict)
class RAGPipeline:
"""RAG (Retrieval-Augmented Generation) ํ์ดํ๋ผ์ธ"""
def __init__(self, vector_manager: VectorDBManager, index):
self.vector_manager = vector_manager
self.index = index
def add_documents(self, texts: List[str], metadata_list: List[Dict] = None):
"""๋ฌธ์ ์ถ๊ฐ"""
documents = []
for i, text in enumerate(texts):
doc = {
"text": text,
"metadata": metadata_list[i] if metadata_list else {}
}
documents.append(doc)
self.vector_manager.upsert_documents(self.index, documents)
def retrieve_context(self, query: str, top_k: int = 3) -> str:
"""์ฟผ๋ฆฌ์ ๊ด๋ จ๋ ์ปจํ
์คํธ ๊ฒ์"""
results = self.vector_manager.search(self.index, query, top_k)
context_parts = []
for i, result in enumerate(results):
context_parts.append(f"[{i+1}] {result['text']}")
return "\n\n".join(context_parts)
def generate_answer(self, query: str, top_k: int = 3) -> str:
"""RAG ๊ธฐ๋ฐ ๋ต๋ณ ์์ฑ"""
# 1. ๊ด๋ จ ๋ฌธ์ ๊ฒ์
context = self.retrieve_context(query, top_k)
# 2. ํ๋กฌํํธ ๊ตฌ์ฑ
prompt = f"""๋ค์ ์ปจํ
์คํธ๋ฅผ ๋ฐํ์ผ๋ก ์ง๋ฌธ์ ๋ต๋ณํด์ฃผ์ธ์.
์ปจํ
์คํธ:
{context}
์ง๋ฌธ: {query}
๋ต๋ณ:"""
# 3. LLM์ผ๋ก ๋ต๋ณ ์์ฑ
response = self.vector_manager.openai.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.7
)
return response.choices[0].message.content
# ์ฌ์ฉ ์์
if __name__ == "__main__":
# ํ๊ฒฝ ๋ณ์์์ API ํค ๋ก๋
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "your-api-key")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "your-api-key")
# ๋งค๋์ ์ด๊ธฐํ
manager = VectorDBManager(PINECONE_API_KEY, OPENAI_API_KEY)
# ์ธ๋ฑ์ค ์์ฑ
index = manager.create_index("knowledge-base")
# ๋ฌธ์ ์ถ๊ฐ
documents = [
{
"text": "๋ฒกํฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค๋ ๊ณ ์ฐจ์ ๋ฒกํฐ๋ฅผ ์ ์ฅํ๊ณ ์ ์ฌ๋ ๊ฒ์์ ์ํํฉ๋๋ค.",
"metadata": {"category": "database", "lang": "ko"}
},
{
"text": "RAG๋ ๊ฒ์๊ณผ ์์ฑ์ ๊ฒฐํฉํ์ฌ LLM์ ๋ต๋ณ ํ์ง์ ํฅ์์ํต๋๋ค.",
"metadata": {"category": "ai", "lang": "ko"}
},
{
"text": "Pinecone์ ์์ ๊ด๋ฆฌํ ๋ฒกํฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์๋น์ค์
๋๋ค.",
"metadata": {"category": "database", "lang": "ko"}
}
]
manager.upsert_documents(index, documents)
# ๊ฒ์ ํ
์คํธ
print("\n=== ์ ์ฌ๋ ๊ฒ์ ===")
results = manager.search(index, "๋ฒกํฐ DB๋ ๋ฌด์์ธ๊ฐ์?", top_k=2)
for r in results:
print(f"Score: {r['score']:.4f} | {r['text'][:50]}...")
# RAG ํ์ดํ๋ผ์ธ ํ
์คํธ
print("\n=== RAG ๋ต๋ณ ์์ฑ ===")
rag = RAGPipeline(manager, index)
answer = rag.generate_answer("RAG๊ฐ ๋ญ๊ฐ์?")
print(f"Answer: {answer}")
Comparison of major vector databases (as of 2025):
| Services | Pricing | Features | Suitable Use Cases |
|---|---|---|---|
| Pinecone | Usage-based (Free tier available) |
Fully managed Serverless | Rapid prototyping, minimal operational burden |
| Weaviate | $25~$153/month (Serverless) |
Open source GraphQL Hybrid search | Complex filtering, preference for self-hosting |
| Qdrant | $102+/month (Cloud) |
Rust-based SOC2 certified High performance | Large-scale production, security-critical |
| Chroma | Free (open source) |
Local execution Simple API | Local development, small-scale projects |
| pgvector | PostgreSQL cost | PostgreSQL extension SQL integration | Leveraging existing PostgreSQL, single database |
Selection guide: For a quick start, use Chroma (local) or Pinecone (cloud); for production scale, use Qdrant or Weaviate; and if you already have a PostgreSQL stack, pgvector is the economical choice. Most services offer a free tier, so try them out first.