如何对数组排序并返回蜂巢中的索引? [英] How to sort an array and return the index in hive?

查看:117
本文介绍了如何对数组排序并返回蜂巢中的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在蜂巢中,我希望从最大到最小对数组进行排序,并获得索引数组.

In hive, I wish to sort an array from largest to smallest, and get the index array.

例如,表格如下:

id  |  value_array
 1  |  {30, 40, 10, 20}
 2  |  {10, 30, 40, 20}

我愿意得到这个:

id  |  value_array
 1  |  {1, 0, 3, 2}
 2  |  {2, 1, 3, 0}

结果arries是初始元素的索引.我该如何实现?

The arries in result are the index of the initial elements. How can I achieve this?

推荐答案

使用posexplode分解数组以获取索引和值,按值排序,收集索引数组:

Explode array using posexplode to get index and value, sort by value, collect array of index:

select id, collect_list(pos) as result_array
from
(
select s.id, a.pos, a.v 
  from your_table s
       lateral view posexplode(s.value_array) a as pos, v
distribute by s.id sort by a.v DESC --sort by value
)s
group by id
;

经过测试,结果:

id  result_array
1   [1,0,3,2]
2   [2,1,3,0]

这篇关于如何对数组排序并返回蜂巢中的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