HBase常用功能和HBase+MapReduce使用總結
1.HBase如果加了列限定,如果該列不存在時返回的結果為empty.
看下面的代碼:
Get get = new Get(Bytes.toBytes("100"));
get.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name")); 這里加入了列限定,也就是只返回列族info下面的name字段。但是如果name字段根本不存在,返回的Result在調用result.isEmpty()時則返回為true,也就是說就算其他字段存在,也什么都沒返回來,包括rowkey也沒有返回來。當然,如果是限定多個列,只要一個列存在就可以正常返回。所以需要注意。
2.HBase在scan時指定的StartRow里面不能加-
看下面的代碼:
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes("3136947-"));
scan.setStopRow(Bytes.toBytes("3136947-" + 1));我的本意是查詢rowkey以 3136947- 開頭的行,但是因為我的里面有一個-(“杠”),所以什么都沒返回,去掉-后正常。這說明這里是不能使用-,-也并不是轉義字符,轉義后也還是scan不出來的。不知道其他字符是不是也不行,沒有測試。 所以需要注意。
3.HBase在scan時過濾掉指定列不存在的記錄
如果想返回某個字段必須存在的行,不存在該字段的記錄過濾掉不返回,方法如下:
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes("3136947"));
scan.setStopRow(Bytes.toBytes("3136947" + 1));
scan.addColumn(Bytes.toBytes("info"),
Bytes.toBytes("name"));
SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("info"),
Bytes.toBytes("name"),
CompareFilter.CompareOp.NOT_EQUAL, Bytes.toBytes("0"));
filter.setFilterIfMissing(true);
scan.setFilter(filter);
這里的過濾器里面指定該列的字段值必須不等于0(當然,如果你的name里有等于0的當然不能使用0),并且設置setFilterIfMissing為true,也就是設置為如果該列不存在就過濾掉這條數據,默認為false。
4.利用MapReduce導出hbase數據
如果hbase作為數據的輸出,job設置如下:
Configuration conf = HBaseConfiguration.create();
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes("3136947"));
scan.setStopRow(Bytes.toBytes("3136947" + 1));
scan.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"));
scan.addFamily(UserStoreHelper.FAMILY_INFO);
scan.addColumn(UserStoreHelper.FAMILY_INFO, UserStoreHelper.USER_ID);
scan.addColumn(UserStoreHelper.FAMILY_INFO, UserStoreHelper.FRIENDS);
scan.addColumn(UserStoreHelper.FAMILY_INFO, UserStoreHelper.LEVEL_CODE);
final Job job = new Job(conf, "exportHBaseUser");
job.setJarByClass(TestJobCreator.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileOutputFormat.setOutputPath(job, new Path("test1"));
// job.setReducerClass(HbaseExportReduce.class);
// job.setPartitionerClass(UserPartitioner.class);
// job.setNumReduceTasks(14);
TableMapReduceUtil.initTableMapperJob(Bytes.toBytes("usertable"),
scan,
TestMapper.class,
Text.class,
NullWritable.class,
job);
5.利用mapReduce插入數據到HBase
如果hbase作為數據的輸入。代碼如下:
final Configuration conf = HBaseConfiguration.create();
final Job job = new Job(conf, "Sync-To-HBase");
job.setJarByClass(PostStoreExportHBaseJobCreator.class);
//我這里是以mongodb為輸入
job.setInputFormatClass(MongoInputFormat.class);
TableMapReduceUtil.initTableReducerJob("usertable", null, job);
//把數據轉換為hbase表格式的map
job.setMapperClass(TestMapper.class);
//直接入hbase庫不需要reduce
job.setNumReduceTasks(0);
這里map的輸出必須是key為ImmutableBytesWritable,value為 Put
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!