如何使用 phantom 查询具有二级索引的可选列?
How do I query an optional column with a secondary index using phantom?
我在可选列上有二级索引:
class Sessions extends CassandraTable[ConcreteSessions, Session] {
object matchId extends LongColumn(this) with PartitionKey[Long]
object userId extends OptionalLongColumn(this) with Index[Option[Long]]
...
}
但是,indexedToQueryColumn
隐式转换不适用于可选列,因此无法编译:
def getByUserId(userId: Long): Future[Seq[Session]] = {
select.where(_.userId eqs userId).fetch()
}
这也不行:
select.where(_.userId eqs Some(userId)).fetch()
或者改变索引的类型:
object userId extends OptionalLongColumn(this) with Index[Long]
有没有办法使用 phantom 执行这样的查询?
我知道我可以反规范化,但它会涉及一些非常混乱的内务处理并使我们的(大量)数据大小增加三倍。查询通常 returns 只有少数结果,所以在这种情况下我愿意使用二级索引。
简答:您不能使用可选字段来查询幻象中的内容。
详细的答案:
但是,如果你真的想使用辅助可选列,你应该将你的实体字段声明为 Option 但你的虚拟表示不应该是一个选项以便查询。
object userId extends LongColumn(this) with Index[Long]
在 fromRow(r: Row) 中,您可以像这样创建对象:
Sessions(matchId(r), Some(userId(r)))
然后在服务部分你可以做以下事情:
.value(_.userId, t.userId.getOrElse(0))
您还有更好的方法来做到这一点。您可以复制 table,创建一种新类型的查询,例如 sessions_by_user_id,在此 table 中,您的 user_id 将是主键,而 match_id 是聚类关键。
由于 user_id 是可选的,您将以仅包含有效用户 ID 的 table 结尾,这样查找起来既简单又快速。
Cassandra 依赖于查询,所以用它对您有利。
查看我的 github 项目,它可以帮助您在同一个 table 中处理多个查询。
我在可选列上有二级索引:
class Sessions extends CassandraTable[ConcreteSessions, Session] {
object matchId extends LongColumn(this) with PartitionKey[Long]
object userId extends OptionalLongColumn(this) with Index[Option[Long]]
...
}
但是,indexedToQueryColumn
隐式转换不适用于可选列,因此无法编译:
def getByUserId(userId: Long): Future[Seq[Session]] = {
select.where(_.userId eqs userId).fetch()
}
这也不行:
select.where(_.userId eqs Some(userId)).fetch()
或者改变索引的类型:
object userId extends OptionalLongColumn(this) with Index[Long]
有没有办法使用 phantom 执行这样的查询?
我知道我可以反规范化,但它会涉及一些非常混乱的内务处理并使我们的(大量)数据大小增加三倍。查询通常 returns 只有少数结果,所以在这种情况下我愿意使用二级索引。
简答:您不能使用可选字段来查询幻象中的内容。
详细的答案:
但是,如果你真的想使用辅助可选列,你应该将你的实体字段声明为 Option 但你的虚拟表示不应该是一个选项以便查询。
object userId extends LongColumn(this) with Index[Long]
在 fromRow(r: Row) 中,您可以像这样创建对象:
Sessions(matchId(r), Some(userId(r)))
然后在服务部分你可以做以下事情:
.value(_.userId, t.userId.getOrElse(0))
您还有更好的方法来做到这一点。您可以复制 table,创建一种新类型的查询,例如 sessions_by_user_id,在此 table 中,您的 user_id 将是主键,而 match_id 是聚类关键。
由于 user_id 是可选的,您将以仅包含有效用户 ID 的 table 结尾,这样查找起来既简单又快速。
Cassandra 依赖于查询,所以用它对您有利。
查看我的 github 项目,它可以帮助您在同一个 table 中处理多个查询。