Saturday, 5 January 2013

HBase REST From C#

HBase supports REST for non-Java front-ends.

To start hbase rest server use the below command.
hbase rest start [The REST server start listening at 8080].

We can define our port using the below command.
hbase rest start -p 9090

Create a table user with column family info.

create 'user','info'

Now use the REST API to insert data into the user table.

//Create the HttpWebrequest object with the HBase rest url.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://---:8080/User/1");

//Method type is POST.
request.Method = "POST";

//Contenet type is JSON.Set this to application/json if you send json data.Otherwise you get error like Unsupported Media Type.
request.ContentType = "application/json";

//To store data in HBase the rowkey,column,columnvalue should be in the Base64String.

//Id column.
string idcolumn = System.Convert.ToBase64String(Encoding.UTF8.GetBytes("info:id"));
string idvalue = System.Convert.ToBase64String(Encoding.UTF8.GetBytes("1"));

//Name column.
string namecolumn = System.Convert.ToBase64String(Encoding.UTF8.GetBytes("info:name"));
string namevalue = System.Convert.ToBase64String(Encoding.UTF8.GetBytes("A"));

string rowkey = System.Convert.ToBase64String(Encoding.UTF8.GetBytes("1"));

//I had used the JSON.NET to construct the json string.
JObject objrow = new JObject();
JProperty key = new JProperty("key", rowkey);
JArray arr = new JArray();
JObject objcolum1 = new JObject();
objcolum1.Add(new JProperty("column", idcolumn));
objcolum1.Add(new JProperty("$", idvalue));
JObject objcolum2 = new JObject();
objcolum2.Add(new JProperty("column", namecolumn));
objcolum2.Add(new JProperty("$", namevalue));
JProperty cell = new JProperty("Cell", arr);
JObject main = new JObject();
JProperty row = new JProperty("Row", objrow);

//Get the json string.
string input = main.ToString();

//Get bytes.
byte[] by = Encoding.Default.GetBytes(input);

//Set the content length.
request.ContentLength = by.Length;

//Get the request stream.
Stream stream = request.GetRequestStream();

//Write bytes to stream.
stream.Write(by, 0, by.Length);

//Execute the request.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

//Get the response stream.
Stream responsestream = response.GetResponseStream();

//Read the response.
using (StreamReader reader = new StreamReader(responsestream))
     //Read the response.
     string res = reader.ReadToEnd();

     //Write the response.

Now you can see the data in hbase user table.

1 comment:

  1. Helped me a lot, thank you!
    Strange thing is, that I seem to be able to do most operations with the StarGate RESR API - besides creating a scanner - that always leads to error 400. Any insights there?