# 如何对KTable（Kafka）中的值进行求和

go评论60阅读模式

How to sum the values in a KTable (Kafka)

# 问题

``````数量

AAPL   50
TSLA   100
``````
``````价格

AAPL   10
TSLA   20
``````

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

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

``````AAPL 500
TSLA 200
``````

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

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

go 51

go 37

go 49

go 41