TECH SOLUTIONS

Click here to edit subtitle

Forums

Post Reply
Forum Home > Bigdata Learnings( Hadoop, HBase,Hive and other bigdata technologies) > Cassandra:Write data into table using Thrift API

Sourav Gulati
Site Owner
Posts: 83

Lets take an example, we have a following file :

$ cat test

row-1 colfam1 quan1 val1

row-2 colfam1 quan2 val2

 


Now , we have a table(columnfamily) in Cassandra "hbtable" in "mykeyspace' ,in which we have to load the data from this file . We have four columns in this table  (rowkey , cf , quantifier,value) with data type varchar .


Following is example of loading data in to this table using Cassandra Thrift API:


 

public class SimpleWriteThrift {

private static final String UTF8 = "UTF8";

private static final String HOST = "192.168.1.11";

private static final int PORT = 9160;

private static final ConsistencyLevel CL = ConsistencyLevel.ALL;

private static final String FILEPATH="/home/user/test";

 


public static void main(String[] args) throws InvalidRequestException, TException, UnavailableException, TimedOutException, IOException {

TTransport tr = new TSocket(HOST,PORT);

TFramedTransport tf = new TFramedTransport(tr);

TProtocol proto = new TBinaryProtocol(tf);

Cassandra.Client client = new Cassandra.Client(proto);

tf.open();


client.set_keyspace("mykeyspace");

String cfName= "hbtable";

long timestamp =System.currentTimeMillis();

ColumnParent cp = new ColumnParent(cfName);

BufferedReader br = new BufferedReader(new FileReader(FILEPATH));


String line;

Column c = new Column();

while ( (line=br.readLine())!=null)

{

String [] columns=line.split("\\s");


ByteBuffer userIDKey=ByteBuffer.wrap(columns[0].getBytes());

c.setName("cf".getBytes());

c.setValue(columns[1].getBytes());

c.setTimestamp(timestamp);

client.insert(userIDKey, cp,c, CL);

c.setName("quantifier".getBytes());

c.setValue(columns[2].getBytes());

c.setTimestamp(timestamp);

client.insert(userIDKey, cp,c, CL);

c.setName("value".getBytes());

c.setValue(columns[3].getBytes());

c.setTimestamp(timestamp);

client.insert(userIDKey, cp,c, CL);

}


tf.close();

System.out.println("Data inserted");

 


Lets check it now in Cassandra :


cqlsh:mykeyspace>select * from hbtable;

rowkey | cf | quantifier | value

--------+---------+------------+-------

row-2 | colfam1 | quan2 | val2

row-1 | colfam1 | quan1 | val1

 





Click here for Other topics of BigData Technologies

 

Tags: Load Data into Cassandra table

          Insert Data into Cassandra table
          

 

March 5, 2013 at 12:25 PM Flag Quote & Reply

You must login to post.