Home Database Mysql Tutorial Parallel Query for MySQL with Shard-Query_MySQL

Parallel Query for MySQL with Shard-Query_MySQL

Jun 01, 2016 pm 01:16 PM

While Shard-Query can work over multiple nodes, this blog post focuses on using Shard-Query with a single node.  Shard-Query can add parallelism to queries which use partitionedtables.  Very large tables can often be partitioned fairly easily. Shard-Query can leverage partitioning to add paralellism, because each partition can be queried independently. Because MySQL 5.6 supports the partition hint, Shard-Query can add parallelism to any partitioning method (even subpartioning) on 5.6 but it is limited to RANGE/LIST partitioning methods on early versions.

The output from Shard-Query is from the commandline client, but you can use MySQL proxy to communicate with Shard-Query too.

In the examples I am going to use the schema from the Star Schema Benchmark.  I generated data for scale factor 10, which means about 6GB of data in the largest table. I am going to show a few different queries, and explain how Shard-Query executes them in parallel.

Here is the DDL for the lineorder table, which I will use for the demo queries:

CREATE TABLE IF NOT EXISTS lineorder( LO_OrderKey bigint not null, LO_LineNumber tinyint not null, LO_CustKey int not null, LO_PartKey int not null, LO_SuppKey int not null, LO_OrderDateKey int not null, LO_OrderPriority varchar(15), LO_ShipPriority char(1), LO_Quantity tinyint, LO_ExtendedPrice decimal, LO_OrdTotalPrice decimal, LO_Discount decimal, LO_Revenue decimal, LO_SupplyCost decimal, LO_Tax tinyint, LO_CommitDateKey int not null, LO_ShipMode varchar(10), primary key(LO_OrderDateKey,LO_PartKey,LO_SuppKey,LO_Custkey,LO_OrderKey,LO_LineNumber)) PARTITION BY HASH(LO_OrderDateKey) PARTITIONS 8;
Copy after login

CREATETABLEIFNOTEXISTSlineorder

(

LO_OrderKeybigintnotnull,

LO_LineNumbertinyintnotnull,

LO_CustKeyintnotnull,

LO_PartKeyintnotnull,

LO_SuppKeyintnotnull,

LO_OrderDateKeyintnotnull,

LO_OrderPriorityvarchar(15),

LO_ShipPrioritychar(1),

LO_Quantitytinyint,

LO_ExtendedPricedecimal,

LO_OrdTotalPricedecimal,

LO_Discountdecimal,

LO_Revenuedecimal,

LO_SupplyCostdecimal,

LO_Taxtinyint,

LO_CommitDateKeyintnotnull,

LO_ShipModevarchar(10),

primarykey(LO_OrderDateKey,LO_PartKey,LO_SuppKey,LO_Custkey,LO_OrderKey,LO_LineNumber)

)PARTITIONBYHASH(LO_OrderDateKey)PARTITIONS8;

Notice that the lineorder table is partitioned by HASH(LO_OrderDateKey) into 8 partitions.  I used 8 partitions and my test box has 4 cores. It does not hurt to have more partitions than cores. A number of partitions that is two or three times the number of cores generally works best because it keeps each partition small, and smaller partitions are faster to scan. If you have a very large table, a larger number of partitions may be acceptable. Shard-Query will submit a query to Gearman for each partition, and the number of Gearman workers controls the parallelism.

The SQL for the first demo is:

SELECT COUNT(DISTINCT LO_OrderDateKey) FROM lineorder;
Copy after login

SELECTCOUNT(DISTINCTLO_OrderDateKey)FROMlineorder;

Here is the explain from regular MySQL:

mysql> explain select count(distinct LO_OrderDateKey) from lineorder/G*************************** 1. row *************************** id: 1select_type: SIMPLEtable: lineorder type: indexpossible_keys: PRIMARYkey: PRIMARYkey_len: 25ref: NULL rows: 58922188Extra: Using index1 row in set (0.00 sec)
Copy after login

mysql>explainselectcount(distinctLO_OrderDateKey)fromlineorder/G

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

          id:1

  select_type:SIMPLE

        table:lineorder

        type:index

possible_keys:PRIMARY

          key:PRIMARY

      key_len:25

          ref:NULL

        rows:58922188

        Extra:Usingindex

1rowinset(0.00sec)

So it is basically a full table scan. It takes a long time:

mysql> select count(distinct LO_OrderDateKey) from lineorder;+---------------------------------+| count(distinct LO_OrderDateKey) |+---------------------------------+|2406 |+---------------------------------+1 row in set (4 min 48.63 sec)
Copy after login

