search
HomeDatabaseMysql TutorialHive.分组排序和TOP

Hive.分组排序和TOP

Jun 07, 2016 pm 03:55 PM
hqlsqltopGroupsortInquire

HQL作为类SQL的查询分析语言,到目前为止,应该也还未能达到其它流行的SQL(如Transact-SQL, MySQL)实现那样完善。而在公司的生产环境中,我想应该也不会紧贴Hive版本更新的步伐,始终部署最新版的Hive;可能会滞后一两个大版本神马的;毕竟,虽然开源工具

HQL作为类SQL的查询分析语言,到目前为止,应该也还未能达到其它流行的SQL(如Transact-SQL, MySQL)实现那样完善。而在公司的生产环境中,我想应该也不会紧贴Hive版本更新的步伐,始终部署最新版的Hive;可能会滞后一两个大版本神马的;毕竟,虽然开源工具的透明性是一大利好,但与闭源的商业工具相比,在可用性等问题上的保障性还是略弱。

使用HQL进行离线分析用户数据时,就算已经过聚合处理,但我们也可能只对那些突出的量化指标或者这些指标的增量变化感兴趣,所以对聚合数据排序(按某列降序?增序?)成为很基本的需要,这在HQL这样尚未成熟的语言中,结合orderby, limit子句可以毫无鸭梨地完成。

然而,即使我们可以把多个字段放入order by子句中,并指定各个字段的升降顺序,如:

order by fieldA desc, fieldB [asc], fieldC desc
但排序操作始终是全局的,我们有时候想要的却是分组排序,即按fieldA排序以后,然后针对fieldA的每个值所对应的fieldB和(或)fieldC排序,而不是像order by那样,针对所有fieldA的值对fieldB和(或)fieldC排序。

为了满足这个需要,Transact-SQL提供了over, partition by句和 row_number()函数,而Hive也在0.11中引入over, partition by子句和rank函数,以此提供方便的窗口分析(分组分析)功能。

那对于0.11版之前的Hive,我们可以实现分组排序吗?答案是肯定的,只是看起来没那么直接。

要实现这个需求,就需要请出distribute by, sort by这两个重要角色了,distribute by能够执行我们需要的分组功能,再结合Hive查询的MapReduce Job特性,sort by又可以在分组内进行局部排序。

当然,如果只有它们,我们只能得到排序后的一堆数据,但是无法知道每一条数据的名次,这就要自己编写UDF函数,来确定和返回名次了,这个函数貌似在网络上流传甚广:

public final class Rank extends UDF {
      private int counter;
      private String last_key ="";
 
      public int evaluate(final String key) {
             if (key == null) {
                    this.last_key= "";
                    this.counter= 0;
                    return counter;
             }
             if(!key.equalsIgnoreCase(this.last_key)) {
                    this.counter= 0;
                    this.last_key= key;
             }
             return this.counter++;
      }
}

在这里我们忽略了自定义UDF的注册的环节。。。在分组之后,应用Rank函数,这个函数始终跟踪最新的参数值,在参数值连续相同的情况下,就将字段counter作自增操作并返回这个计数值;而如果出现和上一次函数调用不同的参数值,Rank函数会重置其计数值字段和key字段(对应参数值)使我们得到一个int类型的名次值。

Hive里称这个为自定义函数,实际上每个自定义函数是一个实现了evaluate方法的类,这个叫法略不福啊。

有了distribute by, sort by和这个Rank函数,我们就能够实现分组排序了,编写HQL查询脚本之前,我们还需要明确:

1. 分组字段:distribute by的字段是哪个(些)?

2. 排序依据:sort by的字段是哪个(些)?

3. 函数参数:Rank函数需要String参数,我们应该给Rank函数传递什么东西作为实参?

不晓得是因为以上这3个问题确实像我们在教科书上偶尔会看到的“容易证得”,还是因为博主们只是想了这个问题,并没有实践,反正我看到的网络上讲分组排序(TOP)的博文都没有明确地提出这3个问题。而按我的实践经历来看,初次实现这种需求的童鞋,就算看了这些博文,在得到正确结果之前,应该都会经历各种困惑,下面我们从实际的场景来看看。

比如,我们需要查询得到这样的数据:每日使用应用myAPP的UV量TOP 30的设备,和这TOP 10的设备中每个设备的流量(VV)最高的10项版块内容(以内容ID来区分);

假定查询所需的Hive表为:hiveTab_useraction

思路梗概:先用一个子查询查出来每台设备的访问内容,同时,用一个子查询查出来TOP30的设备,然后两个表做内连接(join),然后在外层查询中提取所需字段列和数据列。

在这个流程里面:

1)找出TOP10的设备这个环节看起来没有涉及分组排序,但还是需要考虑上面3个问题,因为我们要得到名次,而order by貌似不能同Rank函数友好协作(也有可能是我使用的方式不科学呢),而且,在以下呈现的脚本中,我们还生成了一个常量字符串的distribute_key;

2)然后在外层循环中更需要考虑上面3个问题。

请见HQL脚本:

select
	device_rank,
	device_info,
	vv_rank,
	pageID,	
	act_vv
from
(
	select
		device_rank,
		device_info,
		(Rank(device_rank) + 1) as vv_rank,
		pageID,
		act_vv
	from
	(	
		select
			t2.device_rank,
			t2.device_info,
			t1.pageID,
			t1.act_vv
		from
		(
			select
				fieldA as device_info,
				pageID,
				count(1) as act_vv
			from hiveTab_useraction
			where `date` >= dateStart and `date` <= dateEnd
			group by fieldA, pageID
		) t1
		join
		(
			select
				(Rank(distribute_key) + 1) as device_rank,
				device_info,
				act_uv
			from
			(
				select
					distribute_key,
					device_info,
					act_uv
				from
				(
					select
						&#39;topdevice&#39; as distribute_key,
						device_info,
						act_uv
					from
					(
						select
							fieldA as device_info,
							count(distinct uid) as act_uv
						from hiveTab_useraction
						where `date` >= dateStart and `date` <= dateEnd
						group by fieldA
					) t
					order by act_uv desc
					limit 10
				) t
				distribute by distribute_key 
				sort by act_uv desc
			) t
		) t2 on (t1.device_info = t2.device_info)
		distribute by t2.device_rank
		sort by t2.device_rank, t1.act_vv desc
	) t
) t
where vv_rank <= 10
从脚本实测来看,上面提到的需要明确的3个问题,真的很重要。另外,Rank函数返回的名次是从0开始,所以我们需要作+1处理。

Hive向普通用户也开放了自行编写、注册和使用自定义函数的功能,这一点确实带来了很大的扩展性。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools