"Greater than" where-condition on timeuuid using Datastax C# Cassandra Driver


如何使用

Datastax C# 驱动程序在 timeuuid 数据类型的 CQL 查询中使"大于"或"小于"where 条件?

我在 Cassandra 中有一个表,用于存储按时间戳排序的 cookie 历史记录作为 timeuuid:

CREATE TABLE cookie_history (
    cookie_id text,
    create_date timeuuid,
    item_id text,
    PRIMARY KEY ((cookie_id), create_date)
);

该表使用 C# 类进行映射,以便使用 Datastax C# Cassandra 驱动程序进行查询:

[Table("cookie_history")]
public class CookieHistoryDataEntry
{
    [PartitionKey(1)]
    [Column("cookie_id")]
    public string CookieID;
    [ClusteringKey(1)]
    [Column("create_date")]
    public Guid CreateDate;
    [Column("item_id")]
    public string ItemID;
}

对于给定的cookie,我希望在给定时间戳之后的所有项目。

        var myTimeUuid = new Guid("5812e74d-ba49-11e3-8d27-27303e6a4831");
        var table = session.GetTable<CookieHistoryDataEntry>();
        var query = table.Where(x => x.CookieID == myCookieId
                                  && x.CreateDate > myTimeUuid);

但是这个(x.CreateDate> myTimeUuid)给了我一个编译时错误:

Operator '>' cannot be applied to operands of type 'System.Guid' and 'System.Guid'
可以在

原始 CQL 中使用 timeuuid 上的"大于"。因此,一种解决方案是从驱动程序执行原始 CQL:

session.Execute(@"select * 
    from cookie_history 
    where cookie_id = 1242a96c-4bd4-8505-1bea-803784f80c18 
    and create_date > 5812e74d-ba49-11e3-8d27-27303e6a4831;");
如果你使用

CompareTo(),你可以使用 Linq:

var query = table.Where(x => x.CookieID == myCookieId &&
                        x.CreateDate.CompareTo(myTimeUuid) > 0;

下面是处理 CompareTo 的代码。

相关:如果您需要比较需要使用Cassandra token()方法的分区键,则可以使用CqlToken.Create执行此操作:

var query = table.Where(x => 
    CqlToken.Create(x.PartitionKeyProperty) >= CqlToken.Create(3);

是否有理由尝试将日期表示为 Guid 而不是实际日期类型? 关于 Guid,没有大于或小于的概念,除非这是我不知道的一些边缘情况。 日期 A 可以大于日期 B,从我所看到的一切来看,Guid 的情况并非如此。

实际上,

也可以使用QueryBuilder而不仅仅是原始CQL:

select.where(QueryBuilder.eq('cookie_id', cookie_id).  
  and(QueryBuilder.gt("create_date", 
      QueryBuilder.fcall("maxTimeuuid", 
          QueryBuilder.fcall("unixTimestampOf", 
              QueryBuilder.raw(timeuuid_as_string))));

最新更新