我正在尝试进行一些聚合以将指标发布到 Cloud Watch。在保存最终结果之前,我添加了我的指标计数逻辑。基本上,我试图计算每列的值(value) > 0 的客户数量。这样我就可以获得数字和百分比。
case class ItemData(totalRent : Long, totalPurchase: Long, itemTypeCounts: Map[String, Int] ) extends Serializable
import scala.collection.JavaConversions._
class ItemDataMetrics(startDate: String) {
var totals: ItemData = _
def countNonZero(c: Long): Int = {if (c > 0) 1 else 0}
def accumulate(featureData: ItemData) {
totals.totalRent+= countNonZero( featureData.totalRent )
totals.totalPurchase += countNonZero( featureData.totalPurchase )
for (entry <- featureData.itemTypeCounts.entrySet) {
if (totals.itemTypeCounts.contains( entry.getKey )) {
totals.itemTypeCounts.updated( entry.getKey, entry.getValue + countNonZero( entry.getValue ) )
} else {
totals.itemTypeCounts.put( entry.getKey, countNonZero( entry.getValue ) )
}
}
}
}
var totalCustomer : Int = 0
val itemMetrics: ItemDataMetrics = new ItemDataMetrics(startDate)
val resultValue = resultDF.map( {
r => {
val customerId = r.getAs[String]( "customerId" )
val totalRent = r.getAs[Long]( "totalRent" )
val totalPurchase = r.getAs[Long]( "totalPurchase" )
val itemTypeCounts = r.getAs[Map[String, Int]]( "itemType" )
val items = ItemData( totalRent, totalPurchase, itemTypeCounts)
totalCustomer = totalCustomer + 1
itemMetrics.accumulate(items)
val jsonString = JacksonUtil.toJson( items)
(customerId, jsonString)
}
} )
publishMetrics(startDate, featureMetrics) ---- publishes metrics to cloud watch
resultValue.saveAsTextFile("S3:....")
但是一直报错:
<console>:26: error: value += is not a member of Long
totals.totalRent += countNonZero( itemData.totalRent )
^
<console>:27: error: value += is not a member of Long
totals.totalPurchase += countNonZero( itemData.totalPurchase )
<console>:36: error: value entrySet is not a member of Map[String,Int]
for (entry <- itemData.itemTypeCounts.entrySet) {
我是 scala/spark 的新手。有人可以告诉我我在这里做错了什么吗?
最佳答案
x += y
在 Scala 中有两种情况是有效的:
x
有一个名为+=
的方法,它将以y
作为参数调用,或者x
是一个var
并且有一个名为+
的方法。在这种情况下,x
将被分配x + y
的结果
现在Long
只有一个+
方法,没有+=
方法。因此,您只能在 Long
上使用 +=
,前提是它是 var
。现在您没有显示 ItemData
类的定义,但由于出现错误,我假设 totals.totalRent
是一个 val
(或 def
)。因此它不能被重新分配,你不能在它上面使用 +=
。
关于scala - 错误 : value += is not a member of Long Scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096014/