【问题标题】:Hive - how to reuse a sub-query in hive with optimal performanceHive - 如何在 Hive 中以最佳性能重用子查询
【发布时间】:2017-10-05 20:38:14
【问题描述】:

当我有一个在整个 select 语句中重复多次的复杂子查询时,在 Hive 中构造/编写查询的最佳方法是什么?

我最初为子查询创建了一个临时表,该表在每次运行之前都会刷新。然后我开始使用 CTE 作为原始查询的一部分(丢弃临时表)以提高可读性并注意到性能下降。这让我很好奇在需要重用子查询时,哪种实现方法在性能方面最好。

我正在处理的数据包含超过 1000 万条记录。下面是我编写的使用 CTE 的查询示例。

with temp as (
   select
      a.id,
      x.type,
      y.response
   from sandbox.tbl_form a
   left outer join sandbox.tbl_formStatus b
   on a.id = b.id
   left outer join sandbox.tbl_formResponse y
   on b.id = y.id
   left outer join sandbox.tbl_formType x
   on y.id = x.typeId
   where b.status = 'Completed'
)
select
   a.id,
   q.response as user,
   r.response as system,
   s.response as agent,
   t.response as owner
from sandbox.tbl_form a
left outer join (
   select * from temp x
   where x.type= 'User'
) q
on a.id = q.id
left outer join (
   select * from temp x
   where x.type= 'System'
) r
on a.id = r.id
left outer join (
   select * from temp x
   where x.type= 'Agent'
) s
on a.id = s.id
left outer join (
   select * from temp x
   where x.type= 'Owner'
) t
on a.id = t.id;

【问题讨论】:

    标签: performance view hive subquery common-table-expression


    【解决方案1】:

    您的查询存在问题。

    1) 在 CTE 中,您有三个没有 ON 子句的左连接。这可能会导致严重的性能问题,因为没有 ON 子句的连接是 CROSS JOINS。

    2) 顺便说一句,where b.status = 'Completed' 子句将与表 b 的 LEFT 联接转换为内部联接,尽管仍然没有 ON 子句,它将 a 中的所有记录与 b 中的所有记录与 where 相乘。

    3) 很可能您根本不需要 CTE。只需正确加入ON 子句并使用case when type='User' then response end + 聚合使用min()max() by id

    select a.id
    max(case when x.type='User' then y.response end) as user,
    max(case when x.type='System' then y.response end) as system,
    ...
    
    from sandbox.tbl_form a
       left outer join sandbox.tbl_formStatus b
       on a.id = b.id
       left outer join sandbox.tbl_formResponse y
       on b.id = y.id
       left outer join sandbox.tbl_formType x
       on y.id = x.typeId
       where b.status = 'Completed' --if you want LEFT JOIN add --or b.status is null
    group by a.id
    

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2020-02-12
      相关资源
      最近更新 更多