从riak中的结果集中获取某个值的总和

时间:2014-06-06 04:40:55

标签: scala riak

我正在研究riak-java客户端。在做Mapreduce时我得到了以下输出。 现在我想从我得到的结果集中得到ticketValue的总和。我希望通过传递userID来获取它。

更新

从这个方法我得到如下的resultSet

 def fetchTicketValue(userID:String): Boolean = {
    try{
      val result = riakClient.mapReduce("table-ticket","userID:Kim")
      .addMapPhase(new NamedJSFunction("Riak.mapValuesJson"),true)
      .execute
      val o:String = result.getResultRaw
    }catch{
      case e : Exception => 
         e.printStackTrace
     }
     true
  }

我之前忘记提到大括号 [{....},{....},{....}]

[{"ticketValue":3,"userID":"Kim","Date":"date","ticketID":"98394kjdf","ticketSource":"reg"},{"ticketValue":3,"userID":"Kim","Date":"date","ticketID":"98394kjdf","ticketSource":"reg"},{"ticketValue":3,"userID":"Kim","Date":"date","ticketID":"98394kjdf","ticketSource":"reg"}]

LIKE: userID:"kim"

RESULT: ticketValue:9

我如何获取数据?任何想法都将受到高度赞赏。 提前谢谢。

(Riak版本:1.3.2和Riak Java客户端:1.1.4)

2 个答案:

答案 0 :(得分:0)

import scala.util.parsing.json.JSON

case class Row(ticketValue: Int, userId: String, date: String, ticketId: String, ticketSource: String)

// I'm sure there's a way to do this more cleanly; using it as an implicit maybe
def mapToRow(m: Any): Row = {
  val typedM = m.asInstanceOf[Map[String, Any]]
  Row(typedM("ticketValue").asInstanceOf[Double].toInt,
    typedM("userID").toString,
    typedM("Date").toString,
    typedM("ticketID").toString,
    typedM("ticketSource").toString)
}

def getSum(result: String, userId: String) = {
    val rows = JSON.parseFull("[" + result + "]").get.asInstanceOf[Seq[Map[String, Any]]].map(mapToRow)
    rows.filter(_.userId == userId).map(_.ticketValue).sum
}


val result = """{"ticketValue":3,"userID":"Samy","Date":"date","ticketID":"98394kjdf","ticketSource":"reg"},{"ticketValue":3,"userID":"Kim","Date":"date","ticketID":"98394kjdf","ticketSource":"reg"},{"ticketValue":3,"userID":"Kim","Date":"date","ticketID":"98394kjdf","ticketSource":"reg"},{"ticketValue":3,"userID":"Kim","Date":"date","ticketID":"98394kjdf","ticketSource":"reg"}"""
getSum(result, "Kim")

答案 1 :(得分:0)

你有没有看过 Jerkson Library (据我所知它已经放弃了,但仍然提供了很好的功能),它是一个用于java的Jackson Library的scala包装器,使用默认的Play JSON库是一个好主意但是从2.11开始弃用。从此开始,Jerkson也更容易。

使用Jerkson你可以尝试这个,代码是自我解释的,我最近有同样的问题Link - >

var sum:Int = 0
val parsedList = parse[List[Ticket]](result.getResultRaw)
for (e <-parsedList){
  sum = sum + e.ticketValue
}
println("Final sum: "+sum)