DashVector
DashVector 是一个全托管的向量数据库服务,支持高维密集和稀疏向量,实时插入和过滤搜索。它设计为自动扩展,并能适应不同的应用需求。
本笔记本展示了如何使用与DashVector
向量数据库相关的功能。
要使用DashVector,您必须拥有一个API密钥。 以下是安装说明。
安装
%pip install --upgrade --quiet langchain-community dashvector dashscope
我们想要使用DashScopeEmbeddings
,因此我们也需要获取Dashscope API密钥。
import getpass
import os
if "DASHVECTOR_API_KEY" not in os.environ:
os.environ["DASHVECTOR_API_KEY"] = getpass.getpass("DashVector API Key:")
if "DASHSCOPE_API_KEY" not in os.environ:
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 Reference: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)