
Byted Bytehouse Slow Query
- 2 installs
- 408 repo stars
- Updated August 3, 2026
- volcengine/agentkit-samples
Identifies and analyzes slow queries on ByteHouse, inspects execution plans, tracks query-history trends, and produces optimization suggestions.
About
Detects and analyzes slow queries on a ByteHouse cloud data warehouse, showing execution plans and historical trends. A developer uses it to find and fix slow ByteHouse queries and get optimization advice.
- Surfaces slow queries, execution plans, and query-history trends
- Depends on the bytehouse-mcp skill for ByteHouse access
Byted Bytehouse Slow Query by the numbers
- 2 all-time installs (skills.sh)
- Ranked #741 of 911 Databases skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/volcengine/agentkit-samples --skill byted-bytehouse-slow-queryAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 408 |
| Last updated | August 3, 2026 |
| Repository | volcengine/agentkit-samples ↗ |
What it does
Identifies and analyzes slow queries on ByteHouse, inspects execution plans, tracks query-history trends, and produces optimization suggestions.
Files
ByteHouse 慢查询分析 Skill
🔵 ByteHouse 品牌标识
「ByteHouse」—— 火山引擎云原生数据仓库,极速、稳定、安全、易用
>
本Skill基于ByteHouse MCP Server,提供完整的慢查询分析和性能优化能力
---
描述
ByteHouse慢查询分析和性能优化工具。
当以下情况时使用此 Skill: (1) 需要识别和分析慢查询 (2) 需要查询性能优化建议 (3) 需要查看查询执行计划 (4) 需要分析查询历史趋势 (5) 用户提到"慢查询"、"查询优化"、"性能分析"、"执行计划"
前置条件
- Python 3.8+
- uv (已安装在
/root/.local/bin/uv) - ByteHouse MCP Server Skill - 本skill依赖
bytehouse-mcpskill提供的ByteHouse访问能力
依赖关系
本skill依赖 bytehouse-mcp skill,使用其提供的MCP Server访问ByteHouse。
确保 bytehouse-mcp skill已正确配置并可以正常使用。
📁 文件说明
- SKILL.md - 本文件,技能主文档
- slow_query_analyzer.py - 慢查询分析主程序
- README.md - 快速入门指南
配置信息
ByteHouse连接配置
本skill复用 bytehouse-mcp skill的配置。请确保已在 bytehouse-mcp skill中配置好:
export BYTEHOUSE_HOST="<ByteHouse-host>"
export BYTEHOUSE_PORT="<ByteHouse-port>"
export BYTEHOUSE_USER="<ByteHouse-user>"
export BYTEHOUSE_PASSWORD="<ByteHouse-password>"
export BYTEHOUSE_SECURE="true"
export BYTEHOUSE_VERIFY="true"🎯 功能特性
1. 慢查询识别
- 从query_log表获取慢查询
- 按执行时间排序
- 识别Top N慢查询
- 分析慢查询模式
2. 查询性能分析
- 查询执行时间分布
- 查询类型统计
- 查询频率分析
- 性能趋势分析
3. 执行计划分析
- 获取查询执行计划
- 分析执行计划节点
- 识别性能瓶颈
- 提供优化建议
4. 优化建议生成
- 索引优化建议
- 查询重写建议
- 表引擎建议
- 配置参数调优
🚀 快速开始
方法1: 运行慢查询分析
cd /root/.openclaw/workspace/skills/bytehouse-slow-query
# 先设置环境变量(复用bytehouse-mcp的配置)
export BYTEHOUSE_HOST="<ByteHouse-host>"
export BYTEHOUSE_PORT="<ByteHouse-port>"
export BYTEHOUSE_USER="<ByteHouse-user>"
export BYTEHOUSE_PASSWORD="<ByteHouse-password>"
export BYTEHOUSE_SECURE="true"
export BYTEHOUSE_VERIFY="true"
# 运行慢查询分析
uv run slow_query_analyzer.py分析内容包括:
- Top 20慢查询
- 查询性能统计
- 执行时间分布
- 优化建议生成
输出文件(保存在 `output/` 目录): 1. `slow_queries_{timestamp}.json` - 慢查询列表 2. `query_stats_{timestamp}.json` - 查询统计报告 3. `optimization_suggestions_{timestamp}.json` - 优化建议
💻 慢查询分析维度
时间维度分析
- 按小时: 每小时慢查询数量
- 按天: 每天慢查询趋势
- 按周: 每周慢查询模式
- 按月: 每月慢查询统计
查询类型分析
- SELECT查询: 查询语句分析
- INSERT查询: 写入性能分析
- UPDATE查询: 更新性能分析
- DELETE查询: 删除性能分析
- DDL查询: 建表/改表性能分析
性能指标
- 平均执行时间: 所有查询平均耗时
- P50执行时间: 中位数执行时间
- P95执行时间: 95分位执行时间
- P99执行时间: 99分位执行时间
- 最大执行时间: 最慢查询耗时
---
📊 慢查询报告示例
慢查询列表
{
"analysis_time": "2026-03-12T21:00:00",
"total_queries": 10000,
"slow_queries": 150,
"top_slow_queries": [
{
"query_id": "query-12345",
"query_text": "SELECT * FROM large_table WHERE ...",
"duration_ms": 15000,
"start_time": "2026-03-12T20:55:00",
"read_rows": 1000000,
"read_bytes": 104857600
}
]
}---
📚 更多信息
详细使用说明请参考 bytehouse-mcp skill
--- 最后更新: 2026-03-12
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.ByteHouse 慢查询分析 Skill
🔵 ByteHouse 品牌标识
「ByteHouse」—— 火山引擎云原生数据仓库,极速、稳定、安全、易用
>
本Skill基于ByteHouse MCP Server,提供完整的慢查询分析和性能优化能力
---
📁 文件说明
- SKILL.md - 技能主文档,包含详细使用说明
- slow_query_analyzer.py - 慢查询分析主程序
- README.md - 本文件,快速入门指南
🎯 功能特性
1. 慢查询识别
- 从query_log表获取慢查询
- 按执行时间排序
- 识别Top N慢查询
- 分析慢查询模式
2. 查询性能分析
- 查询执行时间分布
- 查询类型统计
- 查询频率分析
- 性能趋势分析
3. 执行计划分析
- 获取查询执行计划
- 分析执行计划节点
- 识别性能瓶颈
- 提供优化建议
4. 优化建议生成
- 索引优化建议
- 查询重写建议
- 表引擎建议
- 配置参数调优
🚀 快速开始
前置条件
本skill依赖 bytehouse-mcp skill,确保已正确配置:
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 确认bytehouse-mcp可以正常工作
uv run test_mcp_server.py方法1: 运行慢查询分析
cd /root/.openclaw/workspace/skills/bytehouse-slow-query
# 先设置环境变量(复用bytehouse-mcp的配置)
export BYTEHOUSE_HOST="<ByteHouse-host>"
export BYTEHOUSE_PORT="<ByteHouse-port>"
export BYTEHOUSE_USER="<ByteHouse-user>"
export BYTEHOUSE_PASSWORD="<ByteHouse-password>"
export BYTEHOUSE_SECURE="true"
export BYTEHOUSE_VERIFY="true"
# 运行慢查询分析
uv run slow_query_analyzer.py分析内容包括:
- Top 20慢查询
- 查询性能统计
- 执行时间分布
- 优化建议生成
输出文件(保存在 `output/` 目录): 1. `slow_queries_{timestamp}.json` - 慢查询列表 2. `query_stats_{timestamp}.json` - 查询统计报告 3. `optimization_suggestions_{timestamp}.json` - 优化建议
📚 更多信息
详细使用说明请参考 SKILL.md
ByteHouse访问配置请参考 bytehouse-mcp skill
--- 最后更新: 2026-03-12
#!/usr/bin/env python3
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
ByteHouse 慢查询分析工具
分析慢查询、查询性能、优化建议
"""
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
import os
import json
from datetime import datetime, timedelta
from typing import Dict, List, Any
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
def is_cdw_environment():
"""检测是否为CDW环境
根据BYTEHOUSE_HOST判断:
- CDW: tenant-xxxx-cn-shanghai-public.bytehouse.volces.com
- CE: xxxx-public.bytehouse-ce.volces.com
"""
host = os.environ.get('BYTEHOUSE_HOST', '')
return '.bytehouse.volces.com' in host and '.bytehouse-ce.volces.com' not in host
def get_system_table_name(table_name):
"""根据环境返回正确的系统表名
"""
if is_cdw_environment():
table_mapping = {
'query_log': 'bh_system.query_log'
}
return table_mapping.get(table_name, table_name)
else:
return f'system.{table_name}'
async def run_slow_query_analysis():
"""运行慢查询分析"""
print("=" * 80)
print("ByteHouse 慢查询分析工具")
print("=" * 80)
print()
print("⚠️ 请确保已设置以下环境变量:")
print(" - BYTEHOUSE_HOST")
print(" - BYTEHOUSE_PORT")
print(" - BYTEHOUSE_USER")
print(" - BYTEHOUSE_PASSWORD")
print()
# 检测环境类型
env_type = "CDW" if is_cdw_environment() else "CE"
print(f"🔍 检测到环境类型: {env_type}")
print()
# 从环境变量获取配置
env = os.environ.copy()
# MCP Server参数
server_params = StdioServerParameters(
command='/root/.local/bin/uvx',
args=[
'--from',
'git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse',
'mcp_bytehouse',
'-t',
'stdio'
],
env=env
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
print("✅ 连接成功!")
# 分析结果
analysis = {
"analysis_time": datetime.now().isoformat(),
"slow_queries": [],
"query_stats": {},
"optimization_suggestions": []
}
# 1. 查询最近1小时的慢查询
print("\n1️⃣ 查询最近1小时的慢查询...")
try:
query_log_table = get_system_table_name('query_log')
if not query_log_table:
print(" ℹ️ 环境不支持查询日志表")
analysis["slow_queries"] = {
"count": "Not supported",
"top_20": "Not supported in this environment"
}
else:
sql = f"""
SELECT
query_id,
query,
query_duration_ms,
read_rows,
read_bytes,
result_rows,
result_bytes,
exception,
event_time
FROM {query_log_table}
WHERE
type = 'QueryFinish'
AND event_time > now() - interval 1 hour
AND query_duration_ms > 1000
ORDER BY query_duration_ms DESC
LIMIT 20
"""
result = await session.call_tool("run_select_query", {"query": sql})
slow_queries_data = []
for content in result.content:
if content.type == 'text':
slow_queries_data = content.text
# 简单解析,实际项目中需要更完善的解析
analysis["slow_queries"] = {
"count": "parsed_from_result",
"top_20": slow_queries_data
}
print(" ✅ 成功获取慢查询数据")
except Exception as e:
print(f" ⚠️ 获取慢查询失败: {e}")
# 2. 查询统计信息
print("\n2️⃣ 获取查询统计...")
try:
query_log_table = get_system_table_name('query_log')
if not query_log_table:
print(" ℹ️ 环境不支持查询日志表")
analysis["query_stats"] = {
"time_range": "last_1_hour",
"stats": "Not supported in this environment"
}
else:
sql = f"""
SELECT
count(*) as total_queries,
avg(query_duration_ms) as avg_duration_ms,
sum(if(query_duration_ms > 1000, 1, 0)) as slow_query_count,
sum(if(exception != '', 1, 0)) as error_query_count,
sum(read_rows) as total_read_rows,
sum(read_bytes) as total_read_bytes
FROM {query_log_table}
WHERE
type = 'QueryFinish'
AND event_time > now() - interval 1 hour
"""
result = await session.call_tool("run_select_query", {"query": sql})
query_stats_data = []
for content in result.content:
if content.type == 'text':
query_stats_data = content.text
analysis["query_stats"] = {
"time_range": "last_1_hour",
"stats": query_stats_data
}
print(" ✅ 成功获取查询统计")
except Exception as e:
print(f" ⚠️ 获取查询统计失败: {e}")
# 3. 查询类型分布
print("\n3️⃣ 获取查询类型分布...")
try:
query_log_table = get_system_table_name('query_log')
if not query_log_table:
print(" ℹ️ 环境不支持查询日志表")
analysis["query_type_distribution"] = "Not supported in this environment"
else:
sql = f"""
SELECT
substring(query, 1, 20) as query_prefix,
count(*) as query_count,
avg(query_duration_ms) as avg_duration_ms
FROM {query_log_table}
WHERE
type = 'QueryFinish'
AND event_time > now() - interval 1 hour
GROUP BY query_prefix
ORDER BY query_count DESC
LIMIT 10
"""
result = await session.call_tool("run_select_query", {"query": sql})
query_types_data = []
for content in result.content:
if content.type == 'text':
query_types_data = content.text
analysis["query_type_distribution"] = query_types_data
print(" ✅ 成功获取查询类型分布")
except Exception as e:
print(f" ⚠️ 获取查询类型分布失败: {e}")
# 4. 生成优化建议
print("\n4️⃣ 生成优化建议...")
suggestions = []
# 基于慢查询的建议
suggestions.append({
"type": "general",
"priority": "medium",
"title": "监控慢查询",
"description": "建议持续关注慢查询趋势,设置合理的慢查询阈值",
"action": "定期审查slow_query_log,识别性能问题"
})
suggestions.append({
"type": "index",
"priority": "high",
"title": "索引优化",
"description": "检查慢查询的WHERE条件,考虑添加适当的索引",
"action": "使用EXPLAIN分析查询执行计划,识别全表扫描"
})
suggestions.append({
"type": "configuration",
"priority": "medium",
"title": "配置调优",
"description": "检查max_memory_usage、max_threads等配置参数",
"action": "根据查询模式调整ClickHouse配置参数"
})
analysis["optimization_suggestions"] = suggestions
print(f" ✅ 生成了 {len(suggestions)} 条优化建议")
# 保存分析结果
output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "output")
os.makedirs(output_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = os.path.join(output_dir, f"slow_query_analysis_{timestamp}.json")
with open(output_file, "w", encoding="utf-8") as f:
json.dump(analysis, f, ensure_ascii=False, indent=2)
# 打印分析摘要
print("\n" + "=" * 80)
print("📊 慢查询分析摘要")
print("=" * 80)
print(f"\n分析时间: {analysis['analysis_time']}")
print(f"\n优化建议: {len(analysis['optimization_suggestions'])} 条")
print(f"\n前3条建议:")
for i, suggestion in enumerate(analysis['optimization_suggestions'][:3], 1):
print(f" {i}. [{suggestion['priority'].upper()}] {suggestion['title']}")
print(f" {suggestion['description']}")
print(f"\n📁 分析报告已保存到: {output_file}")
print("\n" + "=" * 80)
async def main():
"""主函数"""
try:
await run_slow_query_analysis()
print("\n✅ 慢查询分析完成!")
except Exception as e:
print(f"\n❌ 慢查询分析失败: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
asyncio.run(main())