c# - Datastax C# 驱动程序中的 Cassandra timeuuid

标签 c# cassandra driver datastax

什么 C# 类型相当于 Datastax Cassandra C# 驱动程序中的 timeuuid?

我正在编写一个简单的用户跟踪服务,并希望访问最新的用户历史记录。我正在尝试创建一个与此创建语句等效的表:

CREATE TABLE IF NOT EXISTS user_history (
    user_id text,
    event_type text,
    create_date timeuuid,
    item_id text,
    PRIMARY KEY ((user_id, event_type), create_date)
);

我做了以下类(class):

[AllowFiltering]
[Table("user_history")]
public class UserHistory
{
    [PartitionKey(1)]
    [Column("user_id")]
    public string UserID;

    [PartitionKey(2)]
    [Column("event_type")]
    public string EventType;

    [ClusteringKey(1)]
    [Column("create_date")]
    public DateTime CreateDate { get; set; }

    [Column("item_id")] 
    public string ItemID;
}

我正在使用此语句在 Cassandra 中创建表:

var table = Session.GetTable<UserHistory>();
table.CreateIfNotExists();

但这给了我下表:

CREATE TABLE user_history (
  user_id text,
  event_type text,
  create_date timestamp,
  item_id text,
  PRIMARY KEY ((user_id, event_type), create_date)
)

可以看到,create_date的类型是timestamp,而不是timeuuid

我已经尝试使用 Guid 而不是 DateTime,但是当我调用 .CreateIfNotExists()< 时,它会给我一个 uuid/.

我是否应该为 CreateDate 使用 Guid 而不是 DateTime 并使用原始 CQL3 显式创建表?我想这将允许我从 Cassandra 读取和写入 timeuuid(使用 FluentCassandra 项目中的 GuidGenerator)?! (回想一下:我使用的是 Datastax 驱动程序)

最佳答案

Timeuuid 基本上是一个 guid,所以你应该使用一个 guid,the following code is taken from here: creating-a-time-uuid-guid-in-net and is part of the FluentCassandra project

“以下是在 .NET 中生成时间 UUID 或基于时间的 Guid 对象所需的所有代码。”

public static Guid GenerateTimeBasedGuid(DateTime dateTime)  
{
    long ticks = dateTime.Ticks - GregorianCalendarStart.Ticks;

    byte[] guid = new byte[ByteArraySize];
    byte[] clockSequenceBytes = BitConverter.GetBytes(Convert.ToInt16(Environment.TickCount % Int16.MaxValue));
    byte[] timestamp = BitConverter.GetBytes(ticks);

    // copy node
    Array.Copy(Node, 0, guid, NodeByte, Node.Length);

    // copy clock sequence
    Array.Copy(clockSequenceBytes, 0, guid, GuidClockSequenceByte, clockSequenceBytes.Length);

    // copy timestamp
    Array.Copy(timestamp, 0, guid, 0, timestamp.Length);

    // set the variant
    guid[VariantByte] &= (byte)VariantByteMask;
    guid[VariantByte] |= (byte)VariantByteShift;

    // set the version
    guid[VersionByte] &= (byte)VersionByteMask;
    guid[VersionByte] |= (byte)((int)GuidVersion.TimeBased << VersionByteShift);

    return new Guid(guid);
}

关于c# - Datastax C# 驱动程序中的 Cassandra timeuuid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22019101/

相关文章:

windows - 通过 GUID 打开设备

c# - asp.net core 中的部分标签助手和 HTML 助手有什么区别?

c# - 在这种情况下主线程会发生什么

c# - IXmlSerializable 和继承

benchmarking - 使用 pycassa 进行压力测试

linux - 更改在 Linux 上使用 JFS 驱动程序启动的参数

c - NT 注册表句柄行为

c# - 防止 ListView 丢失所选项目

java - cassandra 1.1.2 中的数据丢失

java - 未检测到 Yaml 更改,启动期间遇到异常 : Invalid yaml: file:/etc/cassandra/cassandra. yaml