File size: 1,973 Bytes
17131ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import chromadb
from chromadb.config import Settings
import os
class VectorStore:
def __init__(self, persist_path: str, collection_name: str):
"""
Inisialisasi koneksi ke ChromaDB.
"""
if not os.path.exists(persist_path):
os.makedirs(persist_path, exist_ok=True)
print(f"[D&K] Connecting to ChromaDB at: {persist_path}")
# Setup Client
self.client = chromadb.PersistentClient(path=persist_path)
# Get or Create Collection
# metadata={"hnsw:space": "cosine"} agar similarity search akurat
self.collection = self.client.get_or_create_collection(
name=collection_name,
metadata={"hnsw:space": "cosine"}
)
print(f"[D&K] Collection '{collection_name}' ready. Total items: {self.collection.count()}")
def add_documents(self, ids, documents, embeddings, metadatas):
"""
Menyimpan batch data ke vector database.
"""
try:
self.collection.add(
ids=ids,
documents=documents,
embeddings=embeddings,
metadatas=metadatas
)
except Exception as e:
print(f"[D&K] Error adding documents: {e}")
def search(self, query_embedding, n_results=10):
"""
Mencari dokumen berdasarkan vector embedding query.
"""
results = self.collection.query(
query_embeddings=[query_embedding],
n_results=n_results
)
# Flatten results (Chroma returns lists of lists)
documents = results["documents"][0] if results["documents"] else []
metadatas = results["metadatas"][0] if results["metadatas"] else []
distances = results["distances"][0] if results["distances"] else []
return documents, metadatas, distances
def get_count(self):
return self.collection.count() |