Skip to content
LlamaIndex 文档版本 跟随上游 源快照 ba3cb143 更新于 2026-10-18

百度 VectorDB 是由百度智能云精心开发并全托管的企业级分布式数据库服务,功能强大。它以存储、检索和分析多维向量数据的卓越能力而脱颖而出。VectorDB 的核心运行在百度专有的“Mochow”向量数据库内核上,确保高性能、高可用性和高安全性,同时具备出色的可扩展性和易用性。

该数据库服务支持多种索引类型和相似度计算方法,可满足各种用例。VectorDB 的一个突出特点是能够管理高达 100 亿的庞大向量规模,同时保持出色的查询性能,支持每秒数百万次查询(QPS),查询延迟为毫秒级。

本 notebook 展示 BaiduVectorDB 作为向量存储在 LlamaIndex 中的基本用法。

要运行,你应该有一个数据库实例。

设置

如果你在 Colab 中打开这个 Notebook,可能需要先安装 LlamaIndex 🦙。

%pip install llama-index-vector-stores-baiduvectordb
!pip install llama-index
!pip install pymochow
from llama_index.core import (
    VectorStoreIndex,
    SimpleDirectoryReader,
    StorageContext,
)
from llama_index.vector_stores.baiduvectordb import (
    BaiduVectorDB,
    TableParams,
    TableField,
)
import pymochow

请提供 OpenAI 访问密钥

要使用 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'

创建并填充向量存储

现在,你将加载 Paul Graham 的一些文章(来自本地文件),并将其存储到百度 VectorDB 中。

# load documents
documents = 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]} ..."
)

初始化百度 VectorDB

创建向量存储包括创建底层数据库集合(如果尚不存在):

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 调用会同时完成几件事:将输入文档切分为大小可控的分块(“节点”)、为每个节点计算嵌入向量,并将它们全部存储到百度 VectorDB 中。

查询存储

基本查询

query_engine = index.as_query_engine()
response = query_engine.query("Why did the author choose to work on AI?")
print(response)

基于 MMR 的查询

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)

连接到现有存储

由于此存储由百度 VectorDB 支持,因此从定义上讲它是持久化的。所以,如果你想连接到之前创建并填充的存储,可以这样做:

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)

元数据过滤

百度 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 index
md_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, MetadataFilters
md_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)

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。