【发布时间】:2017-03-28 11:21:41
【问题描述】:
Cassandra 数据建模的基本规则建议我们根据查询模式创建表。
在实践中,这通常意味着您将使用大约一个表 查询模式。如果您需要支持多种查询模式,您可以 通常需要不止一张桌子。
例如,我们可以为 Users
设置这 3 个表CREATE TABLE IF NOT EXISTS users(
id uuid,
username text,
emial text,
role text,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS users_by_role(
role text,
userid uuid,
username text,
emial text,
PRIMARY KEY (role)
);
CREATE TABLE IF NOT EXISTS users_by_email(
email text,
userid uuid,
username text,
role text,
PRIMARY KEY (email)
);
在使用 Cassandra CSharp 驱动程序的 C# 中,我们将 User 映射到第一个表:
public class User
{
public Guid Id;
public string UserName;
public string Email;
public string Role;
}
var config = new MappingConfiguration();
config.Define(new Map<User>()
.TableName("users")
.PartitionKey((o) => o.Id)
.Column((u) => u.Id, (cm) => cm.WithName("id"))
.Column((u) => u.UserName, (cm) => cm.WithName("username"))
.Column((u) => u.Email, (cm) => cm.WithName("email"))
.Column((u) => u.Role, (cm) => cm.WithName("role"))
.ExplicitColumns());
UserMapper = new Mapper(Session, config);
并使用 Mapper 读取数据:
User result = UserMapper.Single<User>("WHERE id=?", guid);
我的第一个问题是:我们如何将 User 映射到另外两个表 users_by_role 和 users_by_email?我认为我们不必再创建 2 个具有相同属性的 CLR 类型。 (此外,我们可以在其他表中有不同的列) 第二个问题:我们如何在 BatchStatement 中使用定义的映射器?例如:将用户插入到我们将使用的第一个表中:
UserMapper.Insert<User>(usr);
但在我们的示例中,我们必须批量插入 3 个表。最好的方法是什么?
驱动程序版本 3.1.0.1
【问题讨论】: