百度向量数据库
百度向量数据库是一款由百度智能云精心开发并全面管理的强大企业级分布式数据库服务。其卓越之处在于能够高效存储、检索和分析多维向量数据。该数据库核心采用百度自研的"Mochow"向量数据库内核,确保高性能、高可用性和高安全性,同时具备出色的可扩展性和用户友好性。
该数据库服务支持多种索引类型和相似度计算方法,适用于各种使用场景。VectorDB的一个突出特点是其能够管理高达100亿的庞大向量规模,同时保持出色的查询性能,支持每秒数百万次查询(QPS)且具有毫秒级查询延迟。
本笔记本展示了在LlamaIndex中使用BaiduVectorDB作为向量存储的基本用法。
要运行,您应该有一个数据库实例。
如果您在 Colab 上打开这个笔记本,您可能需要安装 LlamaIndex 🦙。
%pip install llama-index-vector-stores-baiduvectordb!pip install llama-index!pip install pymochowfrom llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext,)from llama_index.vector_stores.baiduvectordb import ( BaiduVectorDB, TableParams, TableField,)import pymochow请提供OpenAI访问密钥
Section titled “Please provide OpenAI access key”为了使用OpenAI的嵌入功能,您需要提供一个OpenAI API密钥:
import openai
OPENAI_API_KEY = getpass.getpass("OpenAI API Key:")openai.api_key = OPENAI_API_KEY!mkdir -p 'data/paul_graham/'!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'你现在将从本地文件加载一些保罗·格雷厄姆的文章,并将它们存储到百度向量数据库中。
# load documentsdocuments = SimpleDirectoryReader("./data/paul_graham").load_data()print(f"Total documents: {len(documents)}")print(f"First document, id: {documents[0].doc_id}")print(f"First document, hash: {documents[0].hash}")print( f"First document, text ({len(documents[0].text)} characters):\n{'='*20}\n{documents[0].text[:360]} ...")如果向量存储尚不存在,创建向量存储需要创建底层数据库集合:
vector_store = BaiduVectorDB( endpoint="http://192.168.X.X", api_key="*******", table_params=TableParams(dimension=1536, drop_exists=True),)现在将这个商店包装成一个 index LlamaIndex 抽象,以便后续查询:
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents( documents, storage_context=storage_context)请注意,上述 from_documents 调用同时执行了多项操作:将输入文档分割成可管理大小的块(“节点”),为每个节点计算嵌入向量,并将它们全部存储在百度向量数据库中。
query_engine = index.as_query_engine()response = query_engine.query("Why did the author choose to work on AI?")print(response)MMR(最大边际相关性)方法旨在从存储中获取与查询同时相关但彼此尽可能不同的文本片段,目的是为构建最终答案提供更广泛的上下文:
query_engine = index.as_query_engine(vector_store_query_mode="mmr")response = query_engine.query("Why did the author choose to work on AI?")print(response)由于该存储库由百度向量数据库支持,因此本质上是持久化的。所以,如果您想连接到之前创建并填充的存储库,方法如下:
vector_store = BaiduVectorDB( endpoint="http://192.168.X.X", api_key="*******", table_params=TableParams(dimension=1536, drop_exists=False),)
# Create index (from preexisting stored vectors)new_index_instance = VectorStoreIndex.from_vector_store( vector_store=new_vector_store)
# now you can do querying, etc:query_engine = index.as_query_engine(similarity_top_k=5)response = query_engine.query( "What did the author study prior to working on AI?")print(response)Baidu VectorDB向量存储支持在查询时以精确匹配的key=value键值对形式进行元数据过滤。以下单元(基于全新集合)展示了此功能。
在本演示中,为简洁起见,我们加载了一个源文档(即 ../data/paul_graham/paul_graham_essay.txt 文本文件)。尽管如此,您将为该文档附加一些自定义元数据,以说明如何通过文档附加的元数据条件来限制查询。
filter_fields = [ TableField(name="source_type"),]
md_storage_context = StorageContext.from_defaults( vector_store=BaiduVectorDB( endpoint="http://192.168.X.X", api_key="="*******",", table_params=TableParams( dimension=1536, drop_exists=True, filter_fields=filter_fields ), ))
def my_file_metadata(file_name: str): """Depending on the input file name, associate a different metadata.""" if "essay" in file_name: source_type = "essay" elif "dinosaur" in file_name: # this (unfortunately) will not happen in this demo source_type = "dinos" else: source_type = "other" return {"source_type": source_type}
# Load documents and build indexmd_documents = SimpleDirectoryReader( "../data/paul_graham", file_metadata=my_file_metadata).load_data()md_index = VectorStoreIndex.from_documents( md_documents, storage_context=md_storage_context)from llama_index.core.vector_stores import MetadataFilter, MetadataFiltersmd_query_engine = md_index.as_query_engine( filters=MetadataFilters( filters=[MetadataFilter(key="source_type", value="essay")] ))md_response = md_query_engine.query( "How long it took the author to write his thesis?")print(md_response.response)