一定数量后的蜂巢自动增量

时间:2016-08-15 05:23:44

标签: hive

我有一个将数据插入到目标表中,其中所有列都应该从不同的源表中填充,但代理键列除外;这应该是目标表的最大值加上自动增量值的开始1.我可以使用row_number()函数生成自动增量值,但在同一查询中,我应如何从目标表中获取代理键的最大值。在HIVE中是否有任何概念我可以选择代理键的最大值并将其保存在临时变量中?或者有没有其他简单的方法来实现这个结果?

2 个答案:

答案 0 :(得分:8)

以上是针对上述问题的两种方法。 (用例子解释)

方法1:使用shell脚本通过$ {hiveconf}变量获取最大值并设置为hive命令

方法2:使用row_sequence(),max()和连接操作

我的环境:

hadoop-2.6.0
apache-hive-2.0.0-bin

步骤注意:步骤1和步骤2对于两种方法都是通用的。从步骤3开始,两者都不同)

第1步:创建源表和目标表

<强>来源

hive>create table source_table1(string name);
hive>create table source_table2(string name);
hive>create table source_table2(string name);

<强>靶

hive>create table target_table(int id,string name);

第2步:将数据加载到源表

hive>load data local inpath 'source_table1.txt' into table source_table1;
hive>load data local inpath 'source_table2.txt' into table source_table2;
hive>load data local inpath 'source_table3.txt' into table source_table3;

示例输入:

source_table1.txt

a
b
c

source_table2.txt

d
e
f

source_table3.txt

g
h
i

方法1:

第3步:创建一个shell脚本hive_auto_increment.sh

#!/bin/sh
hive -e 'select max(id) from target_table' > max.txt
wait
value=`cat max.txt`
hive --hiveconf mx=$value -e "add jar /home/apache-hive-2.0.0-bin/lib/hive-contrib-2.0.0.jar;
create temporary function row_sequence as 'org.apache.hadoop.hive.contrib.udf.UDFRowSequence';
set mx;
set hiveconf:mx;
INSERT INTO TABLE target_table SELECT row_sequence(),name from source_table1;
INSERT INTO TABLE target_table SELECT (\${hiveconf:mx} +row_sequence()),name from source_table2;
INSERT INTO TABLE target_table SELECT (\${hiveconf:mx} +row_sequence()),name from source_table3;"
wait
hive -e "select * from target_table;"

第4步:运行shell脚本

 > bash  hive_auto_increment.sh 

方法2:

第3步:添加Jar

    hive>add jar /home/apache-hive-2.0.0-bin/lib/hive-contrib-2.0.0.jar;

步骤4:在hive contrib jar的帮助下注册row_sequence函数

hive>create temporary function row_sequence as 'org.apache.hadoop.hive.contrib.udf.UDFRowSequence';

第5步:将source_table1加载到target_table

hive>INSERT INTO TABLE target_table select row_sequence(),name from source_table1;

第6步:将其他来源加载到target_table

  hive>INSERT INTO TABLE target_table SELECT M.rowcount+row_sequence(),T.name from source_table2 T join (select max(id) as rowcount from target_table) M;

  hive>INSERT INTO TABLE target_table SELECT  M.rowcount+row_sequence(),T.name from source_table3 T join (select max(id) as rowcount from target_table) M;

<强>输出:

INFO  : OK
+---------------+-----------------+--+
| target_table.id  | target_table.name  
+---------------+-----------------+--+
| 1                | a               |
| 2                | b               |
| 3                | c               |
| 4                | d               |
| 5                | e               |
| 6                | f               |
| 7                | g               |
| 8                | h               |
| 9                | i               |

答案 1 :(得分:0)

创建表autoincrement1(id int,名称字符串)

插入autoincrement1
从autoincrement1中选择if(isnull(max(id)),0,max(id))+1,'sagar'

相关问题