Hive Learning Note: basic syntax

Source: Internet
Author: User

Hive Basic Syntax

1 , creating tables – User Tables

CREATE [External External Table] TABLE [If not EXISTS exists]Huserinfo (useridintcomment ' User ID ', username string comment ' user name ', userpwd string comment ' user password ', createtime string comment ' creation time ') commen T ' user Information table ' row format delimited fileds terminated by' \ t '--declaring a file line delimiterpartitioned by(DS string Comment'current time, for partitioning fields')--represents what field to split, usually by time. For adding partitionsClustered  byUserid--The fields to sortSorted byUsername into  +Buckets--Bucket (bucket) platoon, the order here means to sort the IDs by name, cluster totals, and then partition into 32 hash buckets. stored asRcfile

Hive currently supports three different ways:

1) is the most common textfile, data do not compress, disk overhead, parsing overhead is also large

2) Squencefile,hadoop API provides a binary API approach, which is easy to use, can be segmented, compressible and other characteristics.

3) rcfile row and column storage combined, it will first block the data, to ensure that the same record on a block, to avoid reading a record need to read multiple blocks. Second, block data columnstore, convenient for data storage and fast column access. Rcfile because of the use of column-type storage, it is expensive to load, but has a good query response, good compression ratio.

Location '/user/hive/test '; -Changing the position of the table in HDFs is not necessarily created first.

Like Old_userinfo--Copy an empty table that allows the user to copy an existing table structure, but does not replicate the data.

2. mysql Date function : Sysdate ()

3. The relationship between ODS and Edw

Edw mainly provides analytical decision service for enterprises. Limitation: t+1

ODS is mainly for enterprise data integration, sharing and quasi-real-time operation monitoring and other functions. Aging: Real Time

ODS is a useful complement and extension of the Edw.

Operating data in the production system through the ETL (extraction, conversion, loading) process into the ODS, the production system between the quasi-real-time exchange of data by ODS system, ODS system at the same time will be integrated production system operating data through ETL and other ways to transfer to the EDW, Complete the process of operating data from the operational environment into the analysis environment.

ODS Effect:

1) The consolidation of operational data and the improvement of operational data quality are a major source of data for Edw.

2) achieve near real-time reporting and query statistics application across the system. ODS collects data from different operational application systems, consolidates shared transaction data from each system, and forms a holistic view of enterprise-class data.

3) as a data synchronization source for other production systems.

4. Introduction to hive partition (partition)

1) in the Hive select query, the entire table content is generally scanned, which consumes a lot of time to do unnecessary work. Sometimes you only need to scan a subset of the data in the table, so the partition concept is introduced when the table is built.

2) A partitioned table refers to the partition space of the partition specified when the table was created.

3) If you need to create a partitioned table, you need to invoke the optional parameter partitioned by when creating the table, as described in the syntax structure of the table creation.

4) A table can have one or more partitions, and each partition exists in a folder as a separate directory under the table folder.

5. Usage scenarios for map-side join and Reduce-side join

1) Map-side Join usage scenario is a large table and a small table of connection operations, where "small table" refers to a file that is small enough to be loaded into memory. The algorithm can execute the join operator on the map side without having to go through the phases of shuffle and reduce, so the efficiency is very high.

2) Reduce-side Join Reduce-side join is a solution when data in two files/directories is very large and it is difficult to store one in memory. The algorithm needs to be completed through the map and reduce two phases, in the map phase, the same key records are divided into the same reduce Task (the source of each record needs to be marked, easy to merge in the reduce phase), in the reduce phase, the same key is merged.

6. Cast type conversion

Select CAST (ad double) from hive;

7, Hive build table: A table can have one or more partitions, each partition in the form of a folder separate table folder directory.

8, Hive's optimization idea:

1) as early as possible to filter data, reduce the amount of data at each stage

2) Reduce job count

3) Solve data skew problem

9. Column cropping: HQL Optimization and Usage tips: Select only the columns that are really needed.

Partition clipping: HQL optimization and usage tips: reduce unnecessary partitioning.

10. Reduce the number of jobs using Hive's optimization mechanism:

HQL Optimization and usage techniques: whether an external association outer join or an internal association inner join, if the join key is the same, no matter how many tables it has, it will be merged into a mapreduce task.

SELECT A.val, B.val, c.valfrom a join B on (a.key= b.key1) JOIN C on (c.key= b.key1), 1 jobs

SELECT A.val, B.val, c.valfrom a join B on (a.key= b.key1) JOIN C on (c.key= B.key2), 2 jobs

11, job input and output optimization:

HQL Optimization and usage skills: Use Muti-insert, union All, the union all of the different tables is equal to multiple inputs, the same table of union all, quite map output more than once.

 insert  overwrite table   TMP1  select  ... from  a where   insert  overwrite  TMP2  select  ... from  a where  condition 2; 
 from a     Insert Table TMP1         Select where Condition 1     Insert Table TMP2         Select where condition 2;

12. Local Model:

Select User Ten ; Select *  from ten; (No MapReduce program is generated)

13, HQL optimization method and use skill: Avoid Cartesian product

14. Data filtering: HQL Optimization and Usage tips: Filter out unwanted data before join

15, small table put before the big table after the principle:

HQL Optimization and usage tips: When writing code statements with join operations, you should place a table/subquery with fewer entries on the left side of the join operator. Because in the reduce phase, the contents of the table on the left side of the join operator are loaded into memory, and a table loaded with fewer entries can effectively reduce the amount of oom (out of memory) that is an overflow. Therefore, for the same key, the corresponding value of a small place before the big put.

