Convert a text file to sequence format in Spark Java

1.8k views Asked by At

In Spark Java, how do I convert a text file to a sequence file? The following is my code:

    SparkConf sparkConf = new SparkConf().setAppName("txt2seq");
    sparkConf.setMaster("local").set("spark.executor.memory", "1g");
    sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
    JavaSparkContext ctx = new JavaSparkContext(sparkConf);

    JavaPairRDD<String, String> infile = ctx.wholeTextFiles("input_txt");
    infile.saveAsNewAPIHadoopFile("outfile.seq", String.class, String.class, SequenceFileOutputFormat.class);

And I got the error below.

14/12/07 23:43:33 ERROR Executor: Exception in task ID 0
java.io.IOException: Could not find a serializer for the Key class: 'java.lang.String'. Please ensure that the configuration 'io.serializations' is properly configured, if you're usingcustom serialization.
    at org.apache.hadoop.io.SequenceFile$Writer.init(SequenceFile.java:1176)
    at org.apache.hadoop.io.SequenceFile$Writer.<init>(SequenceFile.java:1091)

Does anyone have any idea? Thank you!

1

There are 1 answers

0
Thamme Gowda On

Change this:

JavaPairRDD<String, String> infile = ctx.wholeTextFiles("input_txt");
infile.saveAsNewAPIHadoopFile("outfile.seq", String.class, String.class, SequenceFileOutputFormat.class);

to

JavaPairRDD<String, String> infile = ctx.wholeTextFiles("input_txt");
JavaPairRDD<Text, Text> resultRDD = infile.mapToPair(f -> new Tuple2<>(new Text(f._1()), new Text(f._2())));
resultRDD.saveAsNewAPIHadoopFile("outfile.seq", Text.class, Text.class, SequenceFileOutputFormat.class);