【问题标题】:Read file that is added to Hive resource using Add File from UDF使用从 UDF 添加文件读取添加到 Hive 资源的文件
【发布时间】: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


    【解决方案1】:

    使用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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 2018-07-25
      • 2012-05-02
      • 2011-04-26
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多