16, Mapjoin ():

HQL Optimization and usage techniques: when the small table joins with the big table, the Mapjoin is used, which is done on the map side. You can also avoid data skew from small tables and large table joins.

17. Left SEMI JOIN:

HQL Optimization and usage tips: The left SEMI JOIN is a more efficient implementation of the in/exists subquery, which was not previously supported by version 0.13.

18. Left SEMI JOIN:

HQL optimization methods and usage skills

Restriction: You can only set the filter condition in the ON clause, not in the WHERE clause, SELECT clause, or elsewhere.

The difference between the left semi join and join: If the B table has duplicate values, the left semi join produces one, and the join produces multiple bars.

19, Input and output optimization: Rational use of dynamic partitioning

20. Input/Output optimization:UNION ALL optimization

HQL Optimization and usage techniques: Using Hive's optimization of union ALL (0.13 can be directly union) hive-to-union all optimizations are limited to non-nested queries.

21, Input and output optimization: Reasonable use of UNION ALL

HQL Optimization and usage skills: There are too many different table union all, is not recommended, usually using a temporary partition table, the results of different tables are insert into different partitions (can be parallel), and finally unified processing.

22, Input and output optimization: Rational use of UDTF

HQL Optimization and Usage tips: Select Col1,col2,newcol from Mytablelateral VIEW explode (mycol) Adtableas Newcol

Description: The execution process is equivalent to performing two reads separately, then union to a table, but only one job count.

The same mycol also requires an array type, but for the most part of the day we are getting the type of string after splitting the split function.

23, Input and output optimization: multi-granularity calculation optimization

Hql optimization method and usage skills: Apply UDTF Optimization: Order Summary by different dimensions.

 select  *    ( select  ' 1   " ,province,sum (sales) from Order_ TableGroup by province UNION ALL select ' 2  , City,sum  (sales) from  order_tablegroup by   City  union  all  select  ' 3   " ,county,sum (sales) from Order_ TableGroup by county) DF  

24, Data deduplication and sequencing: DISTINCT and GROUP BY

HQL optimization and use of skills: try to avoid the use of distinct for weight, especially large table operation, with GROUP by instead.

25. Data deduplication and sequencing: sorting optimization

HQL Optimization and usage techniques: only order by results in a global order, and can be sorted according to the actual scene.

1) Order BY to achieve global ordering, a reduce implementation, because it can not be executed concurrently, so the efficiency is low.

2) The Sort by implementation is partially ordered, and the result of a single reduce output is ordered, efficient, and usually used with the distribute by keyword (the Distribute by keyword can specify a map to the reduce-side distribution key)

3) CLUSTER by col1 is equivalent to distribute by col1 sort by col1 but cannot specify a collation.

26. Data tilt:

Hql optimization method and Usage skills: The task progress is maintained at 99% (or 100%) for a long time, viewing the Task monitoring page and discovering that only a small number (one or several) of the reduce subtasks are not completed. Because the amount of data processed and other reduce differences are too large. The number of records in a single reduce differs too much from the average number of records, which can typically reach 3 times times or more. The longest term is longer than the average length.

27. Hive useful new features:

1) The delimiter between the specified columns can be implemented with the following command:

Hive>Insert/home/DD_EDW/documents/result'  '\ t'hive> select * from test;

2) Group BY Syntax enhancement, group by can be used in addition to column alias or column position

Like what:

Select Count (1Group by F1 (col1), F2 (col2), F3 (Col3);

can be written

Select Count (1Groupby123;

3) ALTER VIEW View_nameas select_statement

4) SHOW CREATE TABLE ([db_name.] Table_name|view_name)

5) Explain dependency syntax, get input table and input partition

6) implemented truncate, can delete the data stored in the relevant table above HDFs, but

Maintains the integrity of the table and metadata.

28, hive Build Library use rcfile format, anyway is efficient, Facebook reuse.

29. Java-based framework: database MySQL mongodb redis, persistent layer ibatis, frame SPRINGMVC+SPRING/AUTOFAC,

Performance layer JDF JQ velocity.

30, Hive dynamic partition settings:set hive.exec.dynamic.partition.mode=nonstrict;

31, Python analysis of common modules:numpy, Pandas, Matplotlib, scipy

32, Mapjoin to solve data tilt

Use scene: In the statement B table has 3 billion rows of records, a table only 100 rows of records, and the data in the B table is particularly severe, there is a key on the 1.5 billion rows of records, in the operation of the process is particularly slow, and in the process of reduece encountered insufficient memory and error.

SELECT /*  * /A.key,  a.value from  join on a.key  = B.Key

33. Left SEMI JOIN is a more efficient implementation of in/exists subquery

1) implement in query via left OUTER JOIN

Select A.keyfrom the leftouterjoin on a.key =  not NULL

2) using the left semi join to implement the in

SELECT A.keyfrom the leftJOIN on (A.key = B.key)

Note: Throttling conditions can only be set in the ON clause, and filtering in the WHERE clause, SELECT clause, or elsewhere is not possible.

The difference between the left semi join and join: If the B table has duplicate values, the left semi join produces one, and the join produces multiple bars.

34. Hive Explode function

--Row to column

35. The Hive table also has a tblproperties used to add descriptive information to the table, such as the last modification of the information, and the last person to modify it.

such as: Tblproperties (' creator ' = ' Zhoumei ', ' created_at ' = ' 2012-01-02 10:00:00 ')

Hive Learning Note: basic syntax

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.