【发布时间】:2019-02-01 03:33:50
【问题描述】:
我想知道如何从 Udf 读取使用 ADD FILE 添加的 Hive 资源?
例如
Hive > add file /users/temp/key.jks
是否可以在 Java 的 UDF 中读取此文件? 在 Udf 中获取此文件的路径是什么?
谢谢 大卫
【问题讨论】:
标签: java hive user-defined-functions
我想知道如何从 Udf 读取使用 ADD FILE 添加的 Hive 资源?
例如
Hive > add file /users/temp/key.jks
是否可以在 Java 的 UDF 中读取此文件? 在 Udf 中获取此文件的路径是什么?
谢谢 大卫
【问题讨论】:
标签: java hive user-defined-functions
使用ADD 命令将资源添加到会话后,Hive 查询可以通过其名称(在 map/reduce/transform 子句中)引用它,并且该资源在整个 Hadoop 集群上的执行时本地可用。 Hive 使用 Hadoop 的分布式缓存在查询执行时将添加的资源分配给集群中的所有机器。见这里:HiveResources
Hive 中有 in_file(string str, string filename) 函数 - 如果字符串 str 在文件名中显示为整行,则返回 true。可以以in_file源码为例:GenericUDFInFile.java
源代码中的几个方法:
private BufferedReader getReaderFor(String filePath) throws HiveException {
try {
Path fullFilePath = FileSystems.getDefault().getPath(filePath);
Path fileName = fullFilePath.getFileName();
if (Files.exists(fileName)) {
return Files.newBufferedReader(fileName, Charset.defaultCharset());
}
else
if (Files.exists(fullFilePath)) {
return Files.newBufferedReader(fullFilePath, Charset.defaultCharset());
}
else {
throw new HiveException("Could not find \"" + fileName + "\" or \"" + fullFilePath + "\" in IN_FILE() UDF.");
}
}
catch(IOException exception) {
throw new HiveException(exception);
}
}
private void loadFromFile(String filePath) throws HiveException {
set = new HashSet<String>();
BufferedReader reader = getReaderFor(filePath);
try {
String line;
while((line = reader.readLine()) != null) {
set.add(line);
}
} catch (Exception e) {
throw new HiveException(e);
}
finally {
IOUtils.closeStream(reader);
}
}
【讨论】: