Differences between revisions 93 and 94
Revision 93 as of 2011-11-16 03:54:36
Size: 29318
Editor: DaveBrosius
Comment:
Revision 94 as of 2013-11-15 17:41:56
Size: 29379
Editor: GehrigKunz
Comment: statcounter
Deletions are marked like this. Additions are marked like this.
Line 757: Line 757:

{{https://c.statcounter.com/9397521/0/fe557aad/1/|stats}}

If you are new to Cassandra and just want to get started, take a look at the available clients ClientOptions (v0.6) instead.

This page shows examples of using the low-level Thrift interface, primarily intended for client library developers.

To generate the bindings for a particular language, first find out if Thrift supports that language. If it does, you can run "thrift --gen XYZ interface/cassandra.thrift" for whatever XYZ you fancy.

These examples are for Cassandra 0.5 and 0.6.

As of 0.7 and later, the default thrift transport is TFramedTransport so if you get an error such as "No more data to read", switch transports.

PHP

Before working with Cassandra and PHP make sure that your PHP installation has APC enabled. If it does not please re-compile PHP and then recompile Thrift. APC drastically increases the performance of Thrift Interface.

To create Cassandra.php and cassandra_types.php you must use thrift -gen php interface/cassandra.thrift of the cassandra package the rest of these files come from the main thrift package.

<?php
$GLOBALS['THRIFT_ROOT'] = '/usr/share/php/Thrift';
require_once $GLOBALS['THRIFT_ROOT'].'/packages/cassandra/Cassandra.php';
require_once $GLOBALS['THRIFT_ROOT'].'/packages/cassandra/cassandra_types.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TFramedTransport.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';

try {
  // Make a connection to the Thrift interface to Cassandra
  $socket = new TSocket('127.0.0.1', 9160);
  $transport = new TBufferedTransport($socket, 1024, 1024);
  $protocol = new TBinaryProtocolAccelerated($transport);
  $client = new CassandraClient($protocol);
  $transport->open();


  /* Insert some data into the Standard1 column family from the default config */

  // Keyspace specified in storage=conf.xml
  $keyspace = 'Keyspace1';

  // reference to specific User id
  $keyUserId = "1";

  // Constructing the column path that we are adding information into.
  $columnPath = new cassandra_ColumnPath();
  $columnPath->column_family = 'Standard1';
  $columnPath->super_column = null;
  $columnPath->column = 'email';

  // Timestamp for update
  $timestamp = time();

  // We want the consistency level to be ZERO which means async operations on 1 node
  $consistency_level = cassandra_ConsistencyLevel::ZERO;

  // Add the value to be written to the table, User Key, and path.
  $value = "foobar@example.com";
  $client->insert($keyspace, $keyUserId, $columnPath, $value, $timestamp, $consistency_level);

  // Add a new column path to be altered.
  $columnPath->column = 'age';
  //Get a current timestamp
  $timestamp = time();
  // Update the value to be inserted for the updated column Path
  $value = "24";
  $client->insert($keyspace, $keyUserId, $columnPath, $value, $timestamp, $consistency_level);

  /*
   * use batch_insert to insert a supercolumn and its children using the standard config
   * builds the structure
   *
   * Super1 : {
   *    KeyName : {
   *       SuperColumnName : {
   *            foo : fooey value
   *            bar : bar like thing
   *       }
   *    }
   * }
   */

  // build columns to insert
  $column1 = new cassandra_Column();
  $column1->name = 'foo';
  $column1->value = 'fooey value';
  $column1->timestamp = time();

  $column2 = new cassandra_Column();
  $column2->name = 'bar';
  $column2->value = 'bar like thing';
  $column2->timestamp = time();

  // build super column containing the columns
  $super_column = new cassandra_SuperColumn();
  $super_column->name = 'SuperColumnName';
  $super_column->columns = array($column1, $column2);

  // create columnorsupercolumn holder class that batch_insert uses
  $c_or_sc = new cassandra_ColumnOrSuperColumn();
  $c_or_sc->super_column = $super_column;

  // create the mutation (a map of ColumnFamily names to lists ColumnsOrSuperColumns objects
  $mutation['Super1'] = array($c_or_sc);

  $client->batch_insert($keyspace, 'KeyName', $mutation, $consistency_level);

  /* Query for data */

  // Specify what Column Family to query against.
  $columnParent = new cassandra_ColumnParent();
  $columnParent->column_family = "Standard1";
  $columnParent->super_column = NULL;


  $sliceRange = new cassandra_SliceRange();
  $sliceRange->start = "";
  $sliceRange->finish = "";
  $predicate = new cassandra_SlicePredicate();
  list() = $predicate->column_names;
  $predicate->slice_range = $sliceRange;

  // We want the consistency level to be ONE which means to only wait for 1 node
  $consistency_level = cassandra_ConsistencyLevel::ONE;

  // Issue the Query
  $keyUserId = 1;
  $result = $client->get_slice($keyspace, $keyUserId, $columnParent, $predicate, $consistency_level);


  print_r($result);
  $transport->close();



} catch (TException $tx) {
   print 'TException: '.$tx->why. ' Error: '.$tx->getMessage() . "\n";
}
?>

Java

   1 import java.util.List;
   2 import java.io.UnsupportedEncodingException;
   3 
   4 import org.apache.thrift.transport.TTransport;
   5 import org.apache.thrift.transport.TFramedTransport;
   6 import org.apache.thrift.transport.TSocket;
   7 import org.apache.thrift.protocol.TProtocol;
   8 import org.apache.thrift.protocol.TBinaryProtocol;
   9 import org.apache.thrift.TException;
  10 import org.apache.cassandra.service.*;
  11 
  12 public class CClient
  13 {
  14     public static void main(String[] args)
  15     throws TException, InvalidRequestException, UnavailableException, UnsupportedEncodingException, NotFoundException
  16     {
  17         TTransport tr = new TFramedTransport(new TSocket("localhost", 9160));
  18         TProtocol proto = new TBinaryProtocol(tr);
  19         Cassandra.Client client = new Cassandra.Client(proto);
  20         tr.open();
  21 
  22         String key_user_id = "1";
  23 
  24         // insert data
  25         long timestamp = System.currentTimeMillis();
  26         client.insert("Keyspace1",
  27                       key_user_id,
  28                       new ColumnPath("Standard1", null, "name".getBytes("UTF-8")),
  29                       "Chris Goffinet".getBytes("UTF-8"),
  30                       timestamp,
  31                       ConsistencyLevel.ONE);
  32         client.insert("Keyspace1",
  33                       key_user_id,
  34                       new ColumnPath("Standard1", null, "age".getBytes("UTF-8")),
  35                       "24".getBytes("UTF-8"),
  36                       timestamp,
  37                       ConsistencyLevel.ONE);
  38 
  39         // read single column
  40         ColumnPath path = new ColumnPath("Standard1", null, "name".getBytes("UTF-8"));
  41         System.out.println(client.get("Keyspace1", key_user_id, path, ConsistencyLevel.ONE));
  42 
  43         // read entire row
  44         SlicePredicate predicate = new SlicePredicate(null, new SliceRange(new byte[0], new byte[0], false, 10));
  45         ColumnParent parent = new ColumnParent("Standard1", null);
  46         List<ColumnOrSuperColumn> results = client.get_slice("Keyspace1", key_user_id, parent, predicate, ConsistencyLevel.ONE);
  47         for (ColumnOrSuperColumn result : results)
  48         {
  49             Column column = result.column;
  50             System.out.println(new String(column.name, "UTF-8") + " -> " + new String(column.value, "UTF-8"));
  51         }
  52 
  53         tr.close();
  54     }
  55 }

Same example as above but working with cassandra version 0.6.0 beta

   1 package cassandra.clientest;
   2 
   3 import java.io.UnsupportedEncodingException;
   4 import java.util.Date;
   5 import java.util.List;
   6 
   7 import org.apache.cassandra.thrift.Cassandra;
   8 import org.apache.cassandra.thrift.Column;
   9 import org.apache.cassandra.thrift.ColumnOrSuperColumn;
  10 import org.apache.cassandra.thrift.ColumnParent;
  11 import org.apache.cassandra.thrift.ColumnPath;
  12 import org.apache.cassandra.thrift.ConsistencyLevel;
  13 import org.apache.cassandra.thrift.InvalidRequestException;
  14 import org.apache.cassandra.thrift.NotFoundException;
  15 import org.apache.cassandra.thrift.SlicePredicate;
  16 import org.apache.cassandra.thrift.SliceRange;
  17 import org.apache.cassandra.thrift.TimedOutException;
  18 import org.apache.cassandra.thrift.UnavailableException;
  19 import org.apache.thrift.TException;
  20 import org.apache.thrift.protocol.TBinaryProtocol;
  21 import org.apache.thrift.protocol.TProtocol;
  22 import org.apache.thrift.transport.TSocket;
  23 import org.apache.thrift.transport.TTransport;
  24 
  25 public class Main {
  26 
  27         public static final String UTF8 = "UTF8";
  28 
  29         public static void main(String[] args) throws UnsupportedEncodingException,
  30                         InvalidRequestException, UnavailableException, TimedOutException,
  31                         TException, NotFoundException {
  32                 TTransport tr = new TSocket("localhost", 9160);
  33                 TProtocol proto = new TBinaryProtocol(tr);
  34                 Cassandra.Client client = new Cassandra.Client(proto);
  35                 tr.open();
  36 
  37                 String keyspace = "Keyspace1";
  38                 String columnFamily = "Standard1";
  39                 String keyUserID = "1";
  40 
  41                 // insert data
  42                 long timestamp = System.currentTimeMillis();
  43 
  44                 ColumnPath colPathName = new ColumnPath(columnFamily);
  45                 colPathName.setColumn("fullName".getBytes(UTF8));
  46 
  47                 client.insert(keyspace, keyUserID, colPathName, "Chris Goffinet"
  48                                 .getBytes(UTF8), timestamp, ConsistencyLevel.ONE);
  49 
  50                 ColumnPath colPathAge = new ColumnPath(columnFamily);
  51                 colPathAge.setColumn("age".getBytes(UTF8));
  52 
  53                 client.insert(keyspace, keyUserID, colPathAge, "24".getBytes(UTF8),
  54                                 timestamp, ConsistencyLevel.ONE);
  55 
  56                 // read single column
  57                 System.out.println("single column:");
  58                 Column col = client.get(keyspace, keyUserID, colPathName,
  59                                 ConsistencyLevel.ONE).getColumn();
  60 
  61                 System.out.println("column name: " + new String(col.name, UTF8));
  62                 System.out.println("column value: " + new String(col.value, UTF8));
  63                 System.out.println("column timestamp: " + new Date(col.timestamp));
  64 
  65                 // read entire row
  66                 SlicePredicate predicate = new SlicePredicate();
  67                 SliceRange sliceRange = new SliceRange();
  68                 sliceRange.setStart(new byte[0]);
  69                 sliceRange.setFinish(new byte[0]);
  70                 predicate.setSlice_range(sliceRange);
  71 
  72                 System.out.println("\nrow:");
  73                 ColumnParent parent = new ColumnParent(columnFamily);
  74                 List<ColumnOrSuperColumn> results = client.get_slice(keyspace,
  75                                 keyUserID, parent, predicate, ConsistencyLevel.ONE);
  76                 for (ColumnOrSuperColumn result : results) {
  77                         Column column = result.column;
  78                         System.out.println(new String(column.name, UTF8) + " -> "
  79                                         + new String(column.value, UTF8));
  80                 }
  81                 tr.close();
  82         }
  83 }

Same example as above but working with cassandra version 1.0.0

   1 package cassandra.clientest;
   2 
   3 import java.io.UnsupportedEncodingException;
   4 import java.nio.ByteBuffer;
   5 import java.util.List;
   6 
   7 import org.apache.cassandra.thrift.Cassandra;
   8 import org.apache.cassandra.thrift.Column;
   9 import org.apache.cassandra.thrift.ColumnOrSuperColumn;
  10 import org.apache.cassandra.thrift.ColumnParent;
  11 import org.apache.cassandra.thrift.ColumnPath;
  12 import org.apache.cassandra.thrift.ConsistencyLevel;
  13 import org.apache.cassandra.thrift.InvalidRequestException;
  14 import org.apache.cassandra.thrift.NotFoundException;
  15 import org.apache.cassandra.thrift.SlicePredicate;
  16 import org.apache.cassandra.thrift.SliceRange;
  17 import org.apache.cassandra.thrift.TimedOutException;
  18 import org.apache.cassandra.thrift.UnavailableException;
  19 import org.apache.thrift.TException;
  20 import org.apache.thrift.protocol.TBinaryProtocol;
  21 import org.apache.thrift.protocol.TProtocol;
  22 import org.apache.thrift.transport.TFramedTransport;
  23 import org.apache.thrift.transport.TSocket;
  24 import org.apache.thrift.transport.TTransport;
  25 
  26 public class CClient
  27 {
  28     public static void main(String[] args)
  29     throws TException, InvalidRequestException, UnavailableException, UnsupportedEncodingException, NotFoundException, TimedOutException
  30     {
  31         TTransport tr = new TFramedTransport(new TSocket("localhost", 9160));
  32         TProtocol proto = new TBinaryProtocol(tr);
  33         Cassandra.Client client = new Cassandra.Client(proto);
  34         tr.open();
  35 
  36         String key_user_id = "1";
  37 
  38         // insert data
  39         long timestamp = System.currentTimeMillis();
  40         client.set_keyspace("Keyspace1");      
  41         ColumnParent parent = new ColumnParent("Standard1");
  42 
  43         Column nameColumn = new Column(toByteBuffer("name"));
  44         nameColumn.setValue(toByteBuffer("Chris Goffinet"));
  45         nameColumn.setTimestamp(timestamp);
  46         client.insert(toByteBuffer(key_user_id), parent, nameColumn, ConsistencyLevel.ONE);
  47         
  48         Column ageColumn = new Column(toByteBuffer("age"));
  49         ageColumn.setValue(toByteBuffer("24"));
  50         ageColumn.setTimestamp(timestamp);
  51         client.insert(toByteBuffer(key_user_id), parent, ageColumn, ConsistencyLevel.ONE);
  52 
  53         ColumnPath path = new ColumnPath("Standard1");
  54 
  55         // read single column
  56         path.setColumn(toByteBuffer("name"));
  57         System.out.println(client.get(toByteBuffer(key_user_id), path, ConsistencyLevel.ONE));
  58 
  59         // read entire row
  60         SlicePredicate predicate = new SlicePredicate();
  61         SliceRange sliceRange = new SliceRange(toByteBuffer(""), toByteBuffer(""), false, 10);
  62         predicate.setSlice_range(sliceRange);
  63         
  64         List<ColumnOrSuperColumn> results = client.get_slice(toByteBuffer(key_user_id), parent, predicate, ConsistencyLevel.ONE);
  65         for (ColumnOrSuperColumn result : results)
  66         {
  67             Column column = result.column;
  68             System.out.println(toString(column.name) + " -> " + toString(column.value));
  69         }
  70 
  71         tr.close();
  72     }
  73     
  74     public static ByteBuffer toByteBuffer(String value) 
  75     throws UnsupportedEncodingException
  76     {
  77         return ByteBuffer.wrap(value.getBytes("UTF-8"));
  78     }
  79         
  80     public static String toString(ByteBuffer buffer) 
  81     throws UnsupportedEncodingException
  82     {
  83         byte[] bytes = new byte[buffer.remaining()];
  84         buffer.get(bytes);
  85         return new String(bytes, "UTF-8");
  86     }
  87 }

Python

   1 #!/usr/bin/env python # encoding: utf-8
   2 """Sample Cassandra Client
   3 
   4 Created by Chris Goffinet on 2009-08-26."""
   5 
   6 from thrift import Thrift
   7 from thrift.transport import TTransport
   8 from thrift.transport import TSocket
   9 from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated
  10 from cassandra import Cassandra
  11 from cassandra.ttypes import *
  12 import time
  13 import pprint
  14 
  15 def main():
  16 
  17     socket = TSocket.TSocket("localhost", 9160)
  18     transport = TTransport.TBufferedTransport(socket)
  19     protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)
  20     client = Cassandra.Client(protocol)
  21     pp = pprint.PrettyPrinter(indent=2)
  22     keyspace = "Keyspace1"
  23     column_path = ColumnPath(column_family="Standard1", column="email")
  24     key = "1"
  25     value = "foobar@example.com "
  26     timestamp = time.time()
  27     try:
  28         transport.open()
  29         #Insert the data into Keyspace 1
  30         client.insert(keyspace,
  31                       key,
  32                       column_path,
  33                       value,
  34                       timestamp,
  35                       ConsistencyLevel.ZERO)
  36         #Query for data
  37         column_parent = ColumnParent(column_family="Standard1")
  38         slice_range = SliceRange(start="", finish="")
  39         predicate = SlicePredicate(slice_range=slice_range)
  40         result = client.get_slice(keyspace,
  41                                   key,
  42                                   column_parent,
  43                                   predicate,
  44                                   ConsistencyLevel.ONE)
  45         pp.pprint(result)
  46     except Thrift.TException, tx:
  47         print 'Thrift: %s' % tx.message
  48     finally:
  49         transport.close()
  50 
  51 if __name__ == '__main__':
  52     main()

Perl

This is almost a direct port from the PHP version above at PHP Example

#!/usr/bin/perl -w

use strict;
use warnings;

# Change for your environment
use lib '/var/lib/cassandra/interface/gen-perl';
use Cassandra::Cassandra;
use Cassandra::Constants;
use Cassandra::Types;

use Thrift;
use Thrift::BinaryProtocol;
use Thrift::Socket;
use Thrift::BufferedTransport;

use Data::Dumper;

# localhost and 9160 are default in storage conf for rpc listener
my $socket = new Thrift::Socket('localhost', 9160);
my $transport = new Thrift::BufferedTransport($socket,1024,1024);
my $protocol = new Thrift::BinaryProtocol($transport);
my $client = new Cassandra::CassandraClient($protocol);

eval {
   $transport->open();
   # See http://wiki.apache.org/cassandra/DataModel or http://wiki.apache.org/cassandra/ClientExamples#PHP for more explanations
   my $keyspace = 'Keyspace1';
   my $row_key = 'firsttest';

   # See http://wiki.apache.org/cassandra/API#ConsistencyLevel
   my $consistency_level = Cassandra::ConsistencyLevel::ONE;

   # Authentication only available in 0.6
   my $auth_request = new Cassandra::AuthenticationRequest();
   $auth_request->{credentials} = { username => 'user', password => 'password' };
   $client->login($keyspace, $auth_request);

   my $column_path = new Cassandra::ColumnPath();
   $column_path->{column_family} = 'Standard1';
   $column_path->{super_column} = undef;
   $column_path->{column} = 'email';

   my $timestamp = time;

   my $value = 'foobar@example.com';
   $client->insert($keyspace, $row_key, $column_path, $value, $timestamp, $consistency_level);

   $column_path->{column} = 'age';
   $timestamp = time;
   $value = "24";
   $client->insert($keyspace, $row_key, $column_path, $value, $timestamp, $consistency_level);

   my $column1 = new Cassandra::Column();
   $column1->{name} = 'foo';
   $column1->{value} = 'fooey value';
   $column1->{timestamp} = time;

   my $column2 = new Cassandra::Column();
   $column2->{name} = 'bar';
   $column2->{value} = 'bar like thing';
   $column2->{timestamp} = time;

   my $super_column = new Cassandra::SuperColumn();
   $super_column->{name} = 'SuperColumnName';
   $super_column->{columns} = [$column1, $column2];

   my $c_or_sc = new Cassandra::ColumnOrSuperColumn();
   $c_or_sc->{super_column} = $super_column;

   my $mutation = { Super1 => [$c_or_sc] };
   $client->batch_insert($keyspace, 'KeyName', $mutation, $consistency_level);

   my $column_parent = new Cassandra::ColumnParent();
   $column_parent->{column_family} = "Standard1";
   $column_parent->{super_column} = undef;

   my $slice_range = new Cassandra::SliceRange();
   $slice_range->{start} = "";
   $slice_range->{finish} = "";

   my $predicate = new Cassandra::SlicePredicate();
   my @list = $predicate->{column_names};
   $predicate->{slice_range} = $slice_range;

   my $result = $client->get_slice($keyspace, $row_key, $column_parent, $predicate, $consistency_level);

   # Removal available after 0.6
   $client->remove($keyspace, $row_key, $column_path, $timestamp, $consistency_level);
   my $result_after = $client->get_slice($keyspace, $row_key, $column_parent, $predicate, $consistency_level);

   # To get a range of all the keys within that column_parent
   $predicate = new Cassandra::SlicePredicate();
   $predicate->{slice_range} = new Cassandra::SliceRange( {start => '', finish => '' } );

   my $paged_result = $client->get_range_slice($keyspace, $column_parent, $predicate, '', '', 10, $consistency_level);

   print Dumper($result, $result_after, $paged_result);

   # All of these require 0.6 see http://wiki.apache.org/cassandra/API for more information
   print Dumper($client->describe_keyspaces);
   print Dumper($client->describe_keyspace('Keyspace1'));
   print Dumper($client->describe_cluster_name);
   print Dumper($client->describe_version);

   $transport->close();
}; if($@){
   warn(Dumper($@));
}

1;

C#

namespace CassandraDemo
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    using Apache.Cassandra;
    using Thrift.Protocol;
    using Thrift.Transport;

    class Program
    {
        static void Main(string[] args)
        {
            TTransport transport = new TBufferedTransport(new TSocket("localhost", 9160));
            TProtocol protocol = new TBinaryProtocol(transport);
            Cassandra.Client client = new Cassandra.Client(protocol);

            Console.WriteLine("Opening connection");
            transport.Open();

            System.Text.Encoding utf8Encoding = System.Text.Encoding.UTF8;

            long timeStamp = DateTime.Now.Millisecond;
            ColumnPath nameColumnPath = new ColumnPath()
                                        {
                                            Column_family = "Standard1",
                                            Column = utf8Encoding.GetBytes("name")
                                        };

            Console.WriteLine("Inserting name columns");

            //Insert the data into the column 'name'
            client.insert("Keyspace1",
                          "1",
                          nameColumnPath,
                          utf8Encoding.GetBytes("Joe Bloggs"),
                          timeStamp,
                          ConsistencyLevel.ONE);

            client.insert("Keyspace1",
                          "2",
                          nameColumnPath,
                          utf8Encoding.GetBytes("Joe Soap"),
                          timeStamp,
                          ConsistencyLevel.ONE);

            //Simple single value get using the key to get column 'name'
            ColumnOrSuperColumn returnedColumn = client.get("Keyspace1", "1", nameColumnPath, ConsistencyLevel.ONE);
            Console.WriteLine("Column Data in Keyspace1/Standard1: name: {0}, value: {1}",
                              utf8Encoding.GetString(returnedColumn.Column.Name),
                              utf8Encoding.GetString(returnedColumn.Column.Value));

            Console.WriteLine("Getting splice range");

            //Read an entire row
            SlicePredicate predicate = new SlicePredicate()
                                       {
                                          Slice_range = new SliceRange()
                                                        {
                                                            //Start and Finish cannot be null
                                                            Start = new byte[0],
                                                            Finish = new byte[0],
                                                            Count  = 10,
                                                            Reversed = false
                                                        }
                                       };

            ColumnParent parent = new ColumnParent() { Column_family = "Standard1" };
            Dictionary<string , List<ColumnOrSuperColumn>> results = client.multiget_slice("Keyspace1",
                                                                      new List<string>() { "1", "2"},
                                                                      parent,
                                                                      predicate,
                                                                      ConsistencyLevel.ONE);

            foreach (KeyValuePair<string, List<ColumnOrSuperColumn>> resultPair in results)
            {
                Console.WriteLine("Key: {0}", resultPair.Key);

                foreach (ColumnOrSuperColumn resultColumn in resultPair.Value)
                {
                    Column column = resultColumn.Column;
                    Console.WriteLine("name: {0}, value: {1}", utf8Encoding.GetString(column.Name), utf8Encoding.GetString(column.Value));
                }
            }

            Console.WriteLine("Closing connection");
            transport.Close();
        }
    }
}

C++

This is for Cassandra version 0.7 or later

   1 #include "Thrift.h"
   2 #include "transport/TSocket.h"
   3 #include "transport/TTransport.h"
   4 #include "transport/TBufferTransports.h"
   5 #include "protocol/TProtocol.h"
   6 #include "protocol/TBinaryProtocol.h"
   7 #include "Cassandra.h"
   8 
   9 using namespace std;
  10 using namespace apache::thrift;
  11 using namespace apache::thrift::transport;
  12 using namespace apache::thrift::protocol;
  13 using namespace org::apache::cassandra;
  14 
  15 int main(int argc, char *argv[]){
  16   try{
  17     boost::shared_ptr<TTransport> socket = boost::shared_ptr<TSocket>(new TSocket("127.0.0.1", 9160));
  18     boost::shared_ptr<TTransport> tr = boost::shared_ptr<TFramedTransport>(new TFramedTransport (socket));
  19     boost::shared_ptr<TProtocol> p = boost::shared_ptr<TBinaryProtocol>(new TBinaryProtocol(tr));
  20     CassandraClient cass(p);
  21     tr->open();
  22 
  23     cass.set_keyspace("Keyspace1");
  24 
  25     string key = "1";
  26     ColumnParent cparent;
  27     cparent.column_family = "Standard1";
  28     Column c;
  29     c.name = "name";
  30     c.value = "John Smith";
  31     c.__isset.value = true;
  32 
  33     // have to go through all of this just to get the timestamp in ms
  34     struct timeval td;
  35     gettimeofday(&td, NULL);
  36     int64_t ms = td.tv_sec;
  37     ms = ms * 1000;
  38     int64_t usec = td.tv_usec;
  39     usec = usec / 1000;
  40     ms += usec;
  41     c.timestamp = ms;
  42     c.__isset.timestamp = true;
  43 
  44     // insert the "name" column
  45     cass.insert(key, cparent, c, ConsistencyLevel::ONE);
  46 
  47     // insert another column, "age"
  48     c.name = "age";
  49     c.value = "42";
  50     cass.insert(key, cparent, c, ConsistencyLevel::ONE);
  51 
  52     // get a single cell
  53     ColumnPath cp;
  54     cp.__isset.column = true;           // this must be set of you'll get an error re: Padraig O'Sullivan
  55     cp.column = "name";
  56     cp.column_family = "Standard1";
  57     cp.super_column = "";
  58     ColumnOrSuperColumn sc;
  59 
  60     cass.get(sc, key, cp, ConsistencyLevel::ONE);
  61     printf("Column [%s]  Value [%s]  TS [%lld]\n",
  62       sc.column.name.c_str(), sc.column.value.c_str(), sc.column.timestamp);
  63 
  64     // get the entire row for a key
  65     SliceRange sr;
  66     sr.start = "";
  67     sr.finish = "";
  68 
  69     SlicePredicate sp;
  70     sp.slice_range = sr;
  71     sp.__isset.slice_range = true; // set __isset for the columns instead if you use them
  72 
  73     KeyRange range;
  74     range.start_key = key;
  75     range.end_key = "";
  76     range.__isset.start_key = true;
  77     range.__isset.end_key = true;
  78 
  79     vector<KeySlice> results;
  80     cass.get_range_slices(results, cparent, sp, range, ConsistencyLevel::ONE);
  81     for(size_t i=0; i<results.size(); i++){
  82       printf("Key: %s\n", results[i].key.c_str());
  83       for(size_t x=0; x<results[i].columns.size(); x++){
  84         printf("Column: %s  Value: %s\n", results[i].columns[x].column.name.c_str(),
  85           results[i].columns[x].column.value.c_str());
  86       }
  87     }
  88 
  89     tr->close();
  90   }catch(TTransportException te){
  91     printf("Exception: %s  [%d]\n", te.what(), te.getType());
  92   }catch(InvalidRequestException ire){
  93     printf("Exception: %s  [%s]\n", ire.what(), ire.why.c_str());
  94   }catch(NotFoundException nfe){
  95     printf("Exception: %s\n", nfe.what());
  96   }
  97   printf("Done!!!\n");
  98   return 0;
  99 }

Notes

The Cassandra.Client object is always sending its request to the same Cassandra node in the cluster. The server then determines if and where the request should be routed to (Server-based routing). DNS Round Robin or a Cassandra.Client object pool connected to several servers in the cluster can be used to get higher throughput and availability.

The get_string_property() method can be used to retrieve the active node list:

String jsonServerList = client.get_string_property("token map")

The Cassandra.Client object cannot be used concurrently by multiple threads (not thread safe). Each thread must use their own Cassandra.Client object.

stats

ThriftExamples (last edited 2013-11-15 17:41:56 by GehrigKunz)