3
votes

I am trying to read in a Hbase atomic increment column into Pig and have access to it as Long value.

However, the column value uses Hbases Hex like structure: \x00\x00\x00\x00\x00\x00\x00\x01

Does anyone know of a method to convert that in Pig to become equivilant to the get_counter value: 1

I have posted a solution using a UDF:

import java.io.IOException;
import org.apache.pig.EvalFunc;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;


public class ConvertToLong extends EvalFunc<Long> {

@Override
public Long exec(Tuple input) throws IOException {

    if (input == null || input.size() == 0) {
        return null;
    }

    try {

        long value = 0;
        DataByteArray dba = (DataByteArray)input.get(0);
        System.out.println( dba.toString() );
        byte[] ba = dba.get();

        for (int i = 0; i < ba.length; i++)
        {
            value = (value << 8) + (ba[i] & 0xff);
        }
        return value;
        //return value;
    } catch (ExecException e) {
        log.warn("Error reading input: " + e.getMessage());
        return 3L;
    } catch( Exception e ){
        log.warn("Error:" + e.getMessage() );
        return 2L;
    }
}

@Override
public Schema outputSchema(Schema input) {
    return new Schema(new Schema.FieldSchema(null, DataType.LONG));
}
}
2
Even without caster=HBaseBinaryConverter, you could have use simpler code to interpret byte array as a long: return Bytes.toLong(ba);Guillaume Perrot

2 Answers

7
votes

You do not need an UDF to load long integers from HBase. You can rely on the -caster=HBaseBinaryConverter option on HBaseStorage.

Example: I have a table named counters, the value is stored under the val:val column (using the increment feature which stores data as 8 bytes long). To list all the counters in PIG:

counters = LOAD 'hbase://counters' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('val:val', '-caster=HBaseBinaryConverter -loadKey') AS (key:chararray, val:long);
DUMP counters
0
votes

I have never used HBaseStorage so I am not sure, but you can try the following approaches:

Try reading it as a long:

data = LOAD 'your/path' USING HBaseStorage(...) AS (x:long);

If that doesn't work, try this:

data = LOAD 'your/path' USING HBaseStorage(...)
data = FOREACH data GENERATE (long) $1 AS x;

Otherwise, you can always write a UDF that would do the conversion:

data = LOAD 'your/path' USING HBaseStorage(...);
data = FOREACH data GENERATE ConvertToLong($1) as x;