关于reduce中遍历2次数据的问题
關于reduce中遍歷2次數據的問題
@(HADOOP)[hadoop]
reduce方法的javadoc中已經說明了可能會出現的問題:
The framework calls this method for each (key, (list of values)) pair in the grouped inputs. Output values must be of the same type as input values. Input keys must not be altered. The framework will reuse the key and value objects that are passed into the reduce, therefore the application should clone the objects they want to keep a copy of.
也就是說雖然reduce方法會反復執行多次,但key和value相關的對象只有兩個,reduce會反復重用這兩個對象。所以如果要保存key或者value的結果,只能將其中的值取出另存或者重新clone一個對象(例如Text store = new Text(value) 或者 String a = value.toString()),而不能直接賦引用。因為引用從始至終都是指向同一個對象,你如果直接保存它們,那最后它們都指向最后一個輸入記錄。會影響最終計算結果而出錯。
解決辦法:先用一個HashSet將values的各個值保存下來,然后再遍歷這個HashSet。
@Overrideprotected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {Set<String> outputValues = new HashSet<>();int sum = 0;//計算某個UDID在某個時間段出現LBS信息的總次數。for(Text value : values){outputValues.add(value.toString());String[] valueContent = value.toString().trim().split(TAB_SEPERATOR);int count = Integer.parseInt(valueContent[2]);sum += count;}//debug log//注意:reduce中key/value對象重用的問題:https://my.oschina.net/leejun2005/blog/131744if(sum >= LBS_FREQUENCE_THREADHOLD_TO_RETAIN){for(String value : outputValues){context.write(key, new Text(value));}}}詳細可參考:https://my.oschina.net/leejun2005/blog/131744
總結
以上是生活随笔為你收集整理的关于reduce中遍历2次数据的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spark 2.x ML概念与应用
- 下一篇: 关于LBS坐标系与精度的问题