Search code examples
javaapache-kafkaapache-kafka-streams

Create Kafka Stream for count amount from value


I`m producing data like:

Key: "Mike", value: {"amount":46,"time":"2021-11-05T07:53:32.005751Z"}
Key: "John", value: {"amount":46,"time":"2021-11-05T07:53:32.005751Z"}
Key: "Mike", value: {"amount":50,"time":"2021-11-05T07:53:32.005751Z"}

Key is String (Names like Alice, John...). For example i need in result:

{"Mike": 2}
{"John": 1}

or

{"key":"Mike", "count": 2}
{"key":"John", "count": 1}

I tried next:

   public Topology createTopology(){
    StreamsBuilder builder = new StreamsBuilder();
    // json Serde
    final Serializer<JsonNode> jsonSerializer = new JsonSerializer();
    final Deserializer<JsonNode> jsonDeserializer = new JsonDeserializer();
    final Serde<JsonNode> jsonSerde = Serdes.serdeFrom(jsonSerializer, jsonDeserializer);

    KStream<String, JsonNode> textLines = builder.stream("bank-transactions", Consumed.with(Serdes.String(), jsonSerde));
    KTable<String, Long> wordCounts = textLines
            .map((k, v) -> new KeyValue<>(k, v.get("amount").asInt()))
            .groupByKey(Serialized.with(Serdes.String(), Serdes.Integer()))
            .count();

    wordCounts.toStream().to("person-transaction-frequency", Produced.with(Serdes.String(), Serdes.Long()));

    return builder.build();
}

public static void main(String[] args) {
    Properties config = new Properties();
    config.put(StreamsConfig.APPLICATION_ID_CONFIG, "bank-favorite-amount-application");
    config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:29092");
    config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());

    Mc4CalculateFavoriteAmount wordCountApp = new Mc4CalculateFavoriteAmount();

    KafkaStreams streams = new KafkaStreams(wordCountApp.createTopology(), config);
    streams.start();

    // shutdown hook to correctly close the streams application
    Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}

I`m trying to count messages with by names. But i got artifacts in topic:

enter image description here


Solution

  • If you simply want to count the keys, then you can discard the whole value and replace it with a 1 for every key that is seen.

    KStream<String, Bytes> textLines = builder.stream("bank-transactions", Consumed.with(Serdes.String(), Serdes.Bytes()));
    KTable<String, Long> wordCounts = textLines
            .mapValues(v -> 1L)
            .groupByKey(Serialized.with(Serdes.String(), Serdes.Long()))
            .count();
    
    wordCounts.toStream().to("person-transaction-frequency", Produced.with(Serdes.String(), Serdes.Long()));