【问题标题】:How to read a CSV file from Hdfs?如何从 Hdfs 读取 CSV 文件?
【发布时间】:2013-06-13 06:51:09
【问题描述】:

我的数据保存在 CSV 文件中。我想读取 HDFS 中的 CSV 文件。

谁能帮我写代码??

我是 hadoop 新手。提前致谢。

【问题讨论】:

  • 只是阅读或mapreduce?你试过什么?
  • 我只是想看,现在没有 map reduce。我无法搜索读取 csv 文件所需的确切类
  • 即使 Map Reduce 也可以工作,只是我的任务是能够读取放在 HDFS 中的 csv 文件。
  • 请看下面的答案。

标签: csv hadoop hdfs mahout


【解决方案1】:

为此所需的类是FileSystemFSDataInputStreamPath。客户端应该是这样的:

public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        Configuration conf = new Configuration();
        conf.addResource(new Path("/hadoop/projects/hadoop-1.0.4/conf/core-site.xml"));
        conf.addResource(new Path("/hadoop/projects/hadoop-1.0.4/conf/hdfs-site.xml"));
        FileSystem fs = FileSystem.get(conf);
        FSDataInputStream inputStream = fs.open(new Path("/path/to/input/file"));
        System.out.println(inputStream.readChar());         
    }

FSDataInputStream 有几个read 方法。选择适合您需要的。

如果是MR,那就更简单了:

        public static class YourMapper extends
                    Mapper<LongWritable, Text, Your_Wish, Your_Wish> {

                public void map(LongWritable key, Text value, Context context)
                        throws IOException, InterruptedException {

                    //Framework does the reading for you...
                    String line = value.toString();      //line contains one line of your csv file.
                    //do your processing here
                    ....................
                    ....................
                    context.write(Your_Wish, Your_Wish);
                    }
                }
            }

【讨论】:

    【解决方案2】:

    如果你想使用mapreduce,你可以使用TextInputFormat逐行读取并解析mapper的map函数中的每一行。

    其他选项是开发(或查找已开发的)CSV 输入格式,用于从文件中读取数据。

    这里有一个旧教程http://hadoop.apache.org/docs/r0.18.3/mapred_tutorial.html,但新版本中的逻辑相同

    如果您使用单个进程从文件中读取数据,则它与从任何其他文件系统中读取文件相同。这里有一个很好的例子https://sites.google.com/site/hadoopandhive/home/hadoop-how-to-read-a-file-from-hdfs

    HTH

    【讨论】:

    猜你喜欢
    • 2013-08-08
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多