Fakhar uz Zaman
Fakhar uz Zaman

Reputation: 299

Composite Key in HBase

I am new to HBase and have to use composite-key as primary-key. Please tell me

How to make composite-key in hbase?
And How to search a record using that composite-key?

Upvotes: 2

Views: 6323

Answers (2)

Adelin
Adelin

Reputation: 18961

For me the best way to do this is use Orderly. It is a library that help you to create composite keys and sort them. Link to Orderly . You can also use it in scan operation where you set up start and stop row key.

Upvotes: 0

Tariq
Tariq

Reputation: 34184

Just join the parts of your key and use it. Nothing special. Suppose your have a customer table and you want to have a rowkey which consists of CustID and Timestamp. And then you want to fetch all the results for a particular user, irrespective of the timestamp. You would do something like this :

public static void main(String[] args) throws IOException {

    Configuration conf = HBaseConfiguration.create();
    HTable table = new HTable(conf, "demo");
    String CustID = "tar024";
    byte[] rowKey = Bytes.add(Bytes.toBytes(CustID), Bytes.toBytes(System.currentTimeMillis()));

    //Put the data
    Put p = new Put(rowKey);
    System.out.println(Bytes.toString(rowKey));
    p.add(Bytes.toBytes("cf"), Bytes.toBytes("c1"), Bytes.toBytes("VALUE"));
    table.put(p);

    //Get the data
    Scan s = new Scan();
    Filter filter = new PrefixFilter(Bytes.toBytes("tar024"));
    s.setFilter(filter);
    ResultScanner rs = table.getScanner(s);
    for(Result r : rs){
        System.out.println("VALUE : " + Bytes.toString(r.getValue(Bytes.toBytes("cf"), Bytes.toBytes("c1"))));
    }
    rs.close();
    table.close();
}

HTH

Upvotes: 6

Related Questions