MapReduce資料型別及自定義MapReduce資料型別
阿新 • • 發佈:2019-01-27
MapReduce資料型別
資料型別都要實現Writable介面,以便用這些型別定義的資料可以被序列化進行網路傳輸和檔案儲存。自定義key資料型別的時候,因為需要對key進行排序,需要繼承java中的比較器,所以可以直接繼承WritableComparable(WritableComparable繼承了Writable和Comparable)。
基本資料型別:
- BooleanWritable
- ByteWritable
- DoubleWritable
- FloatWritable
- IntWritable
- LongWritable
- Text
- NullWritable:當
自定義MapReduce資料型別
1、實現Writable介面
重寫 write()和readFields()方法
2、實現WritableComparable介面
重寫 write(),readFields()和compareTo()方法,compareTo()方法使用者shuffle過程中根據key排序時使用。
注意:以上兩種方式在使用的使用都需要進行重寫重寫toString(), hashCode(), equals()
具體的自定義資料型別的程式碼如下:
public class UserWritable implements WritableComparable <UserWritable>{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserWritable() {
}
public UserWritable(int id, String name) {
set(id, name);
}
public void set(int id, String name) {
this.setId(id);
this.setName(name);
}
//注意!!!:此兩個方法讀寫欄位的順序必須保持一致,不一致將會出錯
public void readFields(DataInput in) throws IOException {
this.id = in.readInt();
this.name = in.readUTF();
}
public void write(DataOutput out) throws IOException {
out.writeInt(id);
out.writeUTF(name);
}
public int compareTo(UserWritable o) {
int comp = Integer.valueOf(this.getId()).compareTo(o.getId());
if(0 != comp)
return comp;
return this.getName().compareTo(o.getName());
}
@Override
public String toString() {
return id +"\t"+ name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserWritable that = (UserWritable) o;
if (id != that.id) return false;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}