Skip to main content
Open In ColabOpen on GitHub

TiDB

TiDB Cloud,是一个全面的数据库即服务(DBaaS)解决方案,提供专用和无服务器选项。TiDB 无服务器现在正在将内置向量搜索引入 MySQL 生态系统中。通过此增强功能,您可以在无需使用新数据库或额外技术栈的情况下无缝开发 AI 应用程序。成为首批体验者之一,参加 https://tidb.cloud/ai 私有测试版的等待名单。

这个笔记本介绍了如何使用TiDBLoader从TiDB加载数据到langchain中。

前置条件

在使用TiDBLoader之前,我们将安装以下依赖项:

%pip install --upgrade --quiet langchain

然后,我们将配置与TiDB的连接。在这个笔记本中,我们将遵循TiDB云提供的标准连接方法来建立一个安全高效的数据库连接。

import getpass

# copy from tidb cloud console,replace it with your own
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"
tidb_password = getpass.getpass("Input your TiDB password:")
tidb_connection_string = tidb_connection_string_template.replace(
"<PASSWORD>", tidb_password
)

加载数据来自TiDB

以下是一些您可以用于自定义TiDBLoader行为的关键参数说明:

  • query (str): 这是将要执行以连接到 TiDB 数据库的 SQL 查询。查询应该选择你想要加载到 Document 对象中的数据。 例如,你可以使用类似于 "SELECT * FROM my_table" 的查询来从 my_table 中获取所有数据。

  • page_content_columns (Optional[List[str]]): 指定应在每个 Document 对象的 page_content 中包含的列名列表。 如果设置为 None(默认值),则查询返回的所有列都会包含在 page_content 中。这允许您根据数据的具体列来定制每个文档的内容。

  • metadata_columns (Optional[List[str]]): 指定应在每个Document对象的metadata中包含的列名列表。 默认情况下,此列表为空,这意味着除非显式指定,否则不会包含任何元数据。这对于包括不影响主要内容但仍然对处理或分析有价值的附加信息非常有用。

from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine

# Connect to the database
engine = create_engine(tidb_connection_string)
metadata = MetaData()
table_name = "test_tidb_loader"

# Create a table
test_table = Table(
table_name,
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(255)),
Column("description", String(255)),
)
metadata.create_all(engine)


with engine.connect() as connection:
transaction = connection.begin()
try:
connection.execute(
test_table.insert(),
[
{"name": "Item 1", "description": "Description of Item 1"},
{"name": "Item 2", "description": "Description of Item 2"},
{"name": "Item 3", "description": "Description of Item 3"},
],
)
transaction.commit()
except:
transaction.rollback()
raise
from langchain_community.document_loaders import TiDBLoader

# Setup TiDBLoader to retrieve data
loader = TiDBLoader(
connection_string=tidb_connection_string,
query=f"SELECT * FROM {table_name};",
page_content_columns=["name", "description"],
metadata_columns=["id"],
)

# Load data
documents = loader.load()

# Display the loaded documents
for doc in documents:
print("-" * 30)
print(f"content: {doc.page_content}\nmetada: {doc.metadata}")
API 参考:TiDB加载器
------------------------------
content: name: Item 1
description: Description of Item 1
metada: {'id': 1}
------------------------------
content: name: Item 2
description: Description of Item 2
metada: {'id': 2}
------------------------------
content: name: Item 3
description: Description of Item 3
metada: {'id': 3}
test_table.drop(bind=engine)