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

TiDB Cloud 是一套全面的数据库即服务(DBaaS)解决方案,提供专用和 Serverless 两种选项。TiDB Serverless 现在将内置向量搜索集成到 MySQL 生态中。借助这一增强功能,你可以使用 TiDB Serverless 无缝开发 AI 应用,而无需新的数据库或额外的技术栈。创建一个免费的 TiDB Serverless 集群,并在 https://pingcap.com/ai 开始使用向量搜索功能。

本 notebook 提供在 LlamaIndex 中使用 TiDB 向量搜索的详细指南。

设置环境

%pip install llama-index-vector-stores-tidbvector
%pip install llama-index
import textwrap

from llama_index.core import SimpleDirectoryReader, StorageContext
from llama_index.core import VectorStoreIndex
from llama_index.vector_stores.tidbvector import TiDBVectorStore

配置你的 OpenAI 密钥

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass("Input your OpenAI API key:")

配置你需要的 TiDB 连接设置。要连接到 TiDB Cloud 集群,请按照以下步骤操作:

  • 前往 TiDB Cloud 集群控制台,并导航到 Connect 页面。
  • 选择使用 SQLAlchemy 和 PyMySQL 进行连接的选项,并复制提供的连接 URL(不含密码)。
  • 将连接 URL 粘贴到你的代码中,替换 tidb_connection_string_template 变量。
  • 输入你的密码。
# replace with your tidb connect string from tidb cloud console
tidb_connection_string_template = "mysql+pymysql://<USER>:<PASSWORD>@<HOST>:4000/<DB>?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true"
# type your tidb password
tidb_password = getpass.getpass("Input your TiDB password:")
tidb_connection_url = tidb_connection_string_template.replace(
    "<PASSWORD>", tidb_password
)

准备用于演示的数据

!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'
documents = SimpleDirectoryReader("./data/paul_graham").load_data()
print("Document ID:", documents[0].doc_id)
for index, document in enumerate(documents):
    document.metadata = {"book": "paul_graham"}
Document ID: 86e12675-2e9a-4097-847c-8b981dd41806

创建 TiDB 向量存储

下面的代码片段在 TiDB 中创建一个名为 VECTOR_TABLE_NAME 的表,并针对向量搜索进行了优化。此代码成功执行后,你将能够直接在 TiDB 数据库环境中查看和访问 VECTOR_TABLE_NAME 表

VECTOR_TABLE_NAME = "paul_graham_test"
tidbvec = TiDBVectorStore(
    connection_string=tidb_connection_url,
    table_name=VECTOR_TABLE_NAME,
    distance_strategy="cosine",
    vector_dimension=1536,
    drop_existing_table=False,
)

基于 TiDB 向量存储创建查询引擎

storage_context = StorageContext.from_defaults(vector_store=tidbvec)
index = VectorStoreIndex.from_documents(
    documents, storage_context=storage_context, show_progress=True
)

注意:如果你在此过程中由于 MySQL 协议的数据包大小限制而遇到错误,例如尝试插入大量向量(如 2000 行)时,可以通过将插入拆分为更小的批次来缓解此问题。例如,你可以将 insert_batch_size 参数设置为较小的值(如 1000),以避免超过数据包大小限制,确保数据顺利插入 TiDB 向量存储:

storage_context = StorageContext.from_defaults(vector_store=tidbvec)
index = VectorStoreIndex.from_documents(
    documents, storage_context=storage_context, insert_batch_size=1000, show_progress=True
)

语义相似度搜索

本节重点介绍向量搜索基础以及使用元数据过滤器优化结果。请注意,TiDB 向量仅支持 Default VectorStoreQueryMode。

query_engine = index.as_query_engine()
response = query_engine.query("What did the author do?")
print(textwrap.fill(str(response), 100))
The author wrote a book.

使用元数据过滤

使用元数据过滤器执行搜索,以检索符合所应用过滤器的指定数量的最近邻结果。

from llama_index.core.vector_stores.types import (
    MetadataFilter,
    MetadataFilters,
)

query_engine = index.as_query_engine(
    filters=MetadataFilters(
        filters=[
            MetadataFilter(key="book", value="paul_graham", operator="!="),
        ]
    ),
    similarity_top_k=2,
)
response = query_engine.query("What did the author learn?")
print(textwrap.fill(str(response), 100))
Empty Response

再次查询

from llama_index.core.vector_stores.types import (
    MetadataFilter,
    MetadataFilters,
)

query_engine = index.as_query_engine(
    filters=MetadataFilters(
        filters=[
            MetadataFilter(key="book", value="paul_graham", operator="=="),
        ]
    ),
    similarity_top_k=2,
)
response = query_engine.query("What did the author learn?")
print(textwrap.fill(str(response), 100))
The author learned valuable lessons from his experiences.

删除文档

tidbvec.delete(documents[0].doc_id)

检查文档是否已被删除

query_engine = index.as_query_engine()
response = query_engine.query("What did the author learn?")
print(textwrap.fill(str(response), 100))
Empty Response

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