TiDB 向量存储
TiDB Cloud,是一款全面的数据库即服务(DBaaS)解决方案,提供专用和无服务器两种选项。TiDB Serverless 现正将内置向量搜索功能融入 MySQL 生态。通过此增强功能,您可以使用 TiDB Serverless 无缝开发 AI 应用程序,无需新数据库或额外技术栈。创建免费的 TiDB Serverless 集群,立即在 https://pingcap.com/ai 开始使用向量搜索功能。
本笔记本提供了关于在LlamaIndex中使用tidb向量搜索的详细指南。
%pip install llama-index-vector-stores-tidbvector%pip install llama-indeximport textwrap
from llama_index.core import SimpleDirectoryReader, StorageContextfrom llama_index.core import VectorStoreIndexfrom llama_index.vector_stores.tidbvector import TiDBVectorStore配置您的OpenAI密钥
import getpassimport 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 consoletidb_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 passwordtidb_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 向量存储
Section titled “Create TiDB Vectore Store”以下代码片段在 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向量仅支持默认向量存储查询模式。
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