Order By
1 | colOrder: ( ASC | DESC ) |
Order By:全局排序。只有一个 Reducer,无论将reducer设置为几,实际都只有一个。如果指定了hive.mapred.mode=strict(默认值是nonstrict),这时就必须指定limit来限制输出条数,原因是:所有的数据都会在同一个reducer端进行,数据量大的情况下可能不能出结果,那么在这样的严格模式下,必须指定输出的条数。
- 效率较低。
- 两种排序方式。ASC: 升序(默认) ;DESC: 降序。
- ORDER BY 子句在SELECT 语句的结尾
例:
select * from emp order by sal desc;
Sort By
1 | colOrder: ( ASC | DESC ) |
Sort By:分区排序,即每个 Reduce 内部排序。对于大规模的数据集 order by 的效率非常低。在很多情况下,并不需要全局排序,此时可以使用 sort by。
Sort by 会在数据进入reduce之前为每个reducer都产生一个排序后的文件。因此,如果用sort by进行排序,并且设置mapreduce.job.reduces>1,则sort by只保证每个reducer的输出有序,不保证全局有序。
单独使用sort by时随机划分数据所在区,往往和distribute by联用。
CLUSTER BY会根据字段分区,如果有多个reducer, SORT BY会随机分区。
例:
1 | SELECT key, value FROM src SORT BY key ASC, value DESC |
查询有2个reducer,它们的输出分别是:
1 | 0 5 |
1 | 0 4 |
Distribute By
Distribute By:分区操作。 在有些情况下,为了进行后续的聚集操作,我们需要控制某个特定行应该到哪个 reducer。distribute by 类似 MR 中 partition(自定义分区)进行分区,结合 sort by 使用。hive会根据distribute by后面列,将数据分发给对应的reducer,默认是采用hash算法+取余数的方式。Distribute By不保证distributed keys是聚集和有序的。
例:For example, we are Distributing By x on the following 5 rows to 2 reducer:
1 | x1 |
Reducer 1 got
1 | x1 |
Reducer 2 got
1 | x4 |
注意,键值为x1的所有行被分到同一个reducer中,但它们并不是邻近的。
注意:
➢ distribute by 的分区规则是根据分区字段的 hash 码与 reduce 的个数进行模除后, 余数相同的分到一个区。
➢ Hive 要求 DISTRIBUTE BY 语句要写在 SORT BY 语句之前。
Cluster By
官方定义:Cluster By is a short-cut for both Distribute By and Sort By.
当 distribute by 和 sorts by 字段相同时,可以使用 cluster by 方式。cluster by 除了具有 distribute by 的功能外还兼具 sort by 的功能。
注意:排序只能是升序排序,不能指定排序规则为 ASC 或者 DESC。
例:In contrast, if we use Cluster By x, the two reducers will further sort rows on x:
Reducer 1 got
1 | x1 |
Reducer 2 got
1 | x3 |
和Distribute By的例子相比,具有排序功能。
1 | SELECT col1, col2 FROM t1 CLUSTER BY col1 |
Instead of specifying Cluster By, the user can specify Distribute By and Sort By, so the partition columns and sort columns can be different. The usual case is that the partition columns are a prefix of sort columns, but that is not required.
1 | SELECT col1, col2 FROM t1 DISTRIBUTE BY col1 SORT BY col1 ASC, col2 DESC |
参考链接:
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy