将DateTime保存到Cassandra Date列

时间:2018-05-09 18:38:28

标签: c# cassandra

Cassandra .NET驱动程序文档非常糟糕,我正在尝试将一些功能废弃在一起,但是我浪费了太多时间来尝试从我发现的Java文档中更改代码。

我正在尝试使用Cassandra驱动程序将数据写入一个简单的表。该表已经存在,里面有日期。我创建了一个映射并添加了一些列。这是一个用于演示的截止版本:

For<Profile>().TableName("profiles")
    .PartitionKey(p => p.IntegerId)
    .Column(p => p.IntegerId, cm => cm.WithName("profileid"))
    .Column(p => p.BirthDate, cm => cm.WithName("dateofbirth"))

有更多的列和表,但这是重要的部分。

然后通过简单的通用方法完成保存:

public async Task<bool> Add<T>(T item) where T : EntityBase, new()
{
    await _mapper.InsertIfNotExistsAsync(item);
}

此外还有更多代码,但相关部分在这里。重要的是我正在使用InsertIfNotExists并使用与基本实体一起使用的泛型方法。

Cassandra中的

dateofbirth列的类型为Date。 当我运行Insert方法时,我得到一个例外,即Date的长度应该是4个字节而不是8个(我假设我需要切断DateTime的时间部分)。

我尝试在映射上使用WithType并创建类似于this question中描述的TypeSerializer,但没有运气。 任何人都有一个工作代码将此类型(可能还有其他类型)保存到Cassandra?

以下是从互联网改编的日期编解码器的代码,以及如何使用它,它可能(非常)错误:

public class DateCodec : TypeSerializer<DateTime>
{
    private static TypeSerializer<LocalDate> _innerSerializer;

    public DateCodec(TypeSerializer<LocalDate> serializer)
    {
        _innerSerializer = serializer;
        TypeInfo = new CustomColumnInfo("LocalDate");
    }

    public override IColumnInfo TypeInfo { get; }

    public override DateTime Deserialize(ushort protocolVersion, byte[] buffer, int offset, int length, IColumnInfo typeInfo)
    {
        var result = _innerSerializer.Deserialize(protocolVersion, buffer, offset, length, typeInfo);
        return new DateTime(result.Year, result.Month, result.Day);
    }

    public override ColumnTypeCode CqlType { get; }

    public override byte[] Serialize(ushort protocolVersion, DateTime value)
    {
        return _innerSerializer.Serialize(protocolVersion, new LocalDate(value.Year, value.Month, value.Day));
    }
}

用法:

TypeSerializerDefinitions definitions = new TypeSerializerDefinitions();
definitions.Define(new DateCodec(TypeSerializer.PrimitiveLocalDateSerializer));

var cluster = Cluster.Builder()
    .AddContactPoints(...)
    .WithCredentials(...)
    .WithTypeSerializers(definitions)
    .Build();

1 个答案:

答案 0 :(得分:3)

C#驱动程序使用LocalDate类来表示来自Cassandra的date,因此要么需要更改dateofbirth的声明以使用它,要么开发相应的编解码器。

您可以查看C#驱动程序的日期和时间表示文档:https://docs.datastax.com/en/developer/csharp-driver/3.5/features/datatypes/datetime/

使用代码示例更新问题后更新:

定义表格&amp;插入样本数据:

cqlsh> create table test.dt(id int primary key, d date);
cqlsh> insert into test.dt(id, d) values(1, '2018-05-17');
cqlsh> insert into test.dt(id, d) values(2, '2018-05-16');
cqlsh> insert into test.dt(id, d) values(3, '2018-05-15');

以下转换后的作品:

public class DateCodec : TypeSerializer<DateTime>
{
    private static readonly TypeSerializer<LocalDate> serializer = 
         TypeSerializer.PrimitiveLocalDateSerializer;

    public override ColumnTypeCode CqlType
    {
        get { return ColumnTypeCode.Date; }
    }

    public DateCodec() { }

    public override DateTime Deserialize(ushort protocolVersion, byte[] buffer, 
         int offset, int length, IColumnInfo typeInfo)
    {
        var result = serializer.Deserialize(protocolVersion, buffer,
                offset, length, typeInfo);
        return new DateTime(result.Year, result.Month, result.Day);
    }

    public override byte[] Serialize(ushort protocolVersion, DateTime value)
    {
        return serializer.Serialize(protocolVersion, 
            new LocalDate(value.Year, value.Month, value.Day));
    }
}

主程序:

TypeSerializerDefinitions definitions = new TypeSerializerDefinitions();
definitions.Define(new DateCodec());

var cluster = Cluster.Builder()
         .AddContactPoints("localhost")
         .WithTypeSerializers(definitions)
         .Build();
var session = cluster.Connect();
var rs = session.Execute("SELECT * FROM test.dt");
foreach (var row in rs)
{
    var id = row.GetValue<int>("id");
    var date = row.GetValue<DateTime>("d");
    Console.WriteLine("id=" + id + ", date=" + date);
}

var pq = session.Prepare("insert into test.dt(id, d) values(?, ?);");
var bound = pq.Bind(10, new DateTime(2018, 04, 01));
session.Execute(bound);

结果如下:

id=1, date=5/17/18 12:00:00 AM
id=2, date=5/16/18 12:00:00 AM
id=3, date=5/15/18 12:00:00 AM

cqlsh检查:

cqlsh> SELECT * from test.dt ;

 id | d
----+------------
 10 | 2018-04-01
  1 | 2018-05-17
  2 | 2018-05-16
  3 | 2018-05-15