【问题标题】:How to delete table on Cassandra using C# Datastax driver?如何使用 C# Datastax 驱动程序删除 Cassandra 上的表?
【发布时间】:2017-10-10 10:57:45
【问题描述】:
var keyspace = "mydb";
var datacentersReplicationFactors = new Dictionary<string, int>(0);
var replication = ReplicationStrategies.CreateNetworkTopologyStrategyReplicationProperty(datacentersReplicationFactors);

using (var cluster = Cluster.Builder().AddContactPoints("my_ip").Build())
using (var session = cluster.Connect())
{
    session.CreateKeyspaceIfNotExists(keyspace, replication, true);
    session.ChangeKeyspace(keyspace);

    var entityTable = new Table<Models.Entity>(session);
    var attributeTable = new Table<Models.Attribute>(session);

    entityTable.CreateIfNotExists(); // Worked
    attributeTable.CreateIfNotExists(); // Worked

    entityTable.Delete(); // Does nothing
    attributeTable.Delete();  // Does nothing
}

编辑:不使用原始查询 session.Execute("DROP TABLE entities;"); 工作正常。

【问题讨论】:

    标签: c# cassandra datastax


    【解决方案1】:

    Delete() 方法不适用于删除表。它返回 DELETE cql 语句的表示。如果你调用它,你就会得到{DELETE FROM entities}

    如果你需要删除一个表,最简单的方法就是执行 DROP 语句:

    session.Execute("DROP TABLE entities;");
    

    【讨论】:

    • 我得到“第 0:-1 行不匹配的输入 '' 期待 K_WHERE”
    • Delete() 返回什么查询?
    • 嗯,这似乎是 DELETE 命令而不是 DROP,我收到 {DELETE FROM entities}
    • 似乎如此。当我需要删除某个表时,我将使用您在编辑中指定的直接 DROP 执行。
    • 好的,谢谢,我会做一个扩展,然后在这里发布。
    【解决方案2】:

    除非已经有我不知道的删除表的方法,否则您可以使用此扩展。

    public static class DastaxTableExtensions
    {
        public static void Drop<T>(this Table<T> table)
        {
            table.GetSession().Execute($"DROP TABLE {table.Name};");
        }
    
        public static void DropIfExists<T>(this Table<T> table)
        {
            table.GetSession().Execute($"DROP TABLE IF EXISTS {table.Name};");
        }
    }
    

    那你就可以这样使用了

    entityTable.Drop();
    attributeTable.DropIfExists();
    

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 1970-01-01
      • 2016-02-27
      • 2017-01-20
      • 2017-08-04
      • 2019-01-31
      • 2016-01-22
      • 2014-05-13
      • 1970-01-01
      相关资源
      最近更新 更多