2011年3月25日金曜日

Cassandra C++ であそぼ(5)

ぽぽぽぽーーーん
#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;

using namespace org::apache::cassandra;

std::string show_lists( std::vector<KeySlice>& kres ) {
  BOOST_FOREACH( KeySlice kv, kres ) {
    std::cout << "Row key: " << kv.key << std::endl;
    BOOST_FOREACH( ColumnOrSuperColumn& col, kv.columns ) {
      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;
      }
    }
  }
  if( kres.empty() ) return "";
  return kres[kres.size()-1].key;
}

int main(int argc, char* argv[]) {
  using namespace apache::thrift;
  using namespace apache::thrift::protocol;
  using namespace apache::thrift::transport;

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

    KeyRange range;
    range.__isset.start_key = true;
    range.__isset.end_key = true;
    //range.start_key = "";
    //range.end_key = "";
    range.count = 6; // デフォルトは100

    // Random Patition における RowKey に
    // ソートキーという概念が無い点に注意
    // 終了のキーは、この場合、指定しない
    // 先頭から6個づつ読み込む
    std::vector<KeySlice>  kres;
    client.get_range_slices( kres, pare, predicate, range, ConsistencyLevel::ONE );
    // 表示ついでに、最後に読み取った場所をキーとして
    range.start_key = show_lists( kres );
    // 続きから読み込む
    client.get_range_slices( kres, pare, predicate, range, ConsistencyLevel::ONE );
    show_lists( kres );

    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 件のコメント: