【问题标题】:Checking if directory in HDFS already exists or not检查HDFS中的目录是否已经存在
【发布时间】:2014-12-18 06:44:59
【问题描述】:

我在 HDFS 中有以下目录结构,

/analysis/alertData/logs/YEAR/MONTH/DATE/HOURS

也就是说,数据是按月来的,并以年/月/日/小时的格式存储。

我已经编写了一个 shell 脚本,我在其中传递路径直到

"/analysis/alertData/logs"   ( this will vary depending on what product of data i am handling)

然后shell脚本遍历年/月/日/小时文件夹并返回最新的路径。

例如:

 Directories present in HDFS has following structure: 

 /analysis/alertData/logs/2014/10/22/01
 /analysis/alertData/logs/2013/5/14/04

 shell script is given path till :   " /analysis/alertData/logs "

 it outputs most recent directory :    /analysis/alertData/logs/2014/10/22/01

我的问题是如何验证传递给 shell 脚本的 HDFS 目录路径是否有效。假设我传递了错误的路径作为输入或不存在的路径,那么如何在 shell 脚本中处理它。

示例错误路径可以是:

  wrong path   :  /analysis/alertData ( correct path :  /analysis/alertData/logs/ )
  wrong path   :  /abc/xyz/  ( path does not exit in HDFS )

我尝试使用 Hadoop dfs -test -z/-d/-e 选项对我不起作用。 对此有任何建议。

注意:不在这里发布我的原始代码,因为我的问题的解决方案不依赖于它。

提前致谢。

【问题讨论】:

    标签: shell hadoop scripting hdfs


    【解决方案1】:

    尝试不带测试命令 []:

    if $(hadoop fs -test -d $yourdir) ; then echo "ok";else echo "not ok"; fi
    

    【讨论】:

    • 我想补充一下,我试过了,这个命令只工作没有 []。
    【解决方案2】:

    自从

    hdfs dfs -test -d $yourdir
    

    如果存在则返回0,那么

    if [ $? == 0 ]; then
        echo "exists"
    else
        echo "dir does not exists"
    fi
    

    【讨论】:

      【解决方案3】:

      Hadoop fs 已弃用 用法:hdfs dfs -test -[ezd] URI

      选项: -e 选项将检查文件是否存在,如果为真则返回 0。 -z 选项将检查文件是否为零长度,如果为真则返回 0。 -d 选项将检查路径是否为目录,如果为真则返回 0。 示例:hdfs dfs -test -d $yourdir

      请查看以下内容以获取更多信息:https://hadoop.apache.org/docs/r2.4.1/hadoop-project-dist/hadoop-common/FileSystemShell.html 问候

      【讨论】:

        【解决方案4】:

        您好,我使用以下脚本来测试 HDFS 目录是否存在。我在您的问题中看到您尝试了这个测试命令但没有奏效。您能否提供任何关于为什么这不起作用的线索..

         hadoop fs -test -d $dirpath
            if [ $? != 0 ]
                    then
                        hadoop fs -mkdir $dirpath
                        else
                            echo "Directory already present in HDFS"
            fi
        

        【讨论】:

          【解决方案5】:

          适用于带有火花的 scala。

          import org.apache.hadoop.fs.{FileSystem, Path}
          val fs = FileSystem.get(spark.sparkContext.hadoopConfiguration)
          val fileExists = fs.exists(new Path(<HDFSPath>)) //return boolean of true or false
          

          【讨论】:

            【解决方案6】:

            在 Java 中,我们可以使用 FileSystem 类来验证这一点。

            FileSystem

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-10-28
              • 2012-05-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多