mysql>selectcount(distinctLO_OrderDateKey)fromlineorder;

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

|count(distinctLO_OrderDateKey)|

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

|                            2406|

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

1rowinset(4min48.63sec)

Shard-Query executes this query differently from MySQL. It sends a query to each partition, in parallel like the following queries:

Array([0] => SELECT LO_OrderDateKey AS expr_2839651562FROM lineorderPARTITION(p0)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey[1] => SELECT LO_OrderDateKey AS expr_2839651562FROM lineorderPARTITION(p1)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey[2] => SELECT LO_OrderDateKey AS expr_2839651562FROM lineorderPARTITION(p2)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey[3] => SELECT LO_OrderDateKey AS expr_2839651562FROM lineorderPARTITION(p3)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey[4] => SELECT LO_OrderDateKey AS expr_2839651562FROM lineorderPARTITION(p4)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey[5] => SELECT LO_OrderDateKey AS expr_2839651562FROM lineorderPARTITION(p5)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey[6] => SELECT LO_OrderDateKey AS expr_2839651562FROM lineorderPARTITION(p6)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey[7] => SELECT LO_OrderDateKey AS expr_2839651562FROM lineorderPARTITION(p7)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey)
Copy after login
Array(

    [0]=>SELECTLO_OrderDateKeyASexpr_2839651562

FROMlineorder  PARTITION(p0)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

    [1]=>SELECTLO_OrderDateKeyASexpr_2839651562

FROMlineorder  PARTITION(p1)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

    [2]=>SELECTLO_OrderDateKeyASexpr_2839651562

FROMlineorder  PARTITION(p2)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

    [3]=>SELECTLO_OrderDateKeyASexpr_2839651562

FROMlineorder  PARTITION(p3)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

    [4]=>SELECTLO_OrderDateKeyASexpr_2839651562

FROMlineorder  PARTITION(p4)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

    [5]=>SELECTLO_OrderDateKeyASexpr_2839651562

FROMlineorder  PARTITION(p5)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

    [6]=>SELECTLO_OrderDateKeyASexpr_2839651562

FROMlineorder  PARTITION(p6)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

    [7]=>SELECTLO_OrderDateKeyASexpr_2839651562

FROMlineorder  PARTITION(p7)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

)

You will notice that there is one query for each partition.  Those queries will be sent to Gearman and executed in parallel by as many Gearman workers as possible (in this case 4.)  The output of the queries go into a coordinator table, and then another query does a final aggregation.  That query looks like this:

SELECT COUNT(distinct expr_2839651562) AS `count`FROM `aggregation_tmp_73522490`
Copy after login

SELECTCOUNT(distinctexpr_2839651562)AS`count`

FROM`aggregation_tmp_73522490`

The Shard-Query time:

select count(distinct LO_OrderDateKey) from lineorder;Array([count ] => 2406)1 rows returnedExec time: 0.10923719406128
Copy after login

selectcount(distinctLO_OrderDateKey)fromlineorder;

Array(

    [count]=>2406

)1rowsreturned

Exectime:0.10923719406128

That isn’t a typo, it really issub-secondcompared tominutesin regular MySQL.

This is because Shard-Query usesGROUP BYto answer this query and a loose index scanof the PRIMARY KEY is possible:

mysql> explain partitions SELECT LO_OrderDateKey AS expr_2839651562-> FROM lineorderPARTITION(p7)AS `lineorder` WHERE 1=1AND 1=1GROUP BY LO_OrderDateKey-> /G*************************** 1. row *************************** id: 1select_type: SIMPLEtable: lineorder partitions: p7 type: rangepossible_keys: PRIMARYkey: PRIMARYkey_len: 4ref: NULL rows: 80108Extra: Using index for group-by1 row in set (0.00 sec)
Copy after login

mysql>explainpartitionsSELECTLO_OrderDateKeyASexpr_2839651562

    ->FROMlineorder  PARTITION(p7)  AS`lineorder`  WHERE1=1  AND1=1  GROUPBYLO_OrderDateKey

    ->/G

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

          id:1

  select_type:SIMPLE

        table:lineorder

  partitions:p7

        type:range

possible_keys:PRIMARY

          key:PRIMARY

      key_len:4

          ref:NULL

        rows:80108

        Extra:Usingindexforgroup-by

1rowinset(0.00sec)

Next another simple query will be tested, first on regular MySQL:

mysql> select count(*) from lineorder;+----------+| count(*) |+----------+| 59986052 |+----------+1 row in set (4 min 8.70 sec)
Copy after login

