Python如何识别 MySQL 中的冗余索引
作者:Bing@DBA 发布时间:2024-01-13 13:44:46
标签:python,mysql,冗余索引
前言
最近在搞标准化巡检平台,通过 MySQL 的元数据分析一些潜在的问题。冗余索引也是一个非常重要的巡检目,表中索引过多,会导致表空间占用较大,索引的数量与表的写入速度与索引数成线性关系(微秒级),如果发现有冗余索引,建议立即审核删除。
PS:之前见过一个客户的数据库上面竟然创建 300 多个索引!?当时的想法是 “他们在玩排列组合呢” 表写入非常慢,严重影响性能和表维护的复杂度。
脚本介绍
表结构
下方是演示的表结构:
CREATE TABLE `index_test03` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`create_time` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uqi_name` (`name`),
KEY `idx_name` (`name`),
KEY `idx_name_createtime`(name, create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
MySQL 元数据
MySQL 可以通过 information_schema.STATISTICS
表查询索引信息:
SELECT * from information_schema.STATISTICS where TABLE_SCHEMA = 'test02' and TABLE_NAME = 'index_test03';
TABLE_CATALOG | TABLE_SCHEMA | TABLE_NAME | NON_UNIQUE | INDEX_SCHEMA | INDEX_NAME | SEQ_IN_INDEX | COLUMN_NAME | COLLATION | CARDINALITY | SUB_PART | PACKED | NULLABLE | INDEX_TYPE | COMMENT | INDEX_COMMENT |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
def | test02 | index_test03 | 0 | test02 | PRIMARY | 1 | id | A | 0 | NULL | NULL | BTREE | |||
def | test02 | index_test03 | 0 | test02 | uqi_name | 1 | name | A | 0 | NULL | NULL | BTREE | |||
def | test02 | index_test03 | 1 | test02 | idx_name | 1 | name | A | 0 | NULL | NULL | BTREE | |||
def | test02 | index_test03 | 1 | test02 | idx_name_createtime | 1 | name | A | 0 | NULL | NULL | BTREE | |||
def | test02 | index_test03 | 1 | test02 | idx_name_createtime | 2 | create_time | A | 0 | NULL | NULL | BTREE |
脚本通过获得 STATISTICS 表中的索引信息来分析表中是否存在冗余索引,分析粒度为表级别。
DEMO 演示
需要使用 pandas 模块。
import pandas as pd
df_table_level = pd.read_excel('/Users/cooh/Desktop/STATISTICS.xlsx')
table_indexes = df_table_level['INDEX_NAME'].drop_duplicates().tolist()
_indexes = list()
for index_name in table_indexes:
index_info = {'index_cols': df_table_level[df_table_level['INDEX_NAME'] == index_name]['COLUMN_NAME'].tolist(),
'non_unique': df_table_level[df_table_level['INDEX_NAME'] == index_name]['NON_UNIQUE'].tolist()[0],
'index_name': index_name
}
_indexes.append(index_info)
content = ''
election_dict = {i['index_name']: 0 for i in _indexes}
while len(_indexes) > 0:
choice_index_1 = _indexes.pop(0)
for choice_index_2 in _indexes:
# 对比两个索引字段的个数,使用字段小的进行迭代
min_len = min([len(choice_index_1['index_cols']), len(choice_index_2['index_cols'])])
# 获得相似字段的个数据
similarity_col = 0
for i in range(min_len):
# print(i)
if choice_index_1['index_cols'][i] == choice_index_2['index_cols'][i]:
similarity_col += 1
# 然后进行逻辑判断
if similarity_col == 0:
# print('毫无冗余')
pass
else:
# 两个索引的字段包含内容都相同,说明两个索引完全相同,接下来就需要从中选择一个删除
if len(choice_index_1['index_cols']) == similarity_col and len(
choice_index_2['index_cols']) == similarity_col:
# 等于 0 表示有唯一约束
if choice_index_1['non_unique'] == 1:
content += '索引 {0} 与索引 {1} 重复, '.format(choice_index_2['index_name'], choice_index_1['index_name'])
election_dict[choice_index_1['index_name']] += 1
elif choice_index_2['non_unique'] == 1:
content += '索引 {0} 与索引 {1} 重复, '.format(choice_index_1['index_name'], choice_index_2['index_name'])
election_dict[choice_index_2['index_name']] += 1
else:
content += '索引 {0} 与索引 {1} 重复, '.format(choice_index_2['index_name'], choice_index_1['index_name'])
election_dict[choice_index_1['index_name']] += 1
elif len(choice_index_1['index_cols']) == similarity_col and choice_index_1['non_unique'] != 0:
content += '索引 {0} 与索引 {1} 重复, '.format(choice_index_2['index_name'], choice_index_1['index_name'])
election_dict[choice_index_1['index_name']] += 1
elif len(choice_index_2['index_cols']) == similarity_col and choice_index_1['non_unique'] != 0:
content += '索引 {0} 与索引 {1} 重复, '.format(choice_index_1['index_name'], choice_index_2['index_name'])
election_dict[choice_index_2['index_name']] += 1
redundancy_indexes = list()
for _k_name, _vote in election_dict.items():
if _vote > 0:
redundancy_indexes.append(_k_name)
content += '建议删除索引:{0}'.format(', '.join(redundancy_indexes))
print(content)
输出结果:
索引 uqi_name 与索引 idx_name 重复, 索引 idx_name_createtime 与索引 idx_name 重复, 建议删除索引:idx_name
SQL 查询冗余索引
MySQL 5.7 是可以直接通过 sys 元数据库中的视图来查冗余索引的,但是云上 RDS 用户看不到 sys 库。所以才被迫写这个脚本,因为实例太多了,一个一个看不现实。如果你是自建的 MySQL,就不用费那么大劲了,直接使用下面 SQL 来统计。
select * from sys.schema_redundant_indexes;
后记
删除索引属于高危操作,删除前需要多次 check 后再删除。上面是一个 demo 可以包装成函数,使用 pandas 以表为粒度传入数据,就可以嵌入到程序中。有问题欢迎评论沟通。
来源:https://blog.csdn.net/qq_42768234/article/details/127366182


猜你喜欢
- 使用Python实现Word文档的自动化处理,包括批量生成Word文档、在Word文档中批量进行查找和替换、将Word文档批量转换成PDF等
- 本人 python新手,使用的环境是python2.7,勿喷# -*- coding:utf8 -*-import random
- 什么是词干提取?在语言形态学和信息检索里,词干提取是去除词缀得到词根的过程─—得到单词最一般的写法。对于一个词的形态词根,词干并不需要完全相
- 案例以论坛为例,有个接口返回帖子(posts)信息,然后呢,来了新需求,说需要显示帖子的 author 信息。此时会有两种选择:在 post
- ValueError: The number of FixedLocator locations (9), usually from a c
- OpenCV图像处理一、图像入门1.读取图像使用 cv.imread() 函数读取一张图像,图片应该在工作目录中,或者应该提供完整的图像路径
- 环境 python3.8pycharm2021.2知识点requests >>> pip install req
- print 默认输出是换行的,如果要实现不换行需要在变量末尾加上逗号 ,#!/usr/bin/python # -*- coding: UT
- 将一个 awk 脚本移植到 Python 主要在于代码风格而不是转译。脚本是解决问题的有效方法,而 awk 是编写脚本的出色语言。它特别擅长
- 由于本人使用的是windows 10 操作系统,所以介绍在 windows 10 系统中安装 Anaconda3 的过程。下载Anacond
- NumPy数组是一个多维数组对象,称为ndarray创建一个numpy数组,如下所示import numpy as npx=np.array
- 现在同类型的网站数不胜数,网站的功能或服务日趋同质化,大的方面看不出什么差别,差别就体现在细节上。“窥斑见豹”,细节成为网站最有力的表现形式
- 前言:循环中通过break语句会立刻终止并跳出循环语句。break就像是终止按键,不管执行到哪一步,只要遇到break,不管什么后续步骤,直
- 一、引言Server端的脚本运行环境,它简单易用,不需要编译和连接,脚本可以在 Server端直接运行,并且它支持多用户、多线程,因为 AS
- 如下所示:package mainimport ( "fmt" "os/exec" "ti
- 一、介绍正则表达式是一个特殊的字符序列,计算机科学的一个概念。通常被用来检索、替换那些符合某个模式(规则)的文本。许多程序设计语言都支持利用
- 女朋友是一个软件测试人员,在工作中经常会遇到需要录屏记录自己操作,方便后续开发同学定位。因为录屏软件动不动就开始收费,所以她经常更换录屏软件
- 一、前情提要相信来看这篇深造爬虫文章的同学,大部分已经对爬虫有不错的了解了,也在之前已经写过不少爬虫了,但我猜爬取的数据量都较小,因此没有过
- 版本一conda install xxx:这种方式安装的库都会放在/Users/orion-orion/miniforge3/pkgs目录下
- 本人虽然五音不全,但是听歌还是很喜欢的。希望能利用机器自动制作音乐,本我发现了一个比较适合入门的有趣的开源音乐生成模块 PySynth ,文