Technology Sharing

Reverse function in Hive

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Preface

The reverse function is a commonly used string processing function that is available in many programming languages. Recently, during development, I encountered a requirement for a reverse solution, and I found that I had not yet summarized it, so I made up for it.

Basic function introduction

SELECT reverse(string_column) FROM table_name;
  • 1

Example:

SELECT reverse('hello world');
  • 1

The result is:
dlrow olleh

Actual Combat

Currently there are three fields: user id, user name, and interest id combination. The current requirement is to get the last one of each user and interest id combination;

Implementation:

with temp_test as 
(
    select '1458963' as userid ,'小花'  as  user_name ,'[1,5,8]' as favsid
    union all 
    select '1258963' as userid ,'小明'  as  user_name ,'[3,7,9,10]' as favsid 
    union all  
    select '3245895' as userid ,'小翠'  as  user_name ,'[]' as favsid  
)


select 
userid
,user_name
,reverse(split(favsid,'\,')[0]) as favsid
from  
(select 
userid
,user_name
,regexp_replace(reverse(favsid),'\[|\]','') as favsid
from  temp_test
) tt 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

The results are as follows:

useriduser_namefavsid
1458963Small Flower8
1258963Xiao Ming10
3245895Xiao Cui