| 10 | | 如果采用HBASE设计,ROW设计为<userid><reverse_order_stamp><actionid> |
| | 10 | 如果采用HBASE设计,ROW设计为<userid><reverse_order_stamp><actionid>[[BR]] |
| | 11 | 之所以采用row-per-action而不是row-per-user,主要考虑采用row自身的索引进行查询[[BR]] |
| | 12 | |
| | 13 | {{{ |
| | 14 | public static byte [] makeActionRow(int userid, long stamp, int actionid) |
| | 15 | throws Exception { |
| | 16 | byte [] useridBytes = Bytes.toBytes(userid); |
| | 17 | byte [] stampBytes = Bytes.toBytes(stamp); |
| | 18 | byte [] actionidBytes = Bytes.toBytes(actionid); |
| | 19 | return Bytes.add(useridBytes, stampBytes, actionidBytes); |
| | 20 | } |
| | 21 | |
| | 22 | public static Action readActionRow(byte [] row) |
| | 23 | throws Exception { |
| | 24 | // Bytes.toInt(byte [] buf, int offset, int length) |
| | 25 | int userid = Bytes.toInt(row,0,4); |
| | 26 | long stamp = Long.MAX_VALUE - Bytes.toLong(row,4,8); |
| | 27 | int actionid = Bytes.toInt(row,12,4); |
| | 28 | return new Action(userid,stamp,actionid); |
| | 29 | } |
| | 30 | }}} |
| | 31 | |
| | 32 | 插入操作 |
| | 33 | {{{ |
| | 34 | |
| | 35 | public static void putUserAction(Action action) throws Exception { |
| | 36 | // Get the fields from the Action object |
| | 37 | int userid = action.getUserID(); |
| | 38 | long stamp = Long.MAX_VALUE - action.getStamp(); |
| | 39 | int actionid = action.getID(); |
| | 40 | String name = action.getName(); |
| | 41 | |
| | 42 | // Build the composite row, column, and value |
| | 43 | byte [] row = makeActionRow(userid,stamp,actionid); |
| | 44 | byte [] column = Bytes.toBytes("content:name"); |
| | 45 | byte [] value = Bytes.toBytes(name); |
| | 46 | |
| | 47 | // Insert to HBase |
| | 48 | HTable ht = new HTable("useractions"); |
| | 49 | BatchUpdate bu = new BatchUpdate(row); |
| | 50 | bu.put(column,value) |
| | 51 | ht.commit(bu); |
| | 52 | } |
| | 53 | }}} |