【问题标题】:Convert string to timestamp in hive when creating a table创建表时将字符串转换为配置单元中的时间戳
【发布时间】:2021-10-11 20:56:24
【问题描述】:

我有一些 CSV 格式的实时数据。我想从这些数据创建外部表,以便我可以从配置单元查询它。挑战在于,这些文件的 unix 纪元为last_updated_epoch,日期字段last_updated 格式为2021-08-04T06:48:55。我无法将此日期读取为时间戳,因此需要将这些字段转换为时间戳以根据日期和时间进行查询。

我能做什么:我能够创建一个时间戳为 BIGINT 和 last_updated 为字符串的表。但不能在创建表时将last_updated 作为时间戳。选择工作正常:

select last_updated, cast(from_unixtime(last_updated_epoch) as TIMESTAMP) from station_mart limit 10;

【问题讨论】:

    标签: hadoop hive timestamp bigdata hiveql


    【解决方案1】:

    你可以做的是:-

    1. 让您的外部表具有您想要的数据类型。
    2. 将您的 csv 文件放到其他位置。
    3. 使用 load data inpath 命令首先将数据加载到临时表中 着陆位置,然后 使用 insert into 命令将数据从 临时表。在将此数据加载到外部表时,您可以 根据需要转换数据。
    4. 要处理实时数据,您可以创建第 2 步和第 3 步的脚本,然后 将其安排在小于您的 SLA 的时间间隔内,这将为您提供真实的数据 时间。

    Load data inpath 命令会移动数据,因此您不必担心数据重复。

    【讨论】:

      【解决方案2】:

      我提出了三种不同的方法来将您的字符串转换为时间戳。如果您的表定义为 STORED AS TEXTFILE 以外的表,则前两个适用,如果您可以使用 LazySimpleSerDe(与 STORED AS TEXTFILE 相同),则第三种方法适用,在这种情况下,SerDe 将在尽可能低的 livel 上进行转换。

      选择中的转化:

      select last_updated as original_last_updated, --initial string 
      
             --1st method (preferable, because it is not using SimpleDateFormat(which is really not so simple) class internally)
             --you can additionally apply timestamp() construct, though in Hive String in proper format is fully interchangeable
             regexp_replace(last_updated,'^(\\d{4}-\\d{2}-\\d{2})T(\\d{2}:\\d{2}:\\d{2})','$1 $2') as result1, 
      
             --2nd method is using SimpleDateFormat under the hood, easier to read
             from_unixtime(unix_timestamp(last_updated,"yyyy-MM-dd'T'HH:mm:ss")) as result2
      from
      (select '2021-08-04T06:48:55' as last_updated ) s
      

      结果:

      original_last_updated         result1                result2
      2021-08-04T06:48:55           2021-08-04 06:48:55    2021-08-04 06:48:55
      

      第三种方法 - 使用 LazySimpleSerDe:

      如果您使用的是 LazySimpleSerDe(存储为文本文件),则可以通过向 SerDe 属性"timestamp.formats" 提供格式来支持替代时间戳格式(自 1.2.0 版起,HIVE-9298) .尝试将"yyyy-MM-dd'T'HH:mm:ss" 作为属性值并将列类型定义为timestamp。虽然 LazySimpleSerDe 不识别引号,但可以在您拥有带有未引用值的简单 CSV 的情况下使用。

      【讨论】:

        猜你喜欢
        • 2013-10-22
        • 1970-01-01
        • 2020-11-22
        • 1970-01-01
        • 2020-11-05
        • 2016-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多