您好,登錄后才能下訂單哦!
這篇文章給大家介紹hive中udtf如何使用,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
場景:使用UDTF解析JSON串
廢話不多說了,直接上代碼
要想寫UDTF必須繼承GenericUDTF類,并實現(xiàn)initialize,process,close三個方法,initialize定義每行的列名及類型,process方法是對數(shù)據(jù)的操作,就是把一行拆成多行,注意一行有多列的話,需要是個集合,close方法可以不實現(xiàn)
package dw.udf;
import java.util.ArrayList; import java.util.Iterator; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.json.JSONArray; import org.json.JSONObject; public class JsonParse extends GenericUDTF {//集成GenericUDTF @Override public StructObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException { if (args.length != 1) { throw new UDFArgumentLengthException("ExplodeMap takes only one argument"); } if (args[0].getCategory() != ObjectInspector.Category.PRIMITIVE) { throw new UDFArgumentException("ExplodeMap takes string as a parameter"); } ArrayList<String> fieldNames = new ArrayList<String>();//這里是列的 ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>(); fieldNames.add("containerid"); fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); fieldNames.add("first_step"); fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); fieldNames.add("second_step"); fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); fieldNames.add("third_step"); fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs); } @SuppressWarnings("rawtypes") @Override public void process(Object[] args) throws HiveException { try { JSONObject obj = new JSONObject(args[0].toString()); Iterator it = obj.keys(); while (it.hasNext()) { String key = (String) it.next(); JSONArray array = obj.getJSONArray(key); if (key.indexOf("&") != -1) { key = key.substring(0, key.indexOf("&")); } String[] outstr = new String[4]; outstr[0] = key; for (int i = 0; i < array.length(); i++) { outstr[i + 1] = array.getString(i); } forward(outstr); } } catch (Exception e) { e.printStackTrace(); } } @Override public void close() throws HiveException { } }
關(guān)于hive中udtf如何使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。