hive自带的sql查询最终是转化成mapreduce任务进行。
如何转换的呢?
分为如下几步:
1、antlr词法解析器解析SQL成Abstract Syntax Tree即AST树
2、基于AST树解析成若干query block即QB,QB和QBParseInfo其实是hive源码里面的Bean,是SQL解析的关键类
下边是QB的关键几个成员如下:
public class QB { private static final Log LOG = LogFactory.getLog("hive.ql.parse.QB"); private final int numJoins = 0; private final int numGbys = 0; private int numSels = 0; private int numSelDi = 0; private HashMap<String, String> aliasToTabs; private HashMap<String, QBExpr> aliasToSubq; private HashMap<String, Map<String, String>> aliasToProps; private List<String> aliases; private QBParseInfo qbp; private QBMetaData qbm; private QBJoinTree qbjoin; private String id; private boolean isQuery; private boolean isAnalyzeRewrite; private CreateTableDesc tblDesc = null; // table descriptor of the final private CreateTableDesc directoryDesc = null ; private List<Path> encryptedTargetTablePaths; ......
aliasToSubq(表示QB类的aliasToSubq属性)保存子查询的QB对象,aliasToSubq key值是子查询的别名
qbp 即QBParseInfo保存一个基本SQL单元中的给个操作部分的AST Tree结构,
qbm保存每个输入表的元信息,比如表在HDFS上的路径,保存表数据的文件格式等。
下面是QBParseInfo主要成员:
public class QBParseInfo { private final boolean isSubQ; private final String alias; private ASTNode joinExpr; private ASTNode hints; private final HashMap<String, ASTNode> aliasToSrc; /** * insclause-0 -> TOK_TAB ASTNode */ private final HashMap<String, ASTNode> nameToDest; /** * For 'insert into FOO(x,y) select ...' this stores the * insclause-0 -> x,y mapping */ private final Map<String, List<String>> nameToDestSchema; private final HashMap<String, TableSample> nameToSample; private final Map<ASTNode, String> exprToColumnAlias; private final Map<String, ASTNode> destToSelExpr; private final HashMap<String, ASTNode> destToWhereExpr; private final HashMap<String, ASTNode> destToGroupby; private final Set<String> destRollups; private final Set<String> destCubes; private final Set<String> destGroupingSets; private final Map<String, ASTNode> destToHaving; private final HashSet<String> insertIntoTables; ......
QBParseInfo下面的JoinExpr保存TOK_JOIN节点。QB#QBJoinTree是对Join语法树的结构化。
QBParseInfo#nameToDest这个HashMap保存查询单元的输出,key的形式是inclause-i(由于Hive 支持Multi Insert语句,所以可能有多个输出),value是对应的ASTNode节点,即TOK_DESTINATION节点。
类QBParseInfo其余 HashMap属性分别保存输出和各个操作的ASTNode节点的对应关系。
3、通过SemanticAnalyzer分析类把QB解析成Operator操作树
4、优化操作树
5、基于OperatorTree解析成MapReduce任务
其中antlr是一个开源的词法解析器,AST树也不是什么特殊的树,就是普通的树结构。