最近有个业务是想从商品数据中解析出需要的关键词。关键词来自一个词库,词库文件包括产品类目词、菜品词等等。选择用阿里云Max Compute 的Map Reduce(MR)来实现。
开始以为MR不能读取文件,后来发现是可以读取的。参考:https://help.aliyun.com/document_detail/27891.html
try {
byte[] buffer = new byte[1024 * 1024];
int bytesRead = 0;
bufferedInput = context.readResourceFileAsStream("category_words.txt");
while ((bytesRead = bufferedInput.read(buffer)) != -1) {
String line = new String(buffer, 0, bytesRead);
String[] lines = line.split("\n");
for (String chunk : lines) {
dictSet.add(chunk);
//System.out.println("add word:" + chunk);
}
}
bufferedInput.close();
filter = new SensitivewordFilter(dictSet);
} catch (FileNotFoundException ex) {
throw ex;
} catch (IOException ex) {
System.err.print(ex.getStackTrace().toString());
} finally {
}
注意用context.readResourceFileAsStream 一次就把文件的全部字符读取出来,然后自己分行。分行之后在处理填写到自己的词表里面。
注意:byte[] buffer = new byte[1024 * 1024] ,我先开了一个1M内存的空间,一次把全部文件读入。
命令行传入输入和输出表参数:
public static void main(String[] args) throws java.lang.Exception {
if (args.length != 2) {
System.err.println("Usage: WordCount <in_table> <out_table>");
System.exit(2);
}
JobConf job = new JobConf();
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(SumCombiner.class);
job.setReducerClass(SumReducer.class);
//arg[0] : projectxxx.dwd_input_table.dt=20170601
System.out.println(args[0]);
String []arr = args[0].split("-");
String inputProject = arr[0];
String table = arr[1];
String part = arr[2];
job.setMapOutputKeySchema(SchemaUtils.fromString("mall_id:string,mall_name:string,shop_id:string,shop_name:string,word:string"));
job.setMapOutputValueSchema(SchemaUtils.fromString("count:bigint"));
InputUtils.addTable(TableInfo.builder().projectName(inputProject).tableName(table).partSpec(part).build(), job);
OutputUtils.addTable(TableInfo.builder().tableName(args[1]).build(), job);
JobClient.runJob(job);
}
通过Idea打jar之后,jar需要上传到阿里云资源组里面。
然后自己的笔记本上可以用ODPS 命令行执行 odps任务, 参考: https://yq.aliyun.com/articles/1487
命令:
jar -resources ChoseWords.jar,category_words.txt -classpath /Users/xxx/IdeaProjects/ChoseWords/out/artifacts/ChoseWords_jar/ChoseWords.jar com.aliyun.odps.mapred.open.example.WordCount projectxxx-dwd_input_table-dt=20170601 dwd_shop_tags;
上面输入表的project,table 和partition放在一个参数里面,自己在程序里面切分。
最后当我们想把数据放在阿里云任务调度中执行,设置好mapper,reducer和combiner就可以执行。注意mapper 最后一个类前面是$符合,不是dot。有点坑爹。