Hive SQL Execution Process analysis

Source: Internet
Author: User

Transfer from Http://www.tuicool.com/articles/qyUzQj

In the recent study of Impala, let's review the SQL execution process for hive.

There are three types of user interfaces in hive:

CLI (Command line interface) Bin/hive or Bin/hive–service CLI Command line mode (default)
Hive-server/hive-server2 Bin/hive–service Hiveserver or Bin/hive–service hiveserver2 Access via JDBC/ODBC and thrift (Impala borrows hive-metastore this way)
HWI (Hive Web interface) Bin/hive–service Hwi Access via browser

In the Hive shell, enter "show tables;" The actual implementation is:

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-In Parameters--establish sessionstate and import configuration, process input files with instruction Clidriver.processfile (), or interactive instruction Clidriver.processline () Parse Input clidriver.processcmd ()

(1) If Quit or exit, exit

(2) Read the external file and execute the HIVEQL in the file starting with source

(3)! The beginning of the command, executing operating system commands (such as!LS, listing the current directory's file information)

(4) list, listing jar/file/archive

(5) Other commands, generate calls to the corresponding commandprocessor processing, enter Clidriver.processlocalcmd ()

Clidriver.processlocalcmd ()

The set/dfs/add/delete instruction is handed over to the designated Commandprocessor and the remainder to Org.apache.hadoop.hive.ql.Driver.run ()

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

Compile

(1) Convert HIVEQL into an abstract syntax tree (AST) using the Hivelexer.java and Hiveparser.java classes generated by ANTLR.

First, use the ANTLR tool to compile srcqlsrcjavaorgapachehadoophiveqlparsehive.g into the following files: Hiveparser.java, Hive.tokens, HIVE__.G, Hivelexer.java

Hivelexer.java and Hiveparser.java are lexical and parsing class files, HIVE__.G is hivelexer.java corresponding lexical analysis specification, Hive.tokens defines all tokens after lexical analysis.

Then follow the API in "Driver.compile ()->parsedriver.parse (command, CTX)->hiveparserx.statement ()->ANTLR" This call relationship converts the input hiveql into a astnode type syntax tree. Hiveparserx is a subclass of the Hiveparser class generated by ANTLR.

(2) Use the corresponding Semanticanalyzer class to convert the AST tree into a map-reduce task

A) AST-Operator DAG

b) Optimizing the 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 Astnode token type ( 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 is an example of a query of the most common select * from table type, and the subclass entered is Semanticanalyzer. Analyzeinternal (), the logic of this function is as follows:

1) doPhase1 (): Store all the information involved in the SQL statement, save it in the QB, and leave it behind.

2) GetMetaData (): Gets metadata information, primarily the association of tables and metadata involved in SQL

3) Genplan (): Generate operator Tree/dag

4) Optimize: optimization, operator Tree/dag to perform some optimization operations, such as column pruning, etc. (currently can only do rule-based optimize, can not do cost-based optimize)

5) Genmapredtasks (): operator Tree/dag to generate several interdependent Mr Tasks through certain rules

Execute

Serializes the task information generated by the compile phase to Plan.xml, then starts Map-reduce and deserializes plan.xml at configure

Example Analysis:

There is such a table in hive:

Uid

Fruit_name

Count

A

Apple

5

A

Orange

3

A

Apple

2

B

Banana

1

Execute the following query:

SUM (byuid

The execution plan can be viewed through the explain command:

SUM (byuid;

In accordance with the syntax rules of HIVE.G, the resulting AST is 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_groupby (tok_table_ Or_col uid    ))))

The resulting execution plan operator Tree/dag is as follows:

Stage Dependencies:stage-1 is a root stage Stage-0 is a root stagestage plans:stage:stage-1 Map Reduce Alias -> Map Operator tree:logs tablescan//Scan table Alias:logsSelect Operator//Choose field Expressions:expr:uid type:string ExprCount Type:int Outputcolumnnames:uid,CountGroupby Operator//The aggregation is done first on the map side, reducing the amount of shuffle data aggregations:expr:Sumcount)//aggregate function Bucketgroup:False Keys:expr:uid type:string Mode:hash outputcolumnnames: _col0, _col1 ReduceOutput Operator//OutputsKeyValue to reduceKey expressions:expr: _col0 type:string sortOrder: + map-reduce partition columns:expr: _col0 type:string Tag:-1Value expressions:expr: _col1 type:bigint Reduce Operator Tree:group by Operator aggregations:expr: sum (value._col0)//Aggregation Bucketgroup: false keys:expr: key._ Col0 type:string mode:mergepartial outputcolumnnames: _col0, _col1 select Operator//select Field Express ions: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 Strategy:

1. Remove the unwanted column from the query

2. Where condition judgment and so on in the tablescan phase of filtering

3. Use partition information to read only eligible partition

4. Map end join with large table drive, small table loaded into all mapper memory

5. Adjust the join order to ensure that large tables are used as driver tables

6. For table group by when data is unevenly distributed, it is divided into two map-reduce stages to avoid data centralization to a few reducer. The first phase is shuffle with the distinct column and then partially aggregated on the reduce side, reducing the size of the data, and then aggregating the second Map-reduce stage by the group-by column.

7. In the map end with a hash of the partial aggregation, reduce reduce data processing scale.

Reference documents:

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

Hive SQL Execution Process analysis

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.