mysql>selectcount(*)fromlineorder;

+----------+|count(*)|+----------+|59986052|+----------+

1rowinset(4min8.70sec)

Again, the EXPLAIN shows a full table scan:

mysql> explain select count(*) from lineorder/G*************************** 1. row *************************** id: 1select_type: SIMPLEtable: lineorder type: indexpossible_keys: NULLkey: PRIMARYkey_len: 25ref: NULL rows: 58922188Extra: Using index1 row in set (0.00 sec)
Copy after login

mysql>explainselectcount(*)fromlineorder/G

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

          id:1

  select_type:SIMPLE

        table:lineorder

        type:index

possible_keys:NULL

          key:PRIMARY

      key_len:25

          ref:NULL

        rows:58922188

        Extra:Usingindex

1rowinset(0.00sec)

Now, Shard-Query can’t do anything special to speed up this query, except to execute it in parallel, similar to the first query:

[0] => SELECT COUNT(*) AS expr_3190753946FROM lineorder PARTITION(p0) AS `lineorder` WHERE 1=1 AND 1=1[1] => SELECT COUNT(*) AS expr_3190753946FROM lineorder PARTITION(p1) AS `lineorder` WHERE 1=1 AND 1=1[2] => SELECT COUNT(*) AS expr_3190753946FROM lineorder PARTITION(p2) AS `lineorder` WHERE 1=1 AND 1=1[3] => SELECT COUNT(*) AS expr_3190753946FROM lineorder PARTITION(p3) AS `lineorder` WHERE 1=1 AND 1=1...
Copy after login

[0]=>SELECTCOUNT(*)ASexpr_3190753946

FROMlineorderPARTITION(p0)AS`lineorder`WHERE1=1AND1=1

[1]=>SELECTCOUNT(*)ASexpr_3190753946

FROMlineorderPARTITION(p1)AS`lineorder`WHERE1=1AND1=1

[2]=>SELECTCOUNT(*)ASexpr_3190753946

FROMlineorderPARTITION(p2)AS`lineorder`WHERE1=1AND1=1

[3]=>SELECTCOUNT(*)ASexpr_3190753946

FROMlineorderPARTITION(p3)AS`lineorder`WHERE1=1AND1=1

...

The aggregation SQL is similar, but this time the aggregate function is changed to SUM to combine the COUNT from each partition:

SELECT SUM(expr_3190753946) AS ` count `FROM `aggregation_tmp_51969525`
Copy after login

SELECTSUM(expr_3190753946)AS`count`

FROM`aggregation_tmp_51969525`

And the query is quite a bit faster at 140.24 second compared with MySQL’s 248.7 second result:

Array([count ] => 59986052)1 rows returnedExec time: 140.24419403076
Copy after login
Array(

[count]=>59986052

)1rowsreturned

Exectime:140.24419403076

Finally, I want to look at a more complex query that uses joins and aggregation.

mysql> explain select d_year, c_nation,sum(lo_revenue - lo_supplycost) as profitfrom lineorderjoin dim_dateon lo_orderdatekey = d_datekeyjoin customeron lo_custkey = c_customerkeyjoin supplieron lo_suppkey = s_suppkeyjoin parton lo_partkey = p_partkeywherec_region = 'AMERICA'and s_region = 'AMERICA'and (p_mfgr = 'MFGR#1'or p_mfgr = 'MFGR#2')group by d_year, c_nationorder by d_year, c_nation;+----+-------------+-----------+--------+---------------+---------+---------+--------------------------+------+---------------------------------+| id | select_type | table | type | possible_keys | key | key_len | ref| rows | Extra |+----+-------------+-----------+--------+---------------+---------+---------+--------------------------+------+---------------------------------+|1 | SIMPLE| dim_date| ALL| PRIMARY | NULL| NULL| NULL |5 | Using temporary; Using filesort ||1 | SIMPLE| lineorder | ref| PRIMARY | PRIMARY | 4 | ssb.dim_date.D_DateKey | 89 | NULL||1 | SIMPLE| supplier| eq_ref | PRIMARY | PRIMARY | 4 | ssb.lineorder.LO_SuppKey |1 | Using where ||1 | SIMPLE| customer| eq_ref | PRIMARY | PRIMARY | 4 | ssb.lineorder.LO_CustKey |1 | Using where ||1 | SIMPLE| part| eq_ref | PRIMARY | PRIMARY | 4 | ssb.lineorder.LO_PartKey |1 | Using where |+----+-------------+-----------+--------+---------------+---------+---------+--------------------------+------+---------------------------------+5 rows in set (0.01 sec)
Copy after login

mysql>explainselectd_year,c_nation,  sum(lo_revenue-lo_supplycost)asprofit  fromlineorder  

joindim_date  onlo_orderdatekey=d_datekey  

joincustomer  onlo_custkey=c_customerkey  

joinsupplier  onlo_suppkey=s_suppkey  

joinpart  onlo_partkey=p_partkey  

where  c_region='AMERICA'  ands_region='AMERICA'  

and(p_mfgr='MFGR#1'  orp_mfgr='MFGR#2')  

groupbyd_year,c_nation  orderbyd_year,c_nation;

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

|id|select_type|table    |type  |possible_keys|key    |key_len|ref                      |rows|Extra                          |

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

|  1|SIMPLE      |dim_date  |ALL    |PRIMARY      |NULL    |NULL    |NULL                    |    5|Usingtemporary;Usingfilesort|

|  1|SIMPLE      |lineorder|ref    |PRIMARY      |PRIMARY|4      |ssb.dim_date.D_DateKey  |  89|NULL                            |

|  1|SIMPLE      |supplier  |eq_ref|PRIMARY      |PRIMARY|4      |ssb.lineorder.LO_SuppKey|    1|Usingwhere                    |

|  1|SIMPLE      |customer  |eq_ref|PRIMARY      |PRIMARY|4      |ssb.lineorder.LO_CustKey|    1|Usingwhere                    |

|  1|SIMPLE      |part      |eq_ref|PRIMARY      |PRIMARY|4      |ssb.lineorder.LO_PartKey|    1|Usingwhere                    |

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

5rowsinset(0.01sec)

Here is the query on regular MySQL:

mysql> select d_year, c_nation,sum(lo_revenue - lo_supplycost) as profitfrom lineorderjoin dim_dateon lo_orderdatekey = d_datekeyjoin customeron lo_custkey = c_customerkeyjoin supplieron lo_suppkey = s_suppkeyjoin parton lo_partkey = p_partkeywherec_region = 'AMERICA'and s_region = 'AMERICA'and (p_mfgr = 'MFGR#1'or p_mfgr = 'MFGR#2')group by d_year, c_nationorder by d_year, c_nation;+--------+---------------+--------------+| d_year | c_nation| profit |+--------+---------------+--------------+| 1992 | ARGENTINA | 102741829748 |...| 1998 | UNITED STATES |61345891337 |+--------+---------------+--------------+35 rows in set (11 min 56.79 sec)
Copy after login

mysql>selectd_year,c_nation,  sum(lo_revenue-lo_supplycost)asprofit  fromlineorder  joindim_date  onlo_orderdatekey=d_datekey  joincustomer  onlo_custkey=c_customerkey  joinsupplier  onlo_suppkey=s_suppkey  joinpart  onlo_partkey=p_partkey  where  c_region='AMERICA'  ands_region='AMERICA'  and(p_mfgr='MFGR#1'  orp_mfgr='MFGR#2')  groupbyd_year,c_nation  orderbyd_year,c_nation;

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

|d_year|c_nation      |profit      |

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

|  1992|ARGENTINA    |102741829748|

...

|  1998|UNITEDSTATES|  61345891337|

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

35rowsinset(11min56.79sec)

Again, Shard-Query splits up the query to run over each partition (I won’t bore you with the details) and it executes the query faster than MySQL, in 343.3 second compared to ~720:

Array([d_year] => 1998[c_nation] => UNITED STATES[profit] => 61345891337)35 rows returnedExec time: 343.29854893684
Copy after login
Array(

    [d_year]=>1998

    [c_nation]=>UNITEDSTATES

    [profit]=>61345891337

)35rowsreturned

Exectime:343.29854893684

I hope you see how using Shard-Query can speed up queries without using sharding, on just a single server. All you really need to do is add partitioning.

You can get Shard-Query from GitHub at http://github.com/greenlion/swanhart-tools

Please note: Configure and install Shard-Query as normal, but simply use one node and set thecolumnoption (the shard column) to “nocolumn” or false, because you are not required to use a shard column if you are not sharding.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Explain the role of InnoDB redo logs and undo logs. Explain the role of InnoDB redo logs and undo logs. Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL: From Small Businesses to Large Enterprises MySQL: From Small Businesses to Large Enterprises Apr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

How does MySQL index cardinality affect query performance? How does MySQL index cardinality affect query performance? Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

MySQL vs. Other Databases: Comparing the Options MySQL vs. Other Databases: Comparing the Options Apr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

See all articles