title: Reading Avro records out of HBase in Java
body: <p>I have a complicated Avro record (nested records, unioned types) that I store as a value in HBase.  I read in an Avro data file using a schema that currently matches the file's writer schema and the records that are in HBase:</p>
  
  <pre><code>Schema schema = new Schema.Parser().parse(schema_file);
  DatumReader&lt;GenericRecord&gt; datumReader = new SpecificDatumReader&lt;GenericRecord&gt;(schema);
  DataFileReader&lt;GenericRecord&gt; dataFileReader = new DataFileReader&lt;GenericRecord&gt;(avro_file, datumReader);
  GenericRecord record = null;
  record = dataFileReader.next(record);
  </code></pre>
  
  <p>I then check HBase to see if a record with the same rowkey already exists.  The val returned by my get is the byte array representation of the Avro record:</p>
  
  <pre><code>Configuration conf = HBaseConfiguration.create();
  HTable table = new HTable(conf, "table");
  String pk = new String(record.get("x").toString()+record.get("y").toString());
  Get get = new Get(Bytes.toBytes(pk));
  Result result = table.get(get);
  byte[] val = result.getValue(Bytes.toBytes("c"),Bytes.toBytes("c"));
  </code></pre>
  
  <p>If there's no record in HBase with the same rowkey, I put the record in:</p>
  
  <pre><code>if (val == null) {
    System.out.println("pk: "+pk+" does not exist");
    Put put = new Put(Bytes.toBytes(pk));
    put.add(Bytes.toBytes("c"), Bytes.toBytes("c"), Bytes.toBytes(record.toString()));
    try {
      table.put(put);
    } catch (Exception e) {
      System.err.println("Can't put to table: " + e);
    }
  }
  else {
    System.out.println("pk: "+pk+" does exist");
    //help me!
  }
  </code></pre>
  
  <p>If there is a record in HBase with the same rowkey, I want to convert the HBase result's byte array back into   the Avro schema and then compare a couple of the fields to see which record is 'better'.  I'd like to put the 'better' record into HBase, but I'm stuck.  How do I convert the byte array from HBase into a GenericRecord so I can compare fields between my file record and the HBase one?</p>