Hadoop 从 HDFS 读取 JSON

Hadoop read JSON from HDFS

我正在尝试将 JSON 文件读入我的 hadoop mapreduce 算法。 我怎样才能做到这一点?我已将文件 'testinput.json' 放入我的 HDFS 内存中的 /input 中。

调用 mapreduce 时我执行 hadoop jar popularityMR2.jar populariy input output,输入说明 dhfs 内存中的输入目录。

public static class PopularityMapper extends Mapper<Object, Text, Text, Text>{


    protected void map(Object key, Text value,
                       Context context)
            throws IOException, InterruptedException {

        JSONParser jsonParser = new JSONParser();
        try {
            JSONObject jsonobject = (JSONObject) jsonParser.parse(new FileReader("hdfs://input/testinput.json"));
            JSONArray jsonArray = (JSONArray) jsonobject.get("votes");

            Iterator<JSONObject> iterator = jsonArray.iterator();
            while(iterator.hasNext()) {
                JSONObject obj = iterator.next();
                String song_id_rave_id = (String) obj.get("song_ID") + "," + (String) obj.get("rave_ID")+ ",";
                String preference = (String) obj.get("preference");
                System.out.println(song_id_rave_id + "||" + preference);
                context.write(new Text(song_id_rave_id), new Text(preference));
            }
        }catch(ParseException e) {
            e.printStackTrace();
        }
    }

}

我的映射器函数现在看起来像这样。我从 dhfs 内存中读取文件。但它总是 returns 一个错误,找不到文件。

有人知道我如何将这个 json 读入 json 对象吗?

谢谢

  1. FileReader 无法从 HDFS 读取,只能从本地文件系统读取。

  2. 文件路径来自作业参数 - FileInputFormat.addInputPath(job, new Path(args[0]));

无论如何,您不会在 Mapper class 中读取文件。

MapReduce 默认读取以行分隔的文件,因此您的 JSON 对象必须每行一个,例如

{"votes":[]}
{"votes":[]}

从映射器中,您可以将 Text 对象解析为 JSONObject,就像这样

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

    JSONParser jsonParser = new JSONParser();
    try {
        JSONObject jsonobject = (JSONObject) jsonParser.parse(value.toString());
        JSONArray jsonArray = (JSONArray) jsonobject.get("votes");

如果文件中只有一个 JSON 对象,那么您可能不应该使用 MapReduce。


否则,您将不得不实现一个 WholeFileInputFormat 并在作业中设置它

job.setInputFormatClass(WholeFileInputFormat.class);

尝试使用以下函数使用 pydoop 库从 HDFS 路径读取 JSON,它正在工作 expected.Hope 它有帮助。

import pydoop.hdfs as hdfs

def lreadline(inputJsonIterator):
    with hdfs.open(inputJsonIterator,mode='rt') as f:
        lines = f.read().split('\n')
    return lines