1、場景描述
在Hive中,基于某個表創(chuàng)建視圖,直接引用表的字段是不會有問題的;但如果增加一個不存在表中的字段,且字段值為中文,就會出現(xiàn)亂碼的問題。
create table t_unicode_test as select '中國' as country;
create view v_unicode_test as select country, '中國' as country2 from t_unicode_test;
select * from test.v_unicode_test;
+-------------------------+--------------------------+
| v_unicode_test.country | v_unicode_test.country2 |
+-------------------------+--------------------------+
| 中國 | ?? |
+-------------------------+--------------------------+
2、解決過程
????????在網(wǎng)上找了一圈,原因是Hive的元數(shù)據(jù)庫默認(rèn)編碼是 Latin1(ISO-8859-1),解決方案基本都是去Hive元數(shù)據(jù)庫修改編碼。
? ? ? ? 等等,Excuse me???誰家的開發(fā)權(quán)限這么大,還可以改元數(shù)據(jù)庫?沒有權(quán)限訪問Hive的元數(shù)據(jù)庫,看來只能 “曲線救國” 了。
? ? ? ? 思來想去,最后發(fā)現(xiàn)使用 Unicode碼 就可以了。
3、解決方案
? ? ? ? 問題來了,如何將字符串轉(zhuǎn)換為Unicode碼。我在網(wǎng)上抄了一段java代碼:
public static String strToUnicode(String str) {
char[] chars = str.toCharArray();
StringBuilder returnStr = new StringBuilder();
for (char aChar : chars) {
returnStr.append("\\u").append(Integer.toString(aChar, 16));
}
return returnStr.toString();
}
public static void main(String[] args) {
String str = "中國";
System.out.println(strToUnicode(str));
}
結(jié)果:\u4e2d\u56fd
再修改一下創(chuàng)建視圖的語句
alter view v_unicode_test as select country, '\u4e2d\u56fd' as country2 from t_unicode_test;
select * from test.v_unicode_test;
+-------------------------+--------------------------+
| v_unicode_test.country | v_unicode_test.country2 |
+-------------------------+--------------------------+
| 中國 | 中國 |
+-------------------------+--------------------------+
完美解決文章來源:http://www.zghlxwxcb.cn/news/detail-580706.html
后話:
????????如果本地沒有java環(huán)境,可以借助一下Hive文章來源地址http://www.zghlxwxcb.cn/news/detail-580706.html
select java_method('java.net.URLEncoder', 'encode', '中國', 'UTF-16BE');
+---------------+
| _c0 |
+---------------+
| %4E%2D%56%FD |
+---------------+
到了這里,關(guān)于解決Hive視圖View數(shù)據(jù)亂碼的問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!