Summary: Datang telecom encounters slow MySQL access issues

Source: Internet
Author: User

After entering Datang in the summer of 15, the role of OPS was entered into the work. Responsible for database work after.

Take the initiative to apply to the Boss (Fang), responsible for the DBA position. The boss's eyes are questioned, he is responsible for Newawared ORACLE work, then another team in datang years of operation and maintenance and OCP certification.

Boss said: "You can do?" I said, "You put me in charge, I'm sure I can." (At that time young and arrogant, of course, is still very young.) The boss said: "Good afternoon, there is a database access slow, you go with me to solve it?" I: hesitated for 3 seconds, the firm answer: no problem. (because at that time the SQL index still practiced like the fire of the state, or I would not dare to stop it casually.) )

The eldest brother asked again: You tell me, database access slow how to optimize?

I then replied: "From the slow query found, execute the slow SQL statement, parse the statement to do the appropriate index (prefix index, unique index, B-TREE data structure to store data, hash index based on hash table implementation) InnoDB engine does not have a hash index.

Only: Memory engine supports hash pointers.

The NDB cluster engine also supports a unique hash index.


Benefits of indexing

Indexes significantly reduce the amount of data the server needs to scan

Indexes can help the server avoid sorting and staging tables

Indexes can turn random I/O into sequential I/O


Said the above content, the eldest brother did not speak at that time. Because then anxious our team meeting, at the meeting the boss asked us have what to say? I said, I'm in charge of DBA work. He said he would leave the meeting. But I finally succeeded in responsible for the MySQL data work of Newawared. Although the communication with him was only a water fights, it was clear that later I was responsible for MySQL work, he should have agreed.


Today to add a better solution to the problem of large concurrency, big table access slow, today say nothing about the "Partition":

Partition Table

for users: a partitioned table is a separate logical table, but there are multiple physical sub-tables at the bottom.

the code that implements the partition is actually a handle statement for a set of underlying tables ( Handler Object) is encapsulated. Requests to partitioned tables are converted to interface calls to the storage engine through a handle object. Partitioning is a fully encapsulated black box for the SQL layer and transparent to the application, but it is easy to see from the underlying filesystem that each partition table has a table file named with the # split.

how MySQL implements partitioned tables -encapsulation of the underlying tables -means that the index is also defined by the Sub-table of the partition, without a global index.

MySQL uses partitionby words to define each stored data when creating a table. When executing a query, the optimizer filters the partitions defined by the partition definition without the data we need, so that the query does not need to scan all the partitions- just the partition that contains the data that needs to be found.

purpose of partitioning: The data is in different tables according to a coarse granularity. It can be convenient to put the relevant data together and to delete the entire partition at once.

In the following scenarios, partitioning has a very large effect:

The table is so large that it cannot be put all in memory, or only the last part of the table has hot data, and the others are historical data.

Bulk deletion of large amounts of data can erase the entire partitioning method. An independent partition can be optimized, inspected, repaired, and so on.

partitioned table data can be distributed across different physical devices, making efficient use of multiple hardware devices.

use partitioned tables to avoid certain special bottlenecks. InnoDB Single index mutually exclusive access,ext3 file system InnoDB Lock competition.

backing up and recovering separate partitions works well in very large data set scenarios.

Limitations of partitioned Tables

a table can only have a maximum of one partition.

in MySQL5.1, the partition expression must be an integer, or an expression that returns a certificate. in MySQL5.5 , columns can be used for partitioning in some scenarios

If the partition field has a primary key or a unique indexed column, all primary key columns and unique index columns must be included in the

FOREIGN KEY constraints cannot be used in partitioned tables

each operation will " Open and lock all the underlying tables first " and cannot say that the partitioned table is locked in the full table during processing. The storage engine can implement row-level locks on its own (e.g. InnoDB)

partition Table Type

MySQL supports a variety of partition tables. Most of the partitioning is based on the range. Partition expression Research room column, or it can be an expression that contains columns.

Mysql> CREATE TABLE Seles (

-Order_date DATETIME not NULL

) Engine=innodb PARTITION by RANGE (year (order_date)) (

-PARTITION p_2010 VALUES less THAN (2010),

-PARTITION p_2011 VALUES less THAN (2011),

-PARTITION p_2012 VALUES less THAN (2012),

-PARTITION p_catchall VALUES less THAN MAXVALUE);

Query OK, 0 rows affected (1.16 sec)

A variety of functions can be used in PARTITION partition phrases. However, there is a requirement that the value returned by the expression be a definite integer and cannot be a constant. Here we use the function year (), or you can use any other function. such as to_days ().

