ChromaDB 완벽 가이드 | 오픈소스 Vector DB·임베딩·RAG·로컬 실행·실전 활용

ChromaDB 완벽 가이드 | 오픈소스 Vector DB·임베딩·RAG·로컬 실행·실전 활용

이 글의 핵심

ChromaDB로 로컬 벡터 검색을 구현하는 완벽 가이드입니다. 오픈소스, 로컬 실행, 임베딩 저장, RAG 구현까지 실전 예제로 정리했습니다.

실무 경험 공유: Pinecone에서 ChromaDB로 전환하면서, 비용이 100% 절감되고 개발 속도가 2배 빨라진 경험을 공유합니다.

들어가며: “Vector DB 비용이 부담돼요”

실무 문제 시나리오

시나리오 1: 클라우드 비용이 높아요
Pinecone은 비쌉니다. ChromaDB는 무료 오픈소스입니다.

시나리오 2: 로컬 개발이 어려워요
클라우드는 느립니다. ChromaDB는 로컬에서 빠르게 실행됩니다.

시나리오 3: 데이터 프라이버시가 중요해요
클라우드는 걱정됩니다. ChromaDB는 로컬에서 안전합니다.


1. ChromaDB란?

핵심 특징

ChromaDB는 오픈소스 벡터 데이터베이스입니다.

주요 장점:

  • 오픈소스: 무료
  • 로컬 실행: 빠른 개발
  • 간단한 API: 쉬운 사용
  • LangChain 통합: 완벽한 호환
  • Metadata 필터링: 정교한 검색

2. 설치 및 기본 사용

설치

pip install chromadb

기본 사용

import chromadb

# 클라이언트 생성
client = chromadb.Client()

# Collection 생성
collection = client.create_collection(name="my_collection")

# 데이터 추가
collection.add(
    documents=["This is document 1", "This is document 2"],
    metadatas=[{"source": "doc1"}, {"source": "doc2"}],
    ids=["id1", "id2"]
)

# 검색
results = collection.query(
    query_texts=["document about Python"],
    n_results=2
)

print(results)

3. 임베딩

기본 임베딩

# 기본 임베딩 함수 사용
collection = client.create_collection(
    name="my_collection",
    metadata={"hnsw:space": "cosine"}
)

collection.add(
    documents=["Python is great", "JavaScript is popular"],
    ids=["id1", "id2"]
)

커스텀 임베딩

from chromadb.utils import embedding_functions

openai_ef = embedding_functions.OpenAIEmbeddingFunction(
    api_key="your-api-key",
    model_name="text-embedding-3-small"
)

collection = client.create_collection(
    name="my_collection",
    embedding_function=openai_ef
)

4. 검색

기본 검색

results = collection.query(
    query_texts=["Python programming"],
    n_results=5
)

for i, doc in enumerate(results[documents][0]):
    print(f"{i+1}. {doc}")
    print(f"   Distance: {results['distances'][0][i]}")

Metadata 필터링

results = collection.query(
    query_texts=["Python tutorial"],
    n_results=5,
    where={"category": "programming"},
    where_document={"$contains": "beginner"}
)

5. LangChain 통합

from langchain.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain.document_loaders import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter

# 문서 로드
loader = TextLoader("document.txt")
documents = loader.load()

# 청크 분할
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000)
chunks = text_splitter.split_documents(documents)

# Vector Store 생성
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(
    documents=chunks,
    embedding=embeddings,
    persist_directory="./chroma_db"
)

# 검색
docs = vectorstore.similarity_search("Python tutorial", k=3)

for doc in docs:
    print(doc.page_content)

6. RAG 챗봇

from langchain.chains import RetrievalQA
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4", temperature=0)

qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=vectorstore.as_retriever(search_kwargs={"k": 3})
)

def ask(question: str) -> str:
    response = qa_chain.invoke({"query": question})
    return response[result]

# 사용
print(ask("What is Python?"))
print(ask("How do I install packages?"))

7. Persistent Storage

# 저장
client = chromadb.PersistentClient(path="./chroma_db")

collection = client.get_or_create_collection(name="my_collection")

collection.add(
    documents=["Document 1", "Document 2"],
    ids=["id1", "id2"]
)

# 나중에 로드
client = chromadb.PersistentClient(path="./chroma_db")
collection = client.get_collection(name="my_collection")

정리 및 체크리스트

핵심 요약

  • ChromaDB: 오픈소스 Vector DB
  • 로컬 실행: 빠른 개발
  • 간단한 API: 쉬운 사용
  • LangChain 통합: 완벽한 호환
  • Metadata 필터링: 정교한 검색
  • 무료: 오픈소스

구현 체크리스트

  • ChromaDB 설치
  • Collection 생성
  • 데이터 추가
  • 검색 구현
  • LangChain 통합
  • RAG 구현
  • Persistent Storage 설정

같이 보면 좋은 글

  • Pinecone 완벽 가이드
  • LangChain 완벽 가이드
  • Vector Database 비교 가이드

이 글에서 다루는 키워드

ChromaDB, Vector Database, Embedding, RAG, AI, Open Source, Python

자주 묻는 질문 (FAQ)

Q. Pinecone과 비교하면 어떤가요?

A. ChromaDB가 무료이고 로컬 실행이 가능합니다. Pinecone은 관리형으로 확장성이 더 좋습니다.

Q. 프로덕션에서 사용할 수 있나요?

A. 네, 하지만 대규모는 Pinecone이나 Weaviate를 권장합니다.

Q. 어떤 임베딩 모델을 사용할 수 있나요?

A. OpenAI, Cohere, HuggingFace 등 다양한 모델을 사용할 수 있습니다.

Q. 무료인가요?

A. 네, 완전히 오픈소스이고 무료입니다.

... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3