Cassandra Sample Trigger Code获取插入值

时间:2013-11-27 11:45:06

标签: java triggers cassandra

我需要您在触发器扩充方法中提取列名称和值的帮助。

表格默认:

           create table dy_data (
                                     id timeuuid,
                                     data_key text,
                                     time timestamp,
                                    data text,primary key((id,data_key),time)
                                    ) with clustering order by (time desc);

触发码:

public class ArchiveTrigger implements ITrigger {
  public Collection<RowMutation> augment(ByteBuffer key, ColumnFamily cf) {
        try {
            // Below loop only has 2 columns ( one is "data" and another one may be "time" but i am not sure, because i cannot get value.           
            for (Column cell : cf) {
                //Got Exception if I try to get column name
                String name = ByteBufferUtil.string(cell.name());
                //Got only "data" column value and empty value for another column may be "time". If I try ByteBufferUtil.toLong(cell.value()) it throws exception
                String value = ByteBufferUtil.string(cell.value());
                log(" name = " + name);
                log(" value = " + value);
            }
        } catch (Exception e) {
            logger.warn("Exception ", e);
        }
        return null;
    }
}

我尽力在谷歌搜索示例代码。但失败了。请帮我提供示例代码。提前谢谢。

2 个答案:

答案 0 :(得分:4)

感谢iamaleksey为您提供帮助。你的回复对我很有帮助。

以下是对触发器用户有用的代码段

public Collection<RowMutation> augment(ByteBuffer key, ColumnFamily cf) {
        try {
            ByteBuffer id_bb = CompositeType.extractComponent(key, 0);
            UUID id=TimeUUIDType.instance.compose(id_bb);

            ByteBuffer data_key_bb = CompositeType.extractComponent(key, 1);
            String data_key=UTF8Type.instance.compose(data_key_bb);


            Iterator col_itr=cf.iterator();

            Column ts_col=(Column)col_itr.next();
            ByteBuffer time_bb=CompositeType.extractComponent(ts_col.name(),0);
            long time=(TimestampType.instance.compose(time_bb)).getTime();


            Column data_bb=(Column)col_itr.next();
            String data=UTF8Type.instance.compose(data_bb.value());

            log(" id --> "+id.toString());
            log(" data_key-->"+data_key);
            log(" time == "+time);
            log(" data == "+data);
        } catch (Exception e) {
            logger.warn("Exception ", e);
        }
        return null;
    }

PS:因为我知道我的表格格式,所以我对列比较器类型进行了硬编码。如果我们想编写通用触发器代码,我们可以使用cf.getComponentComparator()/ getKeyValidator()。

答案 1 :(得分:3)

要获取'id'和'data_key',您必须拆分键(ByteBuffer键,第一个参数为augment)。 'time'将在cell.name()的第一部分 - 你仍然需要拆分它。 'data'将是cell.value(),不需要进行任何拆分。