MySQL also supports key values, hashes, and list partitioning.

The system passes the child table to reduce the competition for mutually exclusive access to the index. Frequent access, which leads to the competition of mutexes. Using a hash partition can cut the data into multiple slices, greatly reducing the competing relationship of the mutex.

Other partitioning techniques include:

partitioning according to the key values to reduce the InnoDB of the mutex competition.

use the mathematical touch function to partition and then rotation the data into different partitions.

Suppose that the table has an auto-increment primary key column ID, and you want to centralize the closest hotspot data based on time. Then it is necessary to include the timestamp in the primary key, which contradicts the meaning of the primary key itself. In this case, you can also use such a partition expression to achieve the same purpose. Another aspect of the time-range partitioning avoids the problem that when a certain threshold is exceeded, a partition must be added if the time-range partition is used.

How to use partitioned tables

first, the volume of data is huge and cannot be scanned in every query using the full table. Indexes are consumed on space and maintenance, and do not want to use indexes. Even if you really use the index, you will find that the data is not aggregated in the way you want it, there is a lot of fragmentation, resulting in a query of thousands of random I/O, the application is zombie.

Two paths: Let all queries do a sequential scan on the data table, or cache the data tables and indexes in memory.

when the data volume is very large: the B-tree index will not work. Unless the index overrides the query. The cost of index maintenance (disk space,I/O operations) is also very high. Some systems, such as Infobright, completely abandon the B-tree index, selecting some coarse granularity but consuming less to retrieve data, and a small chunk of metadata for the index of large amounts of data.

Partitioning does not require additional data structures to record what each partition has -the partition does not need to pinpoint the location of each piece of data, and no additional data structures are required -so the cost is very low.

To ensure the scalability of large data volumes, the following two strategies are generally available:

full volume scan data, without any index.

You can use a simple partitioning method to store the table, without any indexes, to roughly locate the desired data location based on the rules of the partition. As long as you can use the Where condition to limit the required data to a few partitions, the efficiency is high. The memory is relatively small and the data is quickly squeezed out of memory, so the cache does not work. This strategy is useful when accessing large amounts of data in a normal way.

index data, and isolate hotspots

If the data has obvious hotspots, in addition to this part of the data is rarely accessed other data, you can put this part of the hot spot data in a separate partition, so that the partition of the data can be cached in memory. This allows the query to access only a small partition table, the ability to use the index, and the ability to use the cache efficiently.

What happens when the problem occurs

The above describes two conditions, using partitions.

1 Full-volume scan data, without any index.

2 index data, and isolate hotspots

Queries can filter out many partitions, and the partition itself does not bring many additional costs. It turns out that these two assumptions are problematic in some scenarios. Here are some of the issues you might encounter

NULL value is invalid using partition filtering

Partition column and index column do not match

The cost of choosing a hair is likely to be high.

Open lock all underlying tables can be costly

The cost of maintaining a partition can be high

Restrictions on partitioning

All partitions must use the same storage engine

There are also limitations to the functions and expressions that can be used in a partition function

Some storage engines do not support partitioning

for MyISAM partition table cannot be manipulated using the LOAD INDEX into CACHE

for MyISAM table, you need to open more file descriptors when using partitioned tables.

A partition is a separate table for the storage engine. This allows multiple file descriptors to be used, even if the partition occupies only one table cache count. Even if the appropriate table cache is configured to ensure that the number of file descriptors that can be opened by a single process of the operating system is not exceeded, there is a problem that exceeds the file descriptor limit for partitioned tables.

all the software has bugs, the partitioned tables are introduced in MySQL5.1, and Many of the partitioned tables have been fixed after 5.1.40 and 5.1.50 later . more enhancements have been made in MySQL5.6 , introducing ALTER TABLE EXCHANGE PARTITION.

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/75/8C/wKioL1Y8JRvzdPlOAAE1RYJHjQA554.jpg "title=" 1.png " alt= "Wkiol1y8jrvzdploaae1ryjhjqa554.jpg"/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/75/8F/wKiom1Y8JOShw9xlAADc9i4jPhE865.jpg "title=" 2.png " alt= "Wkiom1y8joshw9xlaadc9i4jphe865.jpg"/>


Query Optimization

The introduction of partitioning brings new ideas to query optimization (and also brings new bugs). The biggest advantage of partitioning: The optimizer can filter some partitions based on partition functions. Depending on the advantages of the weight index, partitioning filtering typically allows queries to scan less data (in some scenarios)

for access to partitioned tables, the The WHERE condition brings in the partitioning column, sometimes even seemingly superfluous, so that the optimizer can filter out the partitions that are not required to be accessed. Without these conditions,MySQL would need to have the corresponding storage engine access all partitions of the table, which could be very slow if the table is very large.

