基于DeepSeek构建的openGauss AI智能优化助手:数据库性能提升新利器
基于DeepSeek构建的openGauss AI智能优化助手:数据库性能提升新利器
- 一、项目概述
- 1.1 项目简介
- 1.2 环境说明
- 1.3 项目代码结构
- 二、系统架构剖析
- 2.1 架构图展示
- 2.2 架构详细说明
- 三、系统功能模块解读
- 3.1 功能模块图展示
- 3.2 功能模块详细说明
- 四、系统数据流分析
- 4.1 数据流图展示
- 4.2 数据流详细解释
- 五、核心技术组件工作原理揭秘
- 5.1 工作原理图展示
- 5.2 工作原理详细解释
- 六、关键代码深度解析
- 6.1 OpenGaussOptimizationAgent 类
- 6.2 analyze_execution_plan 方法
- 七、使用说明与系统演示
- 7.1 使用说明
- 7.2 系统演示效果
- 八、代码获取与配置
- 九、注意事项
- 十、总结与展望
在当今数字化时代,数据库的性能和管理效率对于企业和开发者来说至关重要。openGauss
作为华为开源的国产高斯数据库,拥有广泛的应用场景。而基于 DeepSeek
构建的 openGauss AI
智能优化助手 deepseek-opengauss-agent
,则为 openGauss
数据库的优化和管理带来了全新的解决方案。本文将深入介绍这个智能优化助手的各个方面,带你领略其强大的功能和魅力。
一、项目概述
1.1 项目简介
deepseek-opengauss-agent
是基于 deepseek-r1
开发的 openGauss
数据库优化智能助手。它借助大语言模型 deepseek
的能力,结合多种工具,能够对 openGauss
数据库进行 SQL 查询优化、性能诊断、索引建议、参数调优、SQL 执行等操作,帮助用户显著提升数据库的性能和管理效率。
1.2 环境说明
软件 | 配置 |
---|---|
Windows11 | 16GB 内存 & 8GB 显存 ,个人笔记本电脑 |
DeepSeek - r1 | 14b & 32b,基于 ollama 部署的大模型 |
VMWare WorkStation | 16 + 版本,用于创建虚拟机 |
openEuler20.03 LTS | 华为开源的国产欧拉操作系统 |
openGauss5.0.0 | 华为开源的国产高斯数据库 |
Redis | 基于 Key/Value 的内存数据库,用于存储历史对话信息 |
Python3.11.9 | Python 解释器,该版本兼容性较好 |
PyCharm | 社区版,用于编程的 IDE |
1.3 项目代码结构
deepseek-opengauss-agent/
├── LICENSE
├── .gitignore
├── main.py
├── config.py
├── requirements.txt
├── database/
│ ├── __init__.py
│ ├── connector.py
│ └── schema.py
├── data/
│ ├── finance.sql
│ └── school.sql
├── driver/
│ └── openGauss - connector - python - pyog - master.zip
├── agent/
│ ├── __init__.py
│ ├── main_agent.py
│ ├── memory_manager.py
│ └── prompt_templates.py
├── web_ui/
│ ├── assets
│ │ ├── favicon.ico
│ ├── __init__.py
│ └── app.py
└── tools/├── __init__.py├── performance_diagnose.py├── sql_executor.py├── config_tuner.py├── index_advisor.py├── memory_manager.py└── sql_optimizer.py
二、系统架构剖析
2.1 架构图展示
2.2 架构详细说明
- 用户:发起对
openGauss
数据库的操作请求,如 SQL 优化、性能诊断等。 - OpenGaussOptimizationAgent:作为核心组件,接收用户请求,根据请求内容调用相应的工具进行处理。同时,它还负责与
Redis
进行记忆管理,以及调用DeepSeek
模型获取专业的优化建议。 - 工具集:包括
SQL Optimizer
、Performance Diagnoser
、Index Advisor
、Config Tuner
和SQL Executor
,分别负责 SQL 查询优化、性能诊断、索引建议、参数调优和 SQL 执行等具体操作。 - openGauss 数据库:存储和管理数据,工具集对其进行操作并获取反馈信息。
- Redis:用于存储对话历史和相关信息,帮助
Agent
进行上下文感知和记忆管理。 - DeepSeek 模型:为
Agent
提供专业的数据库优化建议和知识支持。
三、系统功能模块解读
3.1 功能模块图展示
3.2 功能模块详细说明
- SQL 查询优化:分析用户提供的 SQL 查询语句,生成执行计划,识别潜在问题,并给出优化建议和优化后的 SQL 语句。
- 性能诊断:对
openGauss
数据库的整体性能进行诊断,识别系统状态、资源瓶颈和慢查询,并提供相应的优化建议。 - 索引建议:根据用户指定的表名,分析现有索引情况,为表提供合适的索引优化建议。
- 参数调优:根据用户提供的工作负载类型(如 OLTP、OLAP 或混合),对数据库的配置参数进行优化,给出当前配置和优化建议。
- SQL 执行:直接执行用户提供的 SQL 语句,并返回执行结果。
四、系统数据流分析
4.1 数据流图展示
4.2 数据流详细解释
- 用户输入:用户向
OpenGaussOptimizationAgent
发送操作请求。 - Agent 处理:
Agent
解析用户意图,根据需求调用相应的工具,并将工具请求发送给工具集。 - 工具操作:工具集对
openGauss
数据库进行操作,获取操作结果。 - 结果反馈:工具将操作结果返回给
Agent
,Agent
对结果进行处理和分析。 - 用户输出:
Agent
将最终处理结果返回给用户。 - 记忆管理:
Agent
在处理过程中,将对话历史和相关信息保存到Redis
中,以便后续使用。同时,也可以从Redis
中读取记忆信息。 - 模型调用:在需要专业知识和建议时,
Agent
调用DeepSeek
模型,获取模型的响应并应用到处理过程中。
五、核心技术组件工作原理揭秘
5.1 工作原理图展示
5.2 工作原理详细解释
- 意图解析:
Intent_Parser
对用户输入进行解析,判断用户的意图是执行 SQL 还是优化 SQL 等。 - 执行或优化:根据解析结果,
Executor
或Optimizer
分别调用相应的工具(如SQL Executor
或SQL Optimizer
)进行处理。 - 数据库操作:工具对
openGauss
数据库进行操作,并将结果反馈给Agent
。 - 结果输出:
Agent
将处理结果返回给用户。 - 记忆管理和模型调用:在整个过程中,
Agent
与Redis
进行记忆管理,同时在需要时调用DeepSeek
模型获取专业建议。
六、关键代码深度解析
6.1 OpenGaussOptimizationAgent 类
class OpenGaussOptimizationAgent:def __init__(self, session_id: str = "default"):# 初始化工具self.sql_optimizer = SQLOptimizer()self.performance_diagnoser = PerformanceDiagnoser()self.index_advisor = IndexAdvisor()self.config_tuner = ConfigTuner()self.sql_executor = SQLExecutor()# 创建工具集self.tools = [Tool(name="SQL Optimizer",func=self.optimize_sql,description="用于优化 SQL 查询语句。输入应该是一个完整的 SQL 查询。输出包含执行计划、问题分析和优化建议。",),# 其他工具...]# 初始化大语言模型self.llm = CustomOllamaLLM(model=DEEPSEEK_MODEL,temperature=0.3,endpoint=OLLAMA_ENDPOINT,)# 创建代理self.agent = create_react_agent(llm=self.llm,tools=self.tools,prompt=open_gauss_prompt_template,)# 初始化记忆管理器self.memory_manager = RedisMemoryManager(session_id)# 创建执行器self.agent_executor = AgentExecutor(agent=self.agent,tools=self.tools,verbose=True,handle_parsing_errors=True,memory=self.memory_manager.get_chat_history(APP_CONFIG["max_chat_history"]),)def run(self, user_input: str) -> str:# 解析用户意图user_intent, sql_query = self._parse_user_intent(user_input)if user_intent == "execute":# 执行 SQLresult = self.execute_sql(sql_query)# 处理执行结果...elif user_intent == "optimize":# 优化 SQLresult = self.optimize_sql(sql_query)# 处理优化结果...else:# 无法明确意图,使用 Agent 处理self.memory_manager.add_message("user", user_input)response = self.agent_executor.invoke({"input": user_input})if "output" in response:self.memory_manager.add_message("assistant", response["output"])return response["output"]return "抱歉,处理您的请求时出现问题。"
代码解释:
__init__
方法:初始化各种工具、大语言模型、代理、记忆管理器和执行器。这些组件协同工作,为用户提供数据库优化服务。run
方法:解析用户意图,根据意图执行相应的操作(执行 SQL、优化 SQL 或使用代理处理),并返回处理结果。如果无法明确用户意图,则使用Agent
进行处理。
6.2 analyze_execution_plan 方法
def analyze_execution_plan(self, plan):# 初始化分析结果analysis = {"issues": [], "cost": 0, "warnings": []}# 尝试解析 JSON 字符串if isinstance(plan, str):try:plan = json.loads(plan)except json.JSONDecodeError as e:analysis["warnings"].append(f"执行计划 JSON 解析失败: {str(e)}")return analysis# 检查 plan 是否是列表if not isinstance(plan, list) or len(plan) == 0:analysis["warnings"].append(f"执行计划格式异常:预期为非空列表,但得到 {type(plan).__name__}")return analysis# 检查第一个元素是否包含 "Plan" 键root_plan = plan[0]if not isinstance(root_plan, dict) or "Plan" not in root_plan:analysis["warnings"].append(f"执行计划格式异常:缺少 'Plan' 键。类型: {type(root_plan).__name__}")return analysis# 提取总代价plan_node = root_plan["Plan"]total_cost = plan_node.get("Total Cost", 0)analysis["cost"] = total_costdef traverse_plan(node):# 检查节点类型并记录问题node_type = node.get("Node Type", "")if "Seq Scan" in node_type:table_name = node.get("Relation Name", "未知表")analysis["issues"].append({"type": "FULL_TABLE_SCAN","table": table_name,"message": f"全表扫描表 {table_name},考虑添加索引"})elif "Sort" in node_type and node.get("Sort Method") == "external":analysis["issues"].append({"type": "EXTERNAL_SORT","message": "外部排序操作,考虑增加 work_mem 参数或优化排序字段"})# 递归处理子节点if "Plans" in node:plans = node["Plans"]if not isinstance(plans, list):analysis["warnings"].append(f"'Plans' 字段类型异常:预期列表,但得到 {type(plans).__name__}")returnfor child in plans:if isinstance(child, dict):traverse_plan(child)else:analysis["warnings"].append(f"子计划格式异常:{type(child).__name__}")# 开始遍历执行计划traverse_plan(plan_node)return analysis
代码解释:
- 该方法用于分析 SQL 查询的执行计划,识别潜在的优化点。
- 首先对执行计划进行格式检查和解析,然后提取总代价。
- 递归遍历执行计划节点,根据节点类型记录潜在的问题,如全表扫描、外部排序等,并给出相应的优化建议。
七、使用说明与系统演示
7.1 使用说明
- 启动服务:运行
main.py
文件。 - 发起请求:通过命令行或其他方式向服务发送操作请求,如 SQL 查询、性能诊断等。
- 查看结果:服务将返回处理结果,包括执行计划、优化建议、性能诊断报告等。
7.2 系统演示效果
-
系统首页:在浏览器中输入
http://localhost:7860
,正常打开如下图所示:
-
执行 SQL 语句效果:在对话框输入如下未经过优化的 SQL 语句(需要在 SQL 语句前添加
执行 sql:
),让系统执行该 SQL 语句:SELECT c.c_id, c.c_name, c.c_phone, b.b_number, b.b_type FROM client c, bank_card b WHERE c.c_id = b.b_c_id;
执行结果如下:
执行sql时,我在程序中添加了一些关键信息日志帮助理解:INFO:root:检测到执行SQL意图... INFO:root:正在执行SQL查询: SELECT c.c_id, c.c_name, c.c_phone,... …… 解析SQL语句(获取语法树信息): {'tables': ['client'], 'columns': [], 'is_read_only': True, 'estimated_cost': 29.62} 生成原始执行计划: [{"Plan": {"Node Type": "Hash Join","Join Type": "Inner",……"Actual Startup Time": 0.091,"Actual Total Time": 0.097,……"Output": ["c.c_id", "c.c_name", "c.c_phone", "b.b_number", "b.b_type"],"Inner Unique": false,"Hash Cond": "(b.b_c_id = c.c_id)","Plans": [……]}]},"Triggers": [],"Total Runtime": 0.238} ] …… 分析执行计划并提取关键信息: {'scan_methods': ['Seq Scan', 'Seq Scan']……]} 优化执行计划(调用优化器): SELECT c.c_id, c.c_name, c.c_phone, b.b_number, b.b_type FROM client c, bank_card b WHERE c.c_id = b.b_c_id; 生成最终物理执行计划: [{"Plan": {"Node Type": "Hash Join","Join Type": "Inner","Startup Cost": 12.93,"Total Cost": 29.62,"Plan Rows": 220,"Plan Width": 514,"Actual Startup Time": 0.113,"Actual Total Time": 0.119,"Actual Rows": 20,"Actual Loops": 1,"Output": ["c.c_id", "c.c_name", "c.c_phone", "b.b_number", "b.b_type"],"Inner Unique": false,"Hash Cond": "(b.b_c_id = c.c_id)","Plans": [{"Node Type": "Seq Scan","Parent Relationship": "Outer","Relation Name": "bank_card","Schema": "public","Alias": "b","Startup Cost": 0.00,"Total Cost": 13.38,"Plan Rows": 338,"Plan Width": 212,"Actual Startup Time": 0.007,"Actual Total Time": 0.009,"Actual Rows": 20,"Actual Loops": 1,"Output": ["b.b_number", "b.b_type", "b.b_c_id"]},……]},"Triggers": [],"Total Runtime": 0.289} ]
-
优化 SQL 语句效果:在对话框输入如下未经过优化的 SQL 语句(需要在 SQL 语句前添加
优化 sql:
),让系统优化该 SQL 语句:SELECT c.c_name, c.c_id_card, p.pro_id, p.pro_status, p.pro_purchase_time FROM client c INNER JOIN property p ON c.c_id = p.pro_c_id WHERE p.pro_status = '可用';
执行结果如下:
优化sql时,我在程序中添加了一些关键信息日志帮助理解:INFO:root:检测到优化SQL意图... INFO:root:正在优化SQL查询: SELECT c.c_name, c.c_id_card, p.pro... [('finance', 'information_schema', 'tables', 'VIEW', None, None, None, None, None, 'NO', 'NO', None)] 成功连接到openGauss数据库! 用户输入: "优化sql:SELECT c.c_name, c.c_id_card, p.pro_id, p.pro_status, p.pro_purchase_time FROM client c INNER JOIN property p ON c.c_id = p.pro_c_id WHERE p.pro_status = '可用';" "[\n {\n \"Plan\": {\n \"Node Type\": \"Hash Join\",\n \"Join Type\": \"Inner\",\n \"Startup Cost\": 17.44,\n \"Total Cost\": 29.24,\n \"Plan Rows\": 2,\n \"Plan Width\": 398,\n \"Actual Startup Time\": 5.640,\n \"Actual Total Time\": 5.649,\n \"Actual Rows\": 3,\n \"Actual Loops\": 1,\n \"Output\": [\"c.c_name\", \"c.c_id_card\", \"p.pro_id\", \"p.pro_status\", \"p.pro_purchase_time\"],\n \"Inner Unique\": false,\n \"Hash Cond\": \"(c.c_id = p.pro_c_id)\",\n \"Plans\": [\n {\n \"Node Type\": \"Seq Scan\",\n \"Parent Relationship\": \"Outer\",\n \"Relation Name\": \"client\",\n \"Schema\": \"public\",\n \"Alias\": \"c\",\n \"Startup Cost\": 0.00,\n \"Total Cost\": 11.30,\n \"Plan Rows\": 130,\n \"Plan Width\": 306,\n \"Actual Startup Time\": 0.006,\n \"Actual Total Time\": 0.009,\n \"Actual Rows\": 30,\n \"Actual Loops\": 1,\n \"Output\": [\"c.c_id\", \"c.c_name\", \"c.c_mail\", \"c.c_id_card\", \"c.c_phone\", \"c.c_password\"]\n },\n {\n \"Node Type\": \"Hash\",\n \"Parent Relationship\": \"Inner\",\n \"Startup Cost\": 17.40,\n \"Total Cost\": 17.40,\n \"Plan Rows\": 3,\n \"Plan Width\": 100,\n \"Actual Startup Time\": 4.667,\n \"Actual Total Time\": 4.667,\n \"Actual Rows\": 3,\n \"Actual Loops\": 1,\n \"Output\": [\"p.pro_id\", \"p.pro_status\", \"p.pro_purchase_time\", \"p.pro_c_id\"],\n \"Hash Buckets\": 32768,\n \"Original Hash Buckets\": 32768,\n \"Hash Batches\": 1,\n \"Original Hash Batches\": 1,\n \"Peak Memory Usage\": 257,\n \"Plans\": [\n {\n \"Node Type\": \"Seq Scan\",\n \"Parent Relationship\": \"Outer\",\n \"Relation Name\": \"property\",\n \"Schema\": \"public\",\n \"Alias\": \"p\",\n \"Startup Cost\": 0.00,\n \"Total Cost\": 17.40,\n \"Plan Rows\": 3,\n \"Plan Width\": 100,\n \"Actual Startup Time\": 4.651,\n \"Actual Total Time\": 4.657,\n \"Actual Rows\": 3,\n \"Actual Loops\": 1,\n \"Output\": [\"p.pro_id\", \"p.pro_status\", \"p.pro_purchase_time\", \"p.pro_c_id\"],\n \"Filter\": \"(p.pro_status = '\u53ef\u7528'::bpchar)\",\n \"Rows Removed by Filter\": 1\n }\n ]\n }\n ]\n },\n \"Triggers\": [\n ],\n \"Total Runtime\": 5.866\n }\n]" {"issues": [{"type": "FULL_TABLE_SCAN","table": "client","message": "\u5168\u8868\u626b\u63cf\u8868 client\uff0c\u8003\u8651\u6dfb\u52a0\u7d22\u5f15"},{"type": "FULL_TABLE_SCAN","table": "property","message": "\u5168\u8868\u626b\u63cf\u8868 property\uff0c\u8003\u8651\u6dfb\u52a0\u7d22\u5f15"}],"cost": 29.24,"warnings": [] } [{"priority": "HIGH","action": "\u5728\u8868 client \u4e0a\u521b\u5efa\u7d22\u5f15","sql": "CREATE INDEX idx_client_optim ON client(relevant_column);"},{"priority": "HIGH","action": "\u5728\u8868 property \u4e0a\u521b\u5efa\u7d22\u5f15","sql": "CREATE INDEX idx_property_optim ON property(relevant_column);"} ]
八、代码获取与配置
-
8.1 代码下载:跳转到下载页面
-
8.2 安装依赖:
pip install -r requirements.txt
-
8.3 配置环境变量:根据实际情况配置
config.py
文件。
九、注意事项
- 请确保
openGauss
数据库正常运行,并且服务可以访问该数据库。 - 请确保
redis
数据库正常运行,并且服务可以访问该数据库。 - 在使用过程中,如果遇到问题,可以查看日志文件获取详细信息。
十、总结与展望
本文详细介绍了基于 DeepSeek
构建的 openGauss AI
智能优化助手的各个方面,包括项目概述、系统架构、功能模块、数据流、核心技术组件工作原理、关键代码、使用说明等。该智能优化助手为 openGauss
数据库的优化和管理提供了强大的支持,能够显著提升数据库的性能和管理效率。未来,随着技术的不断发展,相信这个智能优化助手将会不断完善和升级,为用户带来更多的惊喜。