我在 Hive 中有一个表,其中一列是字符串。该列中的值类似于“x=1,y=2,z=3”。我需要编写一个查询,为所有行在此列中添加 x 的值。如何提取 x 的值并将它们相加?
最佳答案
您需要一个 UDF
来进行此转换:
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
class SplitColumn extends UDF {
public Integer evaluate(Text input) {
if(input == null) return null;
String val=input.toString().split("=")[1];
return Integer.parseInt(val);
}
}
现在你可以试试这个:
hive> ADD JAR target/hive-extensions-1.0-SNAPSHOT-jar-with-dependencies.jar;
hive> CREATE TEMPORARY FUNCTION SplitColumn as 'com.example.SplitColumn';
hive> select sum(SplitColumn(mycolumnName)) from mytable;
P.S:我没有测试过这个。但这应该为您指明前进的方向。
关于hadoop - 在 Hive 查询中获取字符串中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168106/