Use EXPLAIN PARTITION can observe if the optimizer performs partition filtering.

mysql> mysql> EXPLAIN Partitionsselect * from Seles\g

1. row***************************

Id:1

Select_type:simple

Table:seles

Partitions:p_2010,p_2011,p_2012,p_catchall

Type:all

Possible_keys:null

Key:null

Key_len:null

Ref:null

Rows:4

Extra:null

1 row in Set (0.00 sec)

we can observe:the change of partitions and the difference of rows.

mysql> EXPLAIN Partitions SELECT * fromseles WHERE order_date > ' 2011-01-01 ' \g

1. row***************************

Id:1

Select_type:simple

Table:seles

Partitions:p_2012,p_catchall

Type:all

Possible_keys:null

Key:null

Key_len:null

Ref:null

Rows:2

Extra:using where

1 row in Set (0.00 sec)

The MySQL Optimizer is already good at filtering partitions. It can convert a range condition into a discrete list of values and filter partitions based on each value in the list. However, the optimizer is not omnipotent, the following query of the WHERE condition theory can filter the partition, the actual is not.

mysql> EXPLAIN Partitions SELECT * fromseles WHERE year (order_date) = \g

1. row***************************

Id:1

Select_type:simple

Table:seles

Partitions:p_2010,p_2011,p_2012,p_catchall

Type:all

Possible_keys:null

Key:null

Key_len:null

Ref:null

Rows:4

Extra:using where

1 row in Set (0.00 sec)

you can see that this statement used a Year () this function.

MySQL can only filter partitions if they are compared using the column itself of the partition function, and cannot filter the partitions based on the value of the expression. Even if an expression is a partition function.

mysql> EXPLAIN Partitions SELECT * fromseles WHERE order_date between ' 2010-01-01 ' and ' 2010-12-31 ' \g

1. row***************************

Id:1

Select_type:simple

Table:seles

partitions:p_2011

This is possible.


The following continues with the index.


is an index the best solution?

Indexing is not always the best tool. The index is valid only if the index helps the storage engine quickly find out that the benefits of a record outweigh the extra work it is calling.

Small table: Full table scan is more efficient.

Medium-to-large tables: indexes are very effective.

Extra-Large tables: The cost of building and using indexes will gradually grow. In this case, you need a technique that can directly distinguish a set of data that a query needs, rather than a record match. For example: partitioning technology.


Maintaining indexes and tables

Even if you create the table with the correct type and add the appropriate index, the work is not finished, and you need to maintain tables and indexes to make sure that they are working correctly. Maintenance tables have three purposes: Find and repair damaged tables, maintain accurate index statistics, and reduce fragmentation.


Locate the damaged table

Corrupted indexes can cause queries to return incorrect results or false primary key conflicts, which can even cause a database crash.

If you encounter some weird problems: for example, the error that should not be sent can be run: Check table to see if the sending table is corrupted. CHECK table usually finds errors in most tables and indexes.

MariaDB [test]> Check table dong;

+-----------+-------+----------+----------+

| Table | Op | Msg_type | Msg_text |

+-----------+-------+----------+----------+

| Test.dong | Check | Status | OK |

+-----------+-------+----------+----------+

You can use the Repair Table command to repair a corrupted table, or you can rebuild the table by using the alter operation without doing anything (no-op), including the storage engine that modifies the table as the current engine.


Reduce fragmentation of indexes and data

B-tree indexes can be fragmented, which reduces the efficiency of queries. Fragmented indexes may be stored on disk in a poorly or unordered manner.

B-tree requires random disk access to navigate to leaf pages, so random access is unavoidable.

Fragmented peso primers for data storage are more complex.

Fragmentation of lines, fragmentation of space;

Misam table: These three types of fragmentation can occur. InnoDB does not appear short-line fragments;

OPTIMIZE table or export to re-organize the data in the import mode.

MyISAM: Eliminates fragmentation by rebuilding indexes with sorting algorithms.

InnoDB: Online "Add and remove Indexes", you can eliminate the fragmentation of indexes by first deleting and re-creating indexes.


How is it reasonable to judge a system-created index?

Response time to analyze the query. Find the queries that consume the longest time or those that bring the most stress to the server. Examine these queries: schema, SQL, and index structures, determine if there are queries that scan too many rows, do a lot of extra sorting or use temporary tables, use random I/O to access the data, or have too many tables to query for operations that are not listed in the index.


This article from the "Clear Sky" blog, declined reprint!

Summary: Datang telecom encounters slow MySQL access issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.