java hbase jruby

java - ¿Cómo eliminar masivamente múltiples filas en hbase?



jruby (2)

Tengo las siguientes filas con estas claves en la tabla hbase "mytable"

user_1 user_2 user_3 ... user_9999999

Quiero usar el shell de Hbase para eliminar filas de:

usuario_500 a usuario_900

Sé que no hay manera de eliminar, pero ¿hay alguna manera de que pueda usar el "BulkDeleteProcessor" para hacer esto?

Veo aquí:

https://github.com/apache/hbase/blob/master/hbase-examples/src/test/java/org/apache/hadoop/hbase/coprocessor/example/TestBulkDeleteProtocol.java

Solo quiero pegar las importaciones y luego pegar esto en el shell, pero no tengo idea de cómo hacerlo. ¿Alguien sabe cómo puedo usar este punto final desde el shell jruby hbase?

Table ht = TEST_UTIL.getConnection().getTable("my_table"); long noOfDeletedRows = 0L; Batch.Call<BulkDeleteService, BulkDeleteResponse> callable = new Batch.Call<BulkDeleteService, BulkDeleteResponse>() { ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<BulkDeleteResponse> rpcCallback = new BlockingRpcCallback<BulkDeleteResponse>(); public BulkDeleteResponse call(BulkDeleteService service) throws IOException { Builder builder = BulkDeleteRequest.newBuilder(); builder.setScan(ProtobufUtil.toScan(scan)); builder.setDeleteType(deleteType); builder.setRowBatchSize(rowBatchSize); if (timeStamp != null) { builder.setTimestamp(timeStamp); } service.delete(controller, builder.build(), rpcCallback); return rpcCallback.get(); } }; Map<byte[], BulkDeleteResponse> result = ht.coprocessorService(BulkDeleteService.class, scan .getStartRow(), scan.getStopRow(), callable); for (BulkDeleteResponse response : result.values()) { noOfDeletedRows += response.getRowsDeleted(); } ht.close();

Si no hay forma de hacerlo a través de JRuby, está bien Java o una forma alternativa de eliminar rápidamente varias filas.


¿Realmente quieres hacerlo en shell porque hay otras formas mejores? Una forma es usar la API nativa de java

  • Construye una lista de eliminaciones
  • pasar esta lista de matriz a Table.delete método

Método 1: si ya conoces el rango de teclas.

public void massDelete(byte[] tableName) throws IOException { HTable table=(HTable)hbasePool.getTable(tableName); String tablePrefix = "user_"; int startRange = 500; int endRange = 999; List<Delete> listOfBatchDelete = new ArrayList<Delete>(); for(int i=startRange;i<=endRange;i++){ String key = tablePrefix+i; Delete d=new Delete(Bytes.toBytes(key)); listOfBatchDelete.add(d); } try { table.delete(listOfBatchDelete); } finally { if (hbasePool != null && table != null) { hbasePool.putTable(table); } } }

Método 2: si desea realizar una eliminación por lotes sobre la base de un resultado de escaneo.

public bulkDelete(final HTable table) throws IOException { Scan s=new Scan(); List<Delete> listOfBatchDelete = new ArrayList<Delete>(); //add your filters to the scanner s.addFilter(); ResultScanner scanner=table.getScanner(s); for (Result rr : scanner) { Delete d=new Delete(rr.getRow()); listOfBatchDelete.add(d); } try { table.delete(listOfBatchDelete); } catch (Exception e) { LOGGER.log(e); } }

Ahora vamos a usar un CoProcessor. solo un consejo, ''NO UTILICE CoProcessor'' a menos que sea un experto en HBase. Los CoProcessors tienen muchos problemas incorporados si lo necesita, puedo proporcionarle una descripción detallada. En segundo lugar, cuando borra algo de HBase, nunca se elimina directamente de Hbase, hay un marcador de lápida que se adjunta a ese registro y luego, durante una compactación importante, se elimina, por lo que no es necesario utilizar un coprocesador que es altamente exhaustivo en recursos.

Código modificado para soportar la operación por lotes.

int batchSize = 50; int batchCounter=0; for(int i=startRange;i<=endRange;i++){ String key = tablePrefix+i; Delete d=new Delete(Bytes.toBytes(key)); listOfBatchDelete.add(d); batchCounter++; if(batchCounter==batchSize){ try { table.delete(listOfBatchDelete); listOfBatchDelete.clear(); batchCounter=0; } }}

Creando HBase conf y obteniendo instancia de tabla.

Configuration hConf = HBaseConfiguration.create(conf); hConf.set("hbase.zookeeper.quorum", "Zookeeper IP"); hConf.set("hbase.zookeeper.property.clientPort", ZookeeperPort); HTable hTable = new HTable(hConf, tableName);


Si ya conoce las claves de fila de los registros que desea eliminar de la tabla HBase, puede utilizar el siguiente enfoque

1. Primero crea una lista de objetos con estas teclas de fila

for (int rowKey = 1; rowKey <= 10; rowKey++) { deleteList.add(new Delete(Bytes.toBytes(rowKey + ""))); }

2. Luego obtenga el objeto Table utilizando HBase Connection

Table table = connection.getTable(TableName.valueOf(tableName));

3.Una vez que tenga el objeto de tabla, llame a delete () pasando la lista

table.delete(deleteList);

El código completo se verá a continuación.

Configuration config = HBaseConfiguration.create(); config.addResource(new Path("/etc/hbase/conf/hbase-site.xml")); config.addResource(new Path("/etc/hadoop/conf/core-site.xml")); String tableName = "users"; Connection connection = ConnectionFactory.createConnection(config); Table table = connection.getTable(TableName.valueOf(tableName)); List<Delete> deleteList = new ArrayList<Delete>(); for (int rowKey = 500; rowKey <= 900; rowKey++) { deleteList.add(new Delete(Bytes.toBytes("user_" + rowKey))); } table.delete(deleteList);