为GraphRAG接入Qdrant自定义向量存储
介绍如何通过继承VectorStore基类,把Qdrant作为GraphRAG的自定义向量存储后端,涵盖集合创建、文档向量写入与相似度检索的完整实现流程。
## 微软 GraphRAG [微软 GraphRAG](<https://github.com/microsoft/graphrag>) 是一个 Python 库,用于从无结构文本构建知识图,并将其用于生成检索。它将基于图表的索引与矢量搜索结合起来,以提高LLM响应的质量和相关性。 Qdrant 可以用作GraphRAG的自定义矢量存储后端,使您能够利用Qdrant的性能和可扩展性来存储和搜索嵌入文档. ## 安装 安装所需的软件包 : ```bash pip install graphrag qdrant-client ``` ## 自定义矢量存储执行 GraphRAG 允许您通过扩展自定义矢量存储器注册 。 `VectorStore` 基准类 : ```python import uuid from qdrant_client import QdrantClient from qdrant_client.models import Distance, VectorParams, PointStruct from graphrag_vectors import VectorStore, VectorStoreDocument class QdrantVectorStore(VectorStore): def __init__(self, **kwargs): super().__init__(**kwargs) self.client = QdrantClient( url="https://xyz-example.eu-central.aws.cloud.qdrant.io:6333", api_key="<your-api-key>", ) self.collection_name = self.index_name self.vector_size = kwargs.get("vector_size", 384) def create_index(self, **kwargs): self.client.create_collection( collection_name=self.collection_name, vectors_config=VectorParams( size=self.vector_size, distance=Distance.COSINE ), ) def load_documents( self, documents: list[VectorStoreDocument], overwrite: bool = False ): points = [ PointStruct(id=str(uuid.uuid4()), vector=doc.vector, payload={"_original_id": doc.id}) for doc in documents if doc.vector ] self.client.upsert(collection_name=self.collection_name, points=points) def similarity_search_by_vector( self, query_embedding: list[float], k: int = 10, **kwargs ): results = self.client.query_points( collection_name=self.collection_name, query=query_embedding, limit=k, ).points return [ VectorStoreSearchResult( document=VectorStoreDocument( id=hit.payload["_original_id"], vector=hit.vector ), score=hit.score, ) for hit in results ] # ...other graphrag_vectors.VectorStore methods ``` ## 使用量 注册并使用自定义 Qdrant 向量存储 : ```python from graphrag_vectors import ( register_vector_store, create_vector_store, VectorStoreConfig, IndexSchema, ) # Register the custom vector store register_vector_store("qdrant", QdrantVectorStore) # Create and initialize schema = IndexSchema(index_name="my_collection") vector_store = create_vector_store( VectorStoreConfig(type="qdrant", vector_size=1536), schema, ) vector_store.connect() vector_store.create_index() # Load documents documents = [ VectorStoreDocument(id="doc_1", vector=[0.1, 0.2, ...]), VectorStoreDocument(id="doc_2", vector=[0.3, 0.4, ...]), ] vector_store.load_documents(documents) results = vector_store.similarity_search_by_vector([0.5, 0.6, ...], k=5) ``` ## 进一步阅读 - [微软 GraphRAG 文档](<https://microsoft.github.io/graphrag/>) - [GraphRAG GitHub 仓库](<https://github.com/microsoft/graphrag>)
查看原始来源