如何对KTable(Kafka)中的值进行求和

huangapple go评论101阅读模式
英文:

How to sum the values in a KTable (Kafka)

问题

我有两个KTables。一个保存我拥有的股票数量,另一个保存这些股票的最新价格。

例如,

数量
键     值
AAPL   50
TSLA   100
价格
键     值
AAPL   10
TSLA   20

当两个表中的任何一个发生更新时,我想计算我的投资组合的总价值并将其发布到另一个主题。在上面的示例中,总价值将为50 x $10 + 100 x $20 = $2,500

如何做到这一点的最佳方式是什么?我想一个明智的第一步是合并这两个表,并单独计算每个持仓的价值。但我不知道如何对结果的KTable中的值进行求和,以获取我的投资组合的总价值?

英文:

I have two KTables. One holds the quantities of stocks I own, and the other holds the latest prices for those stocks.

E.g.,

Quantities
Key    Value
AAPL   50
TSLA   100
Prices
Key    Value
AAPL   10
TSLA   20

When there is an update to either table, I want to compute the total value of my portfolio and publish it to another topic. In the example above, the total value would be 50 x $10 + 100 x $20 = $2,500.

What's the best way to do this? I imagine a sensible first step is to join the tables, and compute the value of each position separately. But I don't know how to sum the values in the resulting KTable to get the total value of my portfolio?

答案1

得分: 1

建议是加入,按键分组,然后映射乘积

形成流

AAPL (50, 10)
TSLA (10, 20)

然后使用 mapValues 得到

AAPL 500 
TSLA 200

一旦你有了 KTable,你可以遍历 KVStore 来求和总值

英文:

Suggestion would be join, grouping by key, then map the product

Form a stream of

AAPL (50, 10)
TSLA (10, 20)

Then mapValues to get

AAPL 500 
TSLA 200

Once you have the KTable, you can iterate over the KVStore to sum the total values

huangapple
  • 本文由 发表于 2020年7月31日 01:12:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63178135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定