Analysis of HiveSQL parsing/execution plan Generation Process

Source: Internet
Author: User
I am studying Impala recently. Let's review the Hive SQL Execution Process first. Hive has three user interfaces: cli (Commandlineinterface) binhive or binhive-servicecli command line method (default) hive-serverhive-server2binhive-servicehiveserver or binhive-servicehiveserve

I am studying Impala recently. Let's review the Hive SQL Execution Process first. Hive has three user interfaces: cli (Command line interface) bin/hive or bin/hive-service cli Command line (default) hive-server/hive-server2 bin/hive-service hiveserver or bin/hive-service hiveserve

I am studying Impala recently. Let's review the Hive SQL Execution Process first.

Hive has three user interfaces:

Cli (Command line interface) Bin/hive or bin/hive-service cli Command Line (default)
Hive-server/hive-server2 Bin/hive-service hiveserver or bin/hive-service hiveserver2 Access through JDBC/ODBC and Thrift (Impala borrows hive-metastore in this way)
Hwi (Hive web interface) Bin/hive-service hwi Access through a browser

In hive shell, enter "show tables;" to actually execute:

bin/hadoop jar hive/lib/hive-cli-0.9.0.jar org.apache.hadoop.hive.cli.CliDriver -e 'SHOW TABLES;'

CLI entry function: cli. CliDriver. main ()

Read parameters-> establish SessionState and import configuration-> process the command CliDriver. processFile () in the input file, or parse the command CliDriver. processLine ()-> parse the input CliDriver. processCmd ()

(1) If it is quit or exit, exit

(2) read external files starting with source and execute HiveQL in the file

(3 )! Command to run the Operating System Command (such! Ls to list the file information in the current directory)

(4) list, list jar/file/archive

(5) For other commands, generate and call the corresponding CommandProcessor for processing, and enter CliDriver. processLocalCmd ()

Let's take a look at the CliDriver. processLocalCmd () function:

The set/dfs/add/delete command is handed over to the specified CommandProcessor for processing, and the rest are handed over to org. apache. hadoop. hive. ql. Driver. run () for processing.

Org. apache. hadoop. hive. ql. the Driver class is the starting point of the query. The run () method calls the compile () and execute () functions to complete the query. Therefore, a command query is divided into two phases: compile and execute.

Compile

(1) Use the HiveLexer. java and HiveParser. java classes generated by anlr to convert HiveQL into an abstract syntax tree (AST ).

First, use the anlr tool to compile srcqlsrcjavaorgapachehadoophiveqlparsehive. g into the following files: HiveParser. java ,? Hive. tokens ,? Hive _. g ,? HiveLexer. java

HiveLexer. java and HiveParser. java is a lexical and syntax analysis file, Hive __. g is HiveLexer. the lexical analysis specification corresponding to java, Hive. tokens defines all tokens after lexical analysis.

Then follow the "Driver. compile ()-> ParseDriver. parse (command, ctx)-> HiveParserX. statement ()-> the API in anlr "Call relationship converts the input HiveQL into a syntax tree of the ASTNode type. HiveParserX is a subclass of the HiveParser class generated by anlr.

(2) Use the corresponding SemanticAnalyzer class to convert the AST tree into a Map-reduce task. There are three steps:

A) AST-> operator DAG

B) optimize operator DAG

C) oprator DAG-> Map-reduce task

First, the syntax tree ASTNode generated in the previous step ,? SemanticAnalyzerFactory will generate different SemanticAnalyzer Based on the token type of ASTNode (all these SemanticAnalyzer are inherited from BaseSemanticAnalyzer)

1) ExplainSemanticAnalyzer

2) LoadSemanticAnalyzer

3) ExportSemanticAnalyzer

4) DDLSemanticAnalyzer

5) FunctionSemanticAnalyzer

6) SemanticAnalyzer

Then, call BaseSemanticAnalyzer. analyze ()-> BaseSemanticAnalyzer. analyzeInternal ().

The following uses the most common select * from table type query as an example. The subclass is SemanticAnalyzer. analyzeInternal (). The logic of this function is as follows:

1) doPhase1 (): stores various information involved in SQL statements in QB and keeps them for later use.

2) getMetaData (): obtains metadata information, mainly related to tables and metadata involved in SQL.

3) genPlan (): Generate operator tree/DAG

4) optimize: optimizes operator tree/DAG, such as column pruning. (currently, only rule-based optimize and cost-based optimize can be performed)

5) genMapRedTasks (): Uses operator tree/DAG to generate several mutually dependent MR tasks through certain rules.

Execute

Serialize the task information generated in the Compile phase to plan. xml, start map-reduce, and deserialize plan. xml in configure.

Instance analysis:

Hive has the following table:

Uid

Fruit_name

Count

A

Apple

5

A

Orange

3

A

Apple

2

B

Banana

1

Execute the following query:

SELECT uid, SUM(count) FROM logs GROUP BY uid

You can use the explain command to view the execution plan:

EXPLAIN SELECT uid, SUM(count) FROM logs GROUP BY uid;

According to the hive. g syntax rules, the AST is generated as follows:

ABSTRACT SYNTAX TREE:(  TOK_QUERY  (TOK_FROM (TOK_TABREF (TOK_TABNAME logs)))  (    TOK_INSERT    (TOK_DESTINATION (TOK_DIR TOK_TMP_FILE))    (      TOK_SELECT      (TOK_SELEXPR (TOK_TABLE_OR_COL uid))      (TOK_SELEXPR (TOK_FUNCTION sum (TOK_TABLE_OR_COL count)))    )    (TOK_GROUPBY (TOK_TABLE_OR_COL uid))  ))

The generated execution plan operator tree/DAG is as follows:

Stage dependencies: Stage-1 is a root stage Stage-0 is a root stageSTAGE PLANS: Stage-1 Map Reduce Alias-> Map Operator Tree: logs TableScan // scan the table alias: logs Select Operator // Select the field expressions: expr: uid type: string expr: count type: int outputColumnNames: uid, count Group By Operator // perform aggregation on the map side to reduce the shuffle data volume aggregations: expr: sum (count) // The aggregate function bucketGroup: false keys: expr: uid type: string mode: hash outputColumnNames: _ col0, _ col1 Reduce Output Operator // Output key, value to reduce key expressions: expr: _ col0 type: string sort order: + Map-reduce partition columns: expr: _ col0 type: string tag:-1 value expressions: expr: _ col1 type: bigint Reduce Operator Tree: Group By Operator aggregations: expr: sum (VALUE. _ col0) // aggregate bucketGroup: false keys: expr: KEY. _ col0 type: string mode: mergepartial outputColumnNames: _ col0, _ col1 Select Operator // Select the field expressions: expr: _ col0 type: string expr: _ col1 type: bigint outputColumnNames: _ col0, _ col1 File Output Operator // Output to File compressed: false GlobalTableId: 0 table: input format: org. apache. hadoop. mapred. textInputFormat output format: org. apache. hadoop. hive. ql. io. hiveIgnoreKeyTextOutputFormat Stage: Stage-0 Fetch Operator limit:-1

Hive optimization policy:

1. Remove the column not required in the query

2. When the Where condition is determined, it is filtered in the TableScan stage.

3. Use the Partition information to read only the qualified Partition

4. Map-side join, which is driven by a large table. Small tables are loaded into all mapper memory.

5. Adjust the Join sequence to ensure that the Big Table is used as the driving table.

6. For Group by tables with unbalanced data distribution, to avoid data concentration on a few reducers, the data is divided into two map-reduce stages. In the first stage, the Distinct column is used for shuffle, partial aggregation at the reduce end to reduce the data size, and group-by column aggregation at the second map-reduce stage.

7. Use hash on the map side for partial aggregation to reduce the data processing scale on the reduce side.

References:

Http://fatkun.com/2013/01/hive-group-by.html

Original article address: Hive SQL parsing/execution plan Generation Process Analysis. Thank you for sharing it with the original author.

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.