LlamaIndex如何结合mysql使用,给出示例
时间: 2025-07-11 11:17:23 浏览: 12
<think>我们正在讨论LlamaIndex如何与MySQL数据库集成。根据引用[1],我们知道LlamaIndex提供了DatabaseReader来读取数据库数据。因此,我们需要使用DatabaseReader连接到MySQL,执行SQL查询,并将结果转换为LlamaIndex可以处理的文档格式,然后构建索引。
步骤:
1. 安装必要的依赖:除了llama-index,还需要安装mysql-connector-python(或其他MySQL连接器)。
2. 使用DatabaseReader建立与MySQL的连接,并执行查询。
3. 将查询结果转换为Document对象(每个行或每个表可以作为一个文档)。
4. 构建索引(如VectorStoreIndex)并进行查询。
示例代码结构:
- 导入必要的模块
- 配置数据库连接(使用连接字符串)
- 创建DatabaseReader实例并加载数据
- 构建索引
- 创建查询引擎并执行查询
注意:由于数据库查询可能返回大量数据,我们需要考虑分块或限制查询结果的大小。
下面是一个具体的示例:</think>### LlamaIndex 集成 MySQL 数据库使用指南
通过 `DatabaseReader` 组件,LlamaIndex 可直接连接 MySQL 数据库执行自然语言查询,实现 SQL 生成、数据检索和语义分析的全流程自动化[^1]。以下是完整实现方案:
---
#### 一、环境准备
```bash
# 核心依赖安装
pip install llama-index sqlalchemy mysql-connector-python
```
#### 二、数据库连接与数据加载
```python
from llama_index.core import VectorStoreIndex
from llama_index.readers.database import DatabaseReader
from sqlalchemy import create_engine
# 创建MySQL连接引擎
engine = create_engine("mysql+mysqlconnector://user:password@localhost:3306/mydb")
# 初始化数据库读取器
db_reader = DatabaseReader(engine=engine)
# 加载数据为Document对象
documents = db_reader.load_data(
query="SELECT product_id, description, price FROM products", # 可自定义SQL
max_rows=1000 # 限制加载行数
)
# 构建向量索引
index = VectorStoreIndex.from_documents(documents)
```
#### 三、自然语言查询实现
##### 基础SQL生成
```python
from llama_index.core.query_engine import NLSQLTableQueryEngine
# 创建自然语言SQL引擎
query_engine = NLSQLTableQueryEngine(
sql_database=engine, # 传入数据库连接
tables=["products", "orders"], # 指定可查询表
synthesize_response=True # 自动生成自然语言结果
)
# 自然语言转SQL执行
response = query_engine.query("2023年销售额最高的5个产品是什么?")
print(response.metadata["sql_query"]) # 输出生成的SQL
print(response) # 输出自然语言结果
```
> **输出示例**
> ```sql
> SELECT p.product_name, SUM(o.quantity * o.unit_price) AS total_sales
> FROM orders o JOIN products p ON o.product_id = p.product_id
> WHERE YEAR(o.order_date) = 2023
> GROUP BY p.product_name ORDER BY total_sales DESC LIMIT 5
> ```
> ```
> 2023年销售额前五产品:1. 智能手表(¥1,240,000) 2. 无线耳机...
> ```
##### 复杂联合查询
```python
# 多表关联分析
response = query_engine.query(
"找出北京地区客户购买次数超过3次的产品类别及其平均评分",
table_context={
"products": "包含商品ID、类别、价格",
"orders": "记录客户购买行为",
"reviews": "存储用户评分"
} # 提供表结构说明提升准确性
)
```
#### 四、进阶:RAG 增强分析
```python
from llama_index.core.tools import QueryEngineTool
# 创建SQL工具
sql_tool = QueryEngineTool.from_defaults(
query_engine=query_engine,
name="mysql_analytics",
description="通过自然语言查询MySQL销售数据库"
)
# 构建多引擎智能体
from llama_index.agent.openai import OpenAIAgent
agent = OpenAIAgent.from_tools([sql_tool], verbose=True)
# 执行跨引擎任务
agent.chat(
"对比2022-2023年各季度手机类产品的销售额增长率,"
"并分析用户评论中提到的前三大优缺点"
)
```
---
### 五、性能优化技巧
1. **索引加速**
```python
# 对高频查询字段建立索引
index = VectorStoreIndex.from_documents(
documents,
embed_model="local:BAAI/bge-small-zh", # 本地嵌入模型加速
show_progress=True
)
index.storage_context.persist(persist_dir="./mysql_index") # 持久化索引
```
2. **查询控制**
```python
query_engine = NLSQLTableQueryEngine(
sql_database=engine,
tables=["products"],
max_rows=500, # 限制返回行数
verify_query=True # 执行前验证SQL安全性
)
```
3. **错误处理**
```python
try:
response = query_engine.query("计算每类产品的")
except Exception as e:
# 自动重试简化查询
response = agent.chat(f"简化问题:{str(e)}")
```
> 💡 **生产建议**:结合 `pgvector` 扩展实现混合检索,处理超大规模数据时使用 `LIMIT 1000 OFFSET` 分页加载[^1]。
---
阅读全文
相关推荐













