2011年3月24日木曜日

Cassandra C++ であそぼ(4)

#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>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/foreach.hpp>
 
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";

    typedef std::vector<ColumnOrSuperColumn> csc_vec_type;
    typedef std::map<std::string, csc_vec_type> result_type;
    result_type res;

    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" );

    const char* keys[] = { "Aa", "Bb", "Cc", "Dd", "Ee", "Ff", "Gg", "Hh", "Ii", "Jj" };
    std::vector<std::string> kv;
    for( int i = 0; i < 10; ++i ) {
      kv.push_back( keys[i] );
    }

    client.multiget_slice( res, kv, pare, predicate, ConsistencyLevel::ONE );

    BOOST_FOREACH( result_type::value_type& ri, res ) {
      std::cout << "Row key: " << ri.first << std::endl;
      BOOST_FOREACH( ColumnOrSuperColumn& col, ri.second ) {
        std::cout << col.column.name << ":";
        if( col.column.name == "age" ) { 
          // big endian 
          std::reverse( col.column.value.begin(), col.column.value.end() );
          std::cout << *(long*)(&col.column.value[0]) << std::endl;
        } else {
          std::cout << col.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;
  }
  return 0;
}

0 件のコメント: