【问题标题】:Hive - computed columns in where clauseHive - where 子句中的计算列
【发布时间】:2019-04-22 05:46:13
【问题描述】:

我正在运行如下所示的配置单元查询。

SELECT from_utc_timestamp(arrival_date, "IST") AS `Date`
    FROM table_name
    WHERE 1 BETWEEN '2018-12-01 00:00:00'
            AND '2018-12-02 00:00:00'; 

这里 1 指的是我的第一个选择列(转换为 IST 时区)。但它没有返回任何行。

arrival_date 列的示例数据:

select arrival_date from table_name;

2019-01-01 21:34:12
2019-01-04 06:12:46

然后我尝试了这个,

SELECT from_utc_timestamp(arrival_date, "IST") AS `Date`
FROM table_name
WHERE from_utc_timestamp(arrival_date, "IST") 
BETWEEN '2018-12-01 00:00:00'
            AND '2018-12-02 00:00:00';

现在我正在获取数据。

但是在 where 子句中,我再次转换数据,这可能会导致 TB 大小的表出现性能问题。

如何在 where 子句中使用计算列?

【问题讨论】:

    标签: sql hive bigdata where-clause


    【解决方案1】:

    如果表格日期是 UTC,参数是 IST,那么您可以将参数转换为 UTC:

    SELECT from_utc_timestamp(arrival_date, "IST") AS `Date`
        FROM table_name 
     WHERE arrival_date BETWEEN to_utc_timestamp('2018-12-01 00:00:00', "IST")
                            AND to_utc_timestamp('2018-12-02 00:00:00', "IST");
    

    如果可能的话,最好的方法是单独计算参数并传递 UTC 格式的日期。例如使用 shell 和调用带参数的 hive 脚本。

    例如在shell中做:

    date_start_IST="2018-12-01 00:00:00"
    date_end_IST="2018-12-02 00:00:00"
    
    date_start_UTC=$( export TZ='GMT' && date -d 'TZ="Asia/Kolkata" '"$date_start_IST" +"%F %H:%M:%S" )
    date_end_UTC=$( export TZ='GMT' && date -d 'TZ="Asia/Kolkata" '"$date_end_IST" +"%F %H:%M:%S" )
    
    echo "$date_start_UTC, $date_end_UTC"
    # prints 2018-11-30 18:30:00, 2018-12-01 18:30:00 
    
    #call Hive script:
    
    hive -hiveconf date_start_UTC="$date_start_UTC" -hiveconf date_end_UTC="$date_end_UTC" -f your_script.hql
    

    在脚本 your_script.hql:

    SELECT from_utc_timestamp(arrival_date, "IST") AS `Date`
            FROM table_name 
         WHERE arrival_date BETWEEN '${hivecong:date_start_UTC}'
                                AND '${hivecong:date_end_UTC}';
    

    以这种方式分区修剪将起作用(如果表按到达日期分区),因为没有函数应用于谓词,优化器甚至可以在执行之前派生分区。

    如果不分区,文件为ORC,谓词下推即可。

    如果没有分区也不是ORC,那就是全扫描,不管是不是谓词和列中的函数。

    【讨论】:

      【解决方案2】:

      一种方法可以是子查询

      select * from (SELECT from_utc_timestamp(arrival_date, "IST") AS `Date`
      FROM table_name
      ) a where a.Date BETWEEN '2018-12-01 00:00:00'
                  AND '2018-12-02 00:00:00';
      

      【讨论】:

        猜你喜欢
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-13
        • 1970-01-01
        • 1970-01-01
        • 2013-10-25
        相关资源
        最近更新 更多