日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

hive之反斜杠导致Unicode编码字段里的中文无法正常显示

發布時間:2023/12/8 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hive之反斜杠导致Unicode编码字段里的中文无法正常显示 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

hive之反斜杠導致Unicode編碼字段里的中文無法正常顯示

從mysql拉到hive的ods的表中字段顯示不正常,如下

content字段中文無法顯示
首先利用在線unicode解析看下具體的中文內容是什么

**初始判定問題原因:**此時暫時判定是因為hive沒有成功將“unicode”編碼格式的字段轉化為“utf-8”,故而無法正常顯示
因為沒有找到合適的函數進行轉碼,所以自定義UDF,如下

import org.apache.commons.lang3.StringEscapeUtils; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.Text;public class SelfUnicode extends GenericUDF {/**** @param arguments 輸入參數類型的鑒別器對象* @return 返回值類型的鑒別器對象* @throws UDFArgumentException*/public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {// 判斷輸入參數的個數if(arguments==null ||arguments.length!=1){throw new UDFArgumentLengthException("函數的參數個數不正確!!!");}// 判斷輸入參數的類型if(!arguments[0].getCategory().equals(ObjectInspector.Category.PRIMITIVE)){throw new UDFArgumentTypeException(0,"函數參數類型不正確!!!");}//需要返回string類型的鑒別器對象return PrimitiveObjectInspectorFactory.writableStringObjectInspector;}/**** @param arguments* @return*///private final IntWritable intWritable = new IntWritable(0);private final Text result = new Text();public Object evaluate( DeferredObject[] arguments) throws HiveException {Object o = arguments[0].get();if(o==null){result.set("NULL");return result;}String str = o.toString();if(str.equals("")){result.set("字段值為空");return result;}String res_str="";try {res_str = URLDecoder.decode(str, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}result.set(res_str);return result;}public String getDisplayString(String[] strings) {return "";} }

上傳hdfs后,添加臨時函數,測試運行得結果

add jar hdfs:///user/hive/warehouse/auxlib/self_unicode-1.0-SNAPSHOT.jar; create temporary function my_unicode as 'com.atweimiao.unicodeudf.SelfUnicode'; select my_unicode('"question_id":1,"name":"\u8eab\u9ad8\u4f53\u91cd","tag":"\u8eab\u9ad8\u4f53\u91cd","type":1')


當我以為問題解決的時候,現實很骨感,竟然還是無法轉碼顯示

我以為代碼出了問題,換網絡IO的傳遞對象、換處理的方法,最終還是測試過程沒問題,唯獨解析不了字段,難受!
后來我將這堆字符串黏貼到java中發現了端倪,當這個函數處理字段的時候不是頁面顯示的樣子,其實處理過程多了很多的轉義字符‘\’

因為這些轉義字符,導致URLDecoder.decode(str, "utf-8")無法正確解析str字符串

**最終判定問題原因:**思考之后,其實是反斜杠的原因,導致無法進行解析字符串

故而,使用org.apache.commons.lang3.StringEscapeUtils里的unescapeJava方法可以實現反轉義

使用hive的函數reflect()有時可以實現自定義UDF的一些功能的,所以使用reflect

reflect('org.apache.commons.lang3.StringEscapeUtils', 'unescapeJava',content)

測試運行如下,成功轉碼顯示

總結

以上是生活随笔為你收集整理的hive之反斜杠导致Unicode编码字段里的中文无法正常显示的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。