简体   繁体   中英

How to count the frequency of each ID in kafka Topic

I have a Kafka Topic Tranfer_History in which I streamed a CSV file. Now I want to count the occurrence of each PARTY_ID . Then after I want to apply the transformation : if the count is less than 20 put it to the new topic CHURN and if greater than 20 put it to topic LOYAL #I am using JAVA

public class FirstFilterer {

public static void main(String[] args) {

    final StreamsBuilder builder = new StreamsBuilder();

    /*input messages example
     {"155555","11.11.2016 11:12}
     {"155555","11.11.2016 13:12}
     {"155556","11.11.2016 13:12}
     result to be achived:
     {"155555","2"}
     {"155556","1"}
     */
    builder.stream("test_topic_3")
//                .map()
                  .groupByKey()
//                .windowedBy(Window) // This may or may not be required
                  .count()
                  .toStream()
                  .map(
                    (key,count) -> new KeyValue<>(key.toString(),count)
            )
            .to("test_output_filtered_3");//this topic is empty after the run

I am new to Kafka don't know much plz help me out

This can be achieved through Kafka Streams very easily. First ensure that you have a background of KStream & KTable. You need to follow below steps.

 builder.<Keytype, ValueType>stream(YourInputTopic))
    .map()
    .groupByKey()
    .windowedBy(TimeWindows.of(Duration.ofSeconds(10))) // This may or may not be required 
                                                           in your case
    .count()
    .toStream()
    .map((Windowed<String> key, Long count) -> new KeyValue<>(key.key(),count.toString()))
    .filter((k,v)-> Long.parseLong(v) > 20) // This is the filter
    .to(TopicName));

Note: This is just a pseudocode which will give you an idea of how to achieve this feat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM