使用CQL准备的查询在c ++中管理计数器

时间:2012-05-15 21:45:50

标签: c++ cassandra cql

重新发布实际代码

    // cassandra is a connected org::apache::cassandra::CassandraClient
// statement is a CqlPreparedResult
// result is a CqlResult
// CF declaration is:
/*
CREATE COLUMNFAMILY xp (
  cid ascii PRIMARY KEY,
  exp4 counter,
  exp2 counter,
  exp3 counter,
  exp1 counter
) WITH
  comment='' AND
  comparator=text AND
  read_repair_chance=0.100000 AND
  gc_grace_seconds=864000 AND
  default_validation=counter AND
  min_compaction_threshold=4 AND
  max_compaction_threshold=32 AND
  replicate_on_write=True AND
  compaction_strategy_class='SizeTieredCompactionStrategy' AND
  compression_parameters:sstable_compression='org.apache.cassandra.io.compress.SnappyCompressor';
 */
std::vector<std::string> values;
values.resize(2);
values[0]="1";
values[1]="103";
cassandra->prepare_cql_query(statement,"update xp set exp2 = exp2 + ? where cid=?",Compression::NONE);
int32_t handle=statement.itemId;
try {
    cassandra->execute_prepared_cql_query(result,handle,values);
}
catch(InvalidRequestException &e) {
    cout << __LINE__ << " " << e.why << " "<< e.what() << endl;
}
// throws '?' is an invalid value, should be a long.
values.resize(1);
values[0]="103";
cassandra->prepare_cql_query(statement,"update xp set exp2 = exp2 + 1 where cid=?",Compression::NONE);
handle=statement.itemId;
cassandra->execute_prepared_cql_query(result,handle,values);
//works

所以看起来问题在于我们无法传递二进制数据。 我试图传入一个包含long的实际表示的字符串,但没有成功。 当我从中读取数据时会出现同样的问题,但我认为我可以管理它(扫描返回的字符串并将其一次转换为一个字节作为最后的手段)

是否有人使用counter,c ++和cql成功?

2 个答案:

答案 0 :(得分:0)

long值应编码为big-endian 64位整数。所以试试:

values[0] = "\0\0\0\0\0\0\0\x64";

如果您打算在没有驱动程序的情况下继续使用CQL,那么您将需要大量的编组/解组例程来涵盖这类事情。

答案 1 :(得分:0)

好吧,我发现我缺少完成正确的二进制编码。 使用此函数将我的long转换为字符串,我成功使用准备好的查询

string to_counter(const long value) {
    union  {
        long    v;
        char    cc[8];
    } xx;
    xx.v=value;
    string r;
    r.assign(xx.cc,8);
    reverse(r.begin(),r.end());
    return r;
}

它是伴侣

long from_counter(const string& value) {
    union  {
        long    v;
        char    cc[8];
    } xx;
    for (size_t i=0; i < 8;++i) {
        xx.cc[7-i]=value.at(i);
    }
    return xx.v;
}

我很确定这段代码可以改进,欢迎任何suggestino:)

相关问题