如何使用 HIVE 自动获取列中的当前日期和时间

How to automatically get the current date and time in a column using HIVE

嘿,我的 HIVE 中有两列 table :

例如:-

c1 : name
c2 : age

现在,在创建 table 时,我想声明另外两列,它们会在加载行时自动为我提供当前日期和时间。 例如:John 24 26/08/2015 11:15 如何做到这一点?

注意:您不能将超过 1 列设置为 CURRENT_TIMESTAMP

这里这样,你不能在一栏中设置CURRENT_TIMESTAMP

SQL:

CREATE TABLE IF NOT EXISTS `hive` (
  `id` int(11) NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `age` int(11) DEFAULT '0',
  `datecreated` timestamp NULL DEFAULT CURRENT_TIMESTAMP
);

Hive 当前不支持在创建 table 时向任何列定义添加默认值的功能。完整的 hive create table 语法请参考link: Hive Create Table specification

解决此问题的替代方法是临时将数据加载到临时 table 并使用 insert overwrite table 语句将当前日期和时间添加到主table。

下面的例子可能会有所帮助:

1.创建临时 table

create table EmpInfoTmp(name string, age int);

2。使用文件或现有 table 将数据插入 EmpInfoTmp table:

name|age
Alan|28
Sue|32
Martha|26


3。创建一个 table 将包含您的最终数据:

create table EmpInfo(name string, age tinyint, createDate string, createTime string);

4.从临时 table 插入数据,同时添加默认值为当前日期和时间的列:

insert overwrite table empinfo select name, age, FROM_UNIXTIME( UNIX_TIMESTAMP(), 'dd/MM/YYYY' ), FROM_UNIXTIME( UNIX_TIMESTAMP(), 'HH:mm' ) from empinfofromfile;


5.最终结果是这样的:

name|age|createdate|createtime
Alan|28|26/08/2015|03:56
Martha|26|26/08/2015|03:56
Sue|32|26/08/2015|03:56


请注意,当数据进入临时 table.

时,通过将数据添加到您的最终 table 中,可以准确输入创建日期和时间值。

嘿,我找到了一种使用 shell 脚本的方法。

方法如下:

echo "$(日期+"%Y-%m-%d-%T") $(wc -l /home/hive/landing/$line ) $dir " >> /home/hive/recon/fileinfo.txt

在这里我得到没有空格的日期。最后,我将文本文件上传到我的配置单元 table。