Skip to main content
FalkorDB 是一款开源图数据库,内置向量相似度搜索支持。 它支持:
  • 近似最近邻搜索
  • 欧氏相似度和余弦相似度
  • 结合向量搜索与关键词搜索的混合搜索
本 Notebook 展示如何使用 FalkorDB 向量索引(FalkorDB)。 参见安装说明

设置

# 安装必要的包
pip install -U  falkordb
pip install -U  tiktoken
pip install -U  langchain langchain_huggingface

凭据

我们希望使用 HuggingFace,因此需要获取 HuggingFace API Key。
import getpass
import os

if "HUGGINGFACE_API_KEY" not in os.environ:
    os.environ["HUGGINGFACE_API_KEY"] = getpass.getpass("HuggingFace API Key:")
如果您希望获得模型调用的自动追踪,也可以通过取消注释以下内容来设置您的 LangSmith API key:
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

初始化

from langchain_community.vectorstores.falkordb_vector import FalkorDBVector
from langchain_core.documents import Document
from langchain_huggingface import HuggingFaceEmbeddings
您可以使用 Docker 在本地运行 FalkorDBVector。参见安装说明
host = "localhost"
port = 6379
或者使用 FalkorDB Cloud 运行 FalkorDBVector。
# 示例:
# host = "r-6jissuruar.instance-zwb082gpf.hc-v8noonp0c.europe-west1.gcp.f2e0a955bb84.cloud"
# port = 62471
# username = "falkordb" # 在 FALKORDB CLOUD 上设置
# password = "password" # 在 FALKORDB CLOUD 上设置
vector_store = FalkorDBVector(host=host, port=port, embedding=HuggingFaceEmbeddings())

管理向量存储

向向量存储添加条目

from langchain_core.documents import Document

document_1 = Document(page_content="foo", metadata={"source": "https://example.com"})

document_2 = Document(page_content="bar", metadata={"source": "https://example.com"})

document_3 = Document(page_content="baz", metadata={"source": "https://example.com"})

documents = [document_1, document_2, document_3]

vector_store.add_documents(documents=documents, ids=["1", "2", "3"])
['1', '2', '3']

更新向量存储中的条目

updated_document = Document(
    page_content="qux", metadata={"source": "https://another-example.com"}
)

vector_store.update_documents(document_id="1", document=updated_document)

从向量存储删除条目

vector_store.delete(ids=["3"])

查询向量存储

向量存储创建完毕并添加相关文档后,您很可能需要在链或代理运行过程中对其进行查询。

直接查询

简单相似度搜索可按如下方式执行:
results = vector_store.similarity_search(
    query="thud", k=1, filter={"source": "https://another-example.com"}
)
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")
* qux [{'text': 'qux', 'id': '1', 'source': 'https://another-example.com'}]
如果您希望执行相似度搜索并获取对应分数,可以运行:
results = vector_store.similarity_search_with_score(query="bar")
for doc, score in results:
    print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
* [SIM=0.000001] bar [{'text': 'bar', 'id': '2', 'source': 'https://example.com'}]

转换为检索器后查询

您也可以将向量存储转换为检索器,以便在链中更方便地使用。
retriever = vector_store.as_retriever(search_type="mmr", search_kwargs={"k": 1})
retriever.invoke("thud")
[Document(metadata={'text': 'qux', 'id': '1', 'source': 'https://another-example.com'}, page_content='qux')]

API 参考

有关所有 FalkorDBVector 功能和配置的详细文档,请前往 API 参考:python.langchain.com/api_reference/community/vectorstores/langchain_community.vectorstores.falkordb_vector.FalkorDBVector.html