DashVector
DashVector 是一款完全托管的向量数据库服务,支持高维稠密和稀疏向量、实时插入和过滤搜索。它构建为自动扩展,并可以适应不同的应用程序需求。
此笔记本展示了如何使用与DashVector
向量数据库相关的功能。
要使用 DashVector,您必须拥有 API 密钥。以下为安装说明。
安装
%pip install --upgrade --quiet langchain-community dashvector dashscope
我们希望使用DashScopeEmbeddings
,因此我们也必须获取 Dashscope API 密钥。
import getpass
import os
os.environ["DASHVECTOR_API_KEY"] = getpass.getpass("DashVector API Key:")
os.environ["DASHSCOPE_API_KEY"] = getpass.getpass("DashScope API Key:")
示例
from langchain_community.embeddings.dashscope import DashScopeEmbeddings
from langchain_community.vectorstores import DashVector
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.document_loaders import TextLoader
loader = TextLoader("../../how_to/state_of_the_union.txt")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
embeddings = DashScopeEmbeddings()
API 参考:TextLoader
我们可以从文档中创建 DashVector。
dashvector = DashVector.from_documents(docs, embeddings)
query = "What did the president say about Ketanji Brown Jackson"
docs = dashvector.similarity_search(query)
print(docs)
我们可以添加带有元数据和 ID 的文本,并使用元数据过滤器进行搜索。
texts = ["foo", "bar", "baz"]
metadatas = [{"key": i} for i in range(len(texts))]
ids = ["0", "1", "2"]
dashvector.add_texts(texts, metadatas=metadatas, ids=ids)
docs = dashvector.similarity_search("foo", filter="key = 2")
print(docs)
[Document(page_content='baz', metadata={'key': 2})]
操作频段partition
参数
partition
参数默认为 default,如果传入不存在的partition
参数,则会自动创建partition
。
texts = ["foo", "bar", "baz"]
metadatas = [{"key": i} for i in range(len(texts))]
ids = ["0", "1", "2"]
partition = "langchain"
# add texts
dashvector.add_texts(texts, metadatas=metadatas, ids=ids, partition=partition)
# similarity search
query = "What did the president say about Ketanji Brown Jackson"
docs = dashvector.similarity_search(query, partition=partition)
# delete
dashvector.delete(ids=ids, partition=partition)