๐Ÿค– AI/ML

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.

๐Ÿ“– Detailed Explanation

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.

๐Ÿ’ป Code Example

Vector search example using Pinecone and OpenAI embeddings:

Python
# 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}")

๐Ÿ“Š Performance & Cost

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.

๐Ÿ—ฃ๏ธ How It's Said in Practice

In a RAG system design meeting
"We'll chunk the documents, create embeddings, and put them into a vector database. Which is better, Pinecone or Weaviate? If we need hybrid search, I think Weaviate would be better."
In a search quality discussion
"Vector search alone is a bit lacking in accuracy, so I think adding metadata filtering and reranking would help."
In an infrastructure cost discussion
"With over 100 million records, Pinecone costs would add up quite a bit, so how about going with self-hosted Qdrant?"
In the early stage of development
"Let's first test quickly locally with Chroma, and then migrate to Pinecone for production later."

โš ๏ธ Common Mistakes & Cautions

Ignoring chunking strategy
Embedding whole documents degrades search quality. Chunk appropriately by semantic unit (500-1000 tokens), and add overlap between chunks to prevent context loss.
Embedding model mismatch
You must use the same embedding model when indexing and when searching. If the model changes, the vector space differs and search results become meaningless.
Relying on vector search alone
Vector search is strong at semantic similarity but weak at exact keyword matching. When exact matching is needed, such as for product names or code, use hybrid search (vector + BM25).
Neglecting metadata design
Don't store only vectors; store metadata for filtering (date, category, source, etc.) alongside them. If a requirement such as "search only within documents from the last year" arises later, metadata filters are essential.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More