【问题标题】:get frozen map of cassandra in scala在scala中获取cassandra的冻结地图
【发布时间】:2019-01-06 14:18:27
【问题描述】:

我有以下 Cassandra 表架构:-

CREATE TABLE test (
id text,
stats frozen<map<text, text>> )

我创建了 scala 应用程序来从 cassandra 中提取数据,经过一些操作后,我会再次将数据更新到 cassandra。

val result =  session.execute("Select * from test where id= 'testid'")
val resultList = result.all()
val rows = resultList.iterator()

if (resultList.size() > 0) {
 while (rows.hasNext()) {
   val curRow = rows.next()
   val ID = curRow.getString("id")
   val statistics = curRow.getMap[String,String] ??????
 }
}

cassandra 表中的数据行是这样的:-

('testid',{'a1': '10', 'a2': '0', 'a3': '0', 'a4': '22', 'd1': '0', 'd2': '1', 'd3': '1', 'd4': '0', 'exb': '0', 'inb': '6', 'satno': '10'})
('id123',{'a1': '10', 'a2': '0', 'd1': '0', 'd2': '1', 'd3': '1', 'd4': '0'})

我想将我的统计信息字段准确地映射到统计信息中。我应该如何做到这一点,我在 stats 列中的字段对于 1 行是动态的,对于其他行可能有 10 个键值对,它可能有 7 个键值对。

谢谢,

【问题讨论】:

    标签: scala cassandra cassandra-3.0


    【解决方案1】:

    你需要这样写:

    val statistics = curRow.getMap[String,String]("stats", 
        classOf[String], classOf[String])
    

    例如,

    val cluster = Cluster.builder().addContactPoint("127.0.0.1").build()
    val session = cluster.connect()
    
    val result =  session.execute("Select * from test.fmtest where id= 'id123'")
    val resultList = result.all()
    val rows = resultList.iterator()
    
    if (resultList.size() > 0) {
      while (rows.hasNext()) {
        val curRow = rows.next()
        val ID = curRow.getString("id")
        val statistics = curRow.getMap[String,String]("stats", 
            classOf[String], classOf[String])
        println("id=" + ID + ", stats=" + statistics)
      }
    }
    cluster.close()
    

    将打印:

    id=id123, stats={a1=10, a2=0, d1=0, d2=1, d3=1, d4=0}
    

    【讨论】:

    • 哦,太好了,我怎样才能提取任何特定的键,如“a1”或“d4”?
    • 那么您只需对 statistics 对象使用普通的 Map 操作
    • 感谢@Alex,它成功了。我接受你的回答。
    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2018-02-04
    • 2016-11-15
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多