{"id":13697636,"url":"https://github.com/fhussonnois/kafkastreams-cep","last_synced_at":"2025-04-07T05:11:55.120Z","repository":{"id":9116697,"uuid":"60930425","full_name":"fhussonnois/kafkastreams-cep","owner":"fhussonnois","description":"Complex Event Processing on top of Kafka Streams","archived":false,"fork":false,"pushed_at":"2023-12-16T20:24:35.000Z","size":444,"stargazers_count":311,"open_issues_count":6,"forks_count":62,"subscribers_count":20,"default_branch":"master","last_synced_at":"2025-03-30T21:13:43.200Z","etag":null,"topics":["cep","complex-event-processing","kafka","kafka-streams"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fhussonnois.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-06-11T22:24:23.000Z","updated_at":"2025-03-27T16:43:20.000Z","dependencies_parsed_at":"2024-10-28T20:48:35.986Z","dependency_job_id":"24264ece-b116-4d87-b2ce-03c69f2cc1d4","html_url":"https://github.com/fhussonnois/kafkastreams-cep","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fhussonnois%2Fkafkastreams-cep","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fhussonnois%2Fkafkastreams-cep/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fhussonnois%2Fkafkastreams-cep/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fhussonnois%2Fkafkastreams-cep/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fhussonnois","download_url":"https://codeload.github.com/fhussonnois/kafkastreams-cep/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247595335,"owners_count":20963943,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cep","complex-event-processing","kafka","kafka-streams"],"created_at":"2024-08-02T18:01:01.026Z","updated_at":"2025-04-07T05:11:55.100Z","avatar_url":"https://github.com/fhussonnois.png","language":"Java","funding_links":[],"categories":["Libraries","大数据"],"sub_categories":["Kafka"],"readme":"Complex Event Processing on top of Kafka Streams Processor API !\n=============================================================\n[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://https://github.com/fhussonnois/kafkastreams-cep/blob/master/LICENCE)\n![build status](https://travis-ci.org/fhussonnois/kafkastreams-cep.svg?branch=master)\n\n[Apache Kafka](http://kafka.apache.org/) is a high-throughput, distributed, publish-subscribe messaging system.\n\nThis library can be used to extend the [Kafka Streams API](http://kafka.apache.org/documentation.html#streams) in order to select complex event sequences from streams.\n\nIt provides a convenient DSL to build complex event queries. \n\nThis library is still evolving and public APIs may change in future.\n\n## Quick Start\n\nAdd the KafkaStreamsCEP to the dependency of the pom.xml of your project. \nNote that the last version is currently not available in Maven Central yet.\n\n### Maven dependency\n\nFor Apache Kafka 0.10.0.1 (deprecated \u0026 not stable)\n\nAvailable in [Maven Central](https://search.maven.org/#artifactdetails%7Ccom.github.fhuss%7Ckafka-streams-cep%7C0.1.0%7Cjar)\n\n```xml\n    \u003cdependency\u003e\n      \u003cgroupId\u003ecom.github.fhuss\u003c/groupId\u003e\n      \u003cartifactId\u003ekafka-streams-cep\u003c/artifactId\u003e\n      \u003cversion\u003e0.1.0\u003c/version\u003e\n    \u003c/dependency\u003e\n```\n\nAs of Apache Kafka 1.0.0\n\n```xml\n    \u003cdependency\u003e\n      \u003cgroupId\u003ecom.github.fhuss\u003c/groupId\u003e\n      \u003cartifactId\u003ekafka-streams-cep\u003c/artifactId\u003e\n      \u003cversion\u003e1.0.0\u003c/version\u003e\n    \u003c/dependency\u003e\n```\n\n### Define a pattern\n\n```java\n        ...\n        \n        Properties streamsConfiguration = new Properties();\n        streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, \"my-first-cep-app\");\n        streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, \"localhost:9092\");\n        streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);\n        streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);\n\n        Pattern\u003cString, String\u003e pattern = new QueryBuilder\u003cString, String\u003e()\n                .select(\"select-A\")\n                    .where((event, store) -\u003e event.value().equals(\"A\"))\n                    .then()\n                .select(\"select-B\")\n                    .where(((event, store) -\u003e event.value().equals(\"B\")))\n                    .then()\n                .select(\"select-C\")\n                    .where(((event, store) -\u003e event.value().equals(\"C\")))\n                .build();\n\n        StreamsBuilder builder = new StreamsBuilder();\n\n        KStream\u003cString, String\u003e letters = builder.stream(\"Letters\");\n\n        KStream\u003cString, Sequence\u003cString, String\u003e\u003e sequences = new ComplexStreamsBuilder().stream(letters)\n                .query(\"MyLettersQuery\", pattern);\n        \n        sequences.print(Printed.toSysOut());\n\n        KafkaStreams kafkaStreams = new KafkaStreams(builder.build(), streamsConfiguration);\n        kafkaStreams.start();\n        \n        ...\n\n```\n\n## The Pattern API\n\nThe Kafka Streams CEP library defines a Pattern API that allow you to define complex event pattern sequence that will be used to select records from input streams.\n\nA complex pattern sequence is made of multiple **stages**. Each stage consists of a single **pattern** or a multiple patterns combined together with a logical AND or OR operator.\n\nThese simple patterns specify the conditions necessary to select an event from the input streams and to go to the next following stage.\n\nTo create a new complex pattern sequence you have to first create a new pattern `QueryBuilder` instance.\nA pattern query defines a sequence of events that occur in order but not necessarily in contiguous positions in the input stream.\n```java\nQueryBuilder\u003cString, Integer\u003e builder = new QueryBuilder\u003c\u003e();\n```\n\n\u003ctable\u003e\n    \u003cthead\u003e\n    \u003ctr\u003e\n        \u003cth\u003ePattern Builder Methods \u003c/th\u003e\n        \u003cth\u003eDescription \u0026 Examples\u003c/th\u003e\n    \u003c/tr\u003e\n    \u003c/thead\u003e\n    \u003ctbody\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003eselect()\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n            \u003cp\u003eDefines a new stage.\u003c/p\u003e\n            \u003cpre lang=\"java\"\u003eselect = query.select();\u003c/pre\u003e\n            \u003cp\u003eStage can also be named - by default a stage is named based on its index (0-based)\u003c/p\u003e\n            \u003cpre lang=\"java\"\u003eselect = query.select(\"my-first-stage\");\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003eoptional()\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n            \u003cp\u003eDefines that this pattern is optional. i.e. that at most one event can match this pattern.\u003c/p\u003e\n            \u003cpre lang=\"java\"\u003ebuilder.optional()\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003ezeroOrMore()\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n            \u003cp\u003eDefines that zero or multiple events can match this pattern.\u003c/p\u003e\n            \u003cpre lang=\"java\"\u003ebuilder.zeroOrMore()\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003eoneOrMore()\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n            \u003cp\u003eDefines that at least one event should match this pattern.\u003c/p\u003e\n            \u003cpre lang=\"java\"\u003ebuilder.oneOrMore()\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003etimes(#ofTimes)\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n            \u003cp\u003eDefines that a specific number of events should match this pattern.\u003c/p\u003e\n            \u003cpre lang=\"java\"\u003ebuilder.time(3)\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003ewhere(Matcher)\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n\u003cp\u003eDefines the condition under which an event should be selected to be added to the pattern sequence.\u003c/p\u003e\n\u003cp\u003eCurrently, three types of Matcher can be used to select a relevant event.\u003c/p\u003e \n\u003cstrong\u003eSimpleMatcher\u003c/strong\u003e        \n\u003cpre lang=\"java\"\u003e\nbuilder.where(new SimpleMatcher\u003cString, String\u003e() {\n    @Override\n    public boolean matches(Event\u003cString, String\u003e event) {\n           return event.value().equals(\"A\");\n    }\n});\n\u003c/pre\u003e\n\u003cstrong\u003eStatefulMatcher\u003c/strong\u003e        \n\u003cpre lang=\"java\"\u003e\nbuilder.where(new StatefulMatcher\u003cString, Integer\u003e() {\n   @Override\n   public boolean matches(Event\u003cString, Integer\u003e event, States states) {\n       double average = (int)states.get(\"sum\") / (int)states.get(\"count\");\n       return average \u003e= event.value();\n   }\n});\n\u003c/pre\u003e\n\u003cstrong\u003eSequenceMatcher\u003c/strong\u003e        \n\u003cpre lang=\"java\"\u003e\nbuilder.where(new SequenceMatcher\u003cString, Integer\u003e() {\n    @Override\n    public boolean matches(Event\u003cString, Integer\u003e event, Sequence\u003cString, Integer\u003e sequence, States states) {\n        double average = StreamSupport.stream(sequence.spliterator(), false)\n                .mapToInt(Event::value)\n                .summaryStatistics()\n                .getAverage();\n        return average \u003e= event.value(); }\n    }) \n});\n\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003efold(state, aggregator)\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n\u003cp\u003e\nThe fold() method allows to accumulate some state between each pattern. Then the defined states can be used latter to select relevant events. \u003cbr/\u003eThe aggregator function is invoke only if the input\n\u003c/p\u003e        \n\u003cpre lang=\"java\"\u003e\nbuilder.fold(\"amount\", new Aggregator\u003cString, Integer, Integer\u003e() {\n    @Override\n    public Integer aggregate(String key, Integer value, Integer accumulated) {\n        return accumulated + value;\n    }\n});\n\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003eand(Matcher)\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n        \u003cp\u003eCombines two simple patterns in a stage with a logical operator AND.\u003c/p\u003e\n\u003cpre lang=\"java\"\u003e\nbuilder.where( (event) -\u003e event.value() \u003e 0).and((event) -\u003e event.value() \u003c 10)    \n\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cpre lang=\"java\"\u003eor(Matcher)\u003c/pre\u003e\u003c/td\u003e\n        \u003ctd\u003e\n        \u003cp\u003eCombines two simple patterns in a stage with a logical operator OR.\u003c/p\u003e\n\u003cpre lang=\"java\"\u003e\nbuilder.where( (event) -\u003e event.value().equals(\"A\")).or((event) -\u003e event.value().equals(\"B\")))    \n\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n        \u003ctd\u003ewithin(time, TimeUnit)\u003c/td\u003e\n        \u003ctd\u003e\n        \u003cp\u003eDefines a time window over the entire complex pattern.\u003c/p\u003e\n\u003cpre lang=\"java\"\u003e\nbuilder.within(1, TimeUnit.HOUR)\n});\n\u003c/pre\u003e\n        \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003c/tbody\u003e\n\u003c/table\u003e\n\n## Event Selection Strategies\n\nCurrently, this library supports the following event selection strategies :  \n\n * `Strict contiguity` :  Selected events must be contiguous in the input stream. By default, this is selection strategy used to match complexes sequences.\n \n \u003cp align=\"center\"\u003e\n \u003cimg src=\"./doc/strict_contiguity.png\"/\u003e\n \u003c/p\u003e\n \nThis strategy can be chosen while defining a new stage :\n```java\nbuilder.select(\"my-stage\", Selected.withStrictContiguity())\n```   \n\n * `Skip till next match` :Irrelevant events are skipped until an event matching the next pattern is encountered. If multiple events in the stream can match the next pattern only the first of them is selected.\n\n \u003cp align=\"center\"\u003e\n \u003cimg src=\"./doc/skip_till_next_match.png\"/\u003e\n \u003c/p\u003e\n \nThis strategy can be chosen while defining a new stage :\n \n ```java\n builder.select(\"my-stage\", Selected.withSkipTilNextMatch())\n ```   \n \n * `Skip till any match` : Irrelevant events are skipped until an event matching the next pattern is encountered. All events in the stream that can match a pattern are selected.\n \n \u003cp align=\"center\"\u003e\n \u003cimg src=\"./doc/skip_till_any_match.png\"/\u003e\n \u003c/p\u003e\n \n This strategy can be chosen while defining a new stage :\n ```java\n builder.select(\"my-stage\", Selected.withSkipTilAnyMatch())\n ```   \n \n## How to match an event from a specific topic ?\n\nKafka Streams allow you to consume from multiple input topics.\n\nWhile defining a new stage you can specify the topic name on which the pattern should be applied : \n ```java\n builder.select(\"my-stage\", Selected.fromTopic(\"my-topic\")))\n ```  \n\n## Demonstration\n\nThe below example is based on the research paper **Efficient Pattern Matching over Event Streams**.\n\nImplementation based on https://people.cs.umass.edu/~yanlei/publications/sase-sigmod08.pdf\n\n### CEP Query :\n\n```\n     PATTERN SEQ(Stock+ a[ ], Stock b)\n       WHERE skip_till_next_match(a[ ], b) {\n           [symbol]\n       and\n           a[1].volume \u003e 1000\n       and\n           a[i].price \u003e avg(a[..i-1].price)\n       and\n           b.volume \u003c 80%*a[a.LEN].volume }\n       WITHIN 1 hour\n```\n\n### Build Query\n```java\n            new QueryBuilder\u003cString, StockEvent\u003e()\n            .select(\"stage-1\")\n                .where((event, states) -\u003e event.value().volume \u003e 1000)\n                .\u003cLong\u003efold(\"avg\", (k, v, curr) -\u003e v.price)\n                .then()\n            .select(\"stage-2\", Selected.withSkipTilNextMatch())\n                .zeroOrMore()\n                .where((event, states) -\u003e event.value().price \u003e (long) states.get(\"avg\"))\n                .\u003cLong\u003efold(\"avg\", (k, v, curr) -\u003e (curr + v.price) / 2)\n                .\u003cLong\u003efold(\"volume\", (k, v, curr) -\u003e v.volume)\n                .then()\n            .select(\"stage-3\", Selected.withSkipTilNextMatch())\n                .where((event, states) -\u003e event.value().volume \u003c 0.8 * (long) states.getOrElse(\"volume\", 0L))\n            .within(1, TimeUnit.HOURS)\n            .build();\n```\n\n### KStreams API:\n```java\n        Pattern\u003cObject, StockEvent\u003e pattern = ...\n\n        ComplexStreamsBuilder builder = new ComplexStreamsBuilder();\n\n        CEPStream\u003cString, StockEvent\u003e stream = builder.stream(\"StockEvents\");\n        KStream\u003cString, Sequence\u003cString, StockEvent\u003e\u003e stocks = stream.query(\"Stocks\", pattern, Queried.with(Serdes.String(), new StockEventSerde()));\n        \n        KafkaStreams streams = new KafkaStreams(builder.build(), props);\n```\n\n### Processor API:\n```java\n        Pattern\u003cObject, StockEvent\u003e pattern = ...\n\n        final String queryName = \"Stocks\";\n\n        Topology topology = new Topology()\n                .addSource(\"source\", \"StockEvents\")\n                .addProcessor(\"cep-processor\", () -\u003e new CEPProcessor\u003c\u003e(queryName, pattern), \"source\")\n                .addSink(\"sink\", \"Matches\", \"cep-processor\");\n\n        // utility class to register all stores associated with the pattern.\n        CEPStoreBuilders\u003cString, StockEvent\u003e builders = new CEPStoreBuilders\u003c\u003e();\n        builders.addStateStores(topology, \"cep-processor\", queryName, pattern, Serdes.String(), new StockEventSerde());\n        \n        CEPStoreBuilders\u003cK, V\u003e storeBuilders = new CEPStoreBuilders\u003c\u003e(queryName, pattern);\n        topology.addStateStore(storeBuilders.getEventBufferStoreBuilder(keySerde, valueSerde), \"cep-processor\");\n        topology.addStateStore(storeBuilders.getNFAStateStoreBuilder(keySerde, valueSerde), \"cep-processor\");\n        topology.addStateStore(storeBuilders.getAggregateStateStores(), \"cep-processor\");\n        \n        KafkaStreams streams = new KafkaStreams(topology, props);\n```\n\n## States\n\nTo track the states of matched sequences, KafkaStreamsCEP needs to create three persistent stores for each query.\nThis state stores will result in the creationf of the following changelog topics :  \n\n- \u003capplication_id\u003e-\u003cquery_name\u003e-streamscep-aggregates-changelog\n- \u003capplication_id\u003e-\u003cquery_name\u003e-streamscep-matched-changelog\n- \u003capplication_id\u003e-\u003cquery_name\u003e-streamscep-states-changelog\n\n\n## Demo\n\nRun the demonstration class **CEPStockDemo** :\n\n- Create Input/Ouput streams topics\n```bash\n./bin/kafka-topics --create --topic Stocks --partitions 2 --replication-factor 1 --zookeeper localhost:2181\nCreated topic \"Stocks\".\n\n/bin/kafka-topics --create --topic Matches --partitions 2 --replication-factor 1 --zookeeper localhost:2181\nCreated topic \"Matches\".\n```\n- Produce the following json events **StockEvents**:\n```bash\n./bin/kafka-console-producer --topic Stocks  --property parse.key=true --property key.separator=, --broker-list localhost:9092\n```\n\n- Input\n\n```json\nkey1,{\"name\":\"e1\",\"price\":100,\"volume\":1010}\nkey1,{\"name\":\"e2\",\"price\":120,\"volume\":990}\nkey1,{\"name\":\"e3\",\"price\":120,\"volume\":1005}\nkey1,{\"name\":\"e4\",\"price\":121,\"volume\":999}\nkey1,{\"name\":\"e5\",\"price\":120,\"volume\":999}\nkey1,{\"name\":\"e6\",\"price\":125,\"volume\":750}\nkey1,{\"name\":\"e7\",\"price\":120,\"volume\":950}\nkey1,{\"name\":\"e8\",\"price\":120,\"volume\":700}\n```\n\n- Consume from the sink topic **\"Matches\"**\n\n```bash\n./bin/kafka-console-consumer --new-consumer --topic Matches --bootstrap-server localhost:9092\n```\n- Output\n\n```json\n{\"events\":[{\"name\":\"stage-1\",\"events\":[\"e1\"]},{\"name\":\"stage-2\",\"events\":[\"e2\",\"e3\",\"e4\",\"e5\"]},{\"name\":\"stage-3\",\"events\":[\"e6\"]}]}\n{\"events\":[{\"name\":\"stage-1\",\"events\":[\"e3\"]},{\"name\":\"stage-2\",\"events\":[\"e4\"]},{\"name\":\"stage-3\",\"events\":[\"e6\"]}]}\n{\"events\":[{\"name\":\"stage-1\",\"events\":[\"e1\"]},{\"name\":\"stage-2\",\"events\":[\"e2\",\"e3\",\"e4\",\"e5\",\"e6\",\"e7\"]},{\"name\":\"stage-3\",\"events\":[\"e8\"]}]}\n{\"events\":[{\"name\":\"stage-1\",\"events\":[\"e3\"]},{\"name\":\"stage-2\",\"events\":[\"e4\",\"e6\"]},{\"name\":\"stage-3\",\"events\":[\"e8\"]}]}\n```\n\n## TODO\n * Improve test scenarios\n\n## Contributions\n\nAny feedback, bug reports and PRs are greatly appreciated! See our [guideline](./CONTRIBUTING.md)\n\n## Licence\nLicensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffhussonnois%2Fkafkastreams-cep","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffhussonnois%2Fkafkastreams-cep","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffhussonnois%2Fkafkastreams-cep/lists"}