2011年3月24日木曜日

Cassandra C++ であそぼ(2)

#include <string>
#include <sstream>
#include <iostream>
#include <vector>
 
#include "Cassandra.h"
#include "cassandra_types.h"
 
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocket.h>
#include <transport/TTransportUtils.h>
 
 
const int port= 9160;
 
int main(int argc, char* argv[]) {
  using namespace apache::thrift;
  using namespace apache::thrift::protocol;
  using namespace apache::thrift::transport;
  using namespace org::apache::cassandra;

  boost::shared_ptr<TSocket>     socket(new TSocket("localhost", port));
  boost::shared_ptr<TTransport>  tport(new TFramedTransport(socket));
  boost::shared_ptr<TProtocol>   pcol(new TBinaryProtocol(tport));
  CassandraClient                client(pcol);

  try {
    tport->open();
    client.set_keyspace( "Keyspace1" );

    ColumnParent pare;
    pare.column_family = "Users";

    SlicePredicate predicate;
    predicate.__isset.column_names = true;
    predicate.column_names.push_back( "first" );
    predicate.column_names.push_back( "last" );
    predicate.column_names.push_back( "age" );

    std::vector<ColumnOrSuperColumn> v;
    client.get_slice( v, "jsmith", pare, predicate, ConsistencyLevel::ONE );

    for( int i = 0; i < v.size(); ++i ) {
      std::cout << v[i].column.name << ":";
      if( v[i].column.name == "age" ) { 
        // big endian 
        std::reverse( v[i].column.value.begin(), v[i].column.value.end() );
        std::cout << *(long*)(&v[i].column.value[0]) << std::endl;
      } else {
        std::cout << v[i].column.value << std::endl;
      }
    }

    tport->close();
  } catch (InvalidRequestException &re) {
    std::cerr << "invalid request: " << re.why.c_str() << std::endl;
  } catch (TException &tx) {
    std::cerr << "ERROR: " << tx.what() << std::endl;
  }
}

0 件のコメント: