Apache Cassandra Connector

This connector provides sinks that writes data into a Apache Cassandra database. To use this connector, add the following dependency to your project:

  1. <dependency>
  2. <groupId>org.apache.flink</groupId>
  3. <artifactId>flink-connector-cassandra_2.11</artifactId>
  4. <version>1.9.0</version>
  5. </dependency>

Note that the streaming connectors are currently NOT part of the binary distribution. See how to link with them for cluster execution here.

Installing Apache Cassandra

There are multiple ways to bring up a Cassandra instance on local machine:

Cassandra Sinks

Configurations

Flink’s Cassandra sink are created by using the static CassandraSink.addSink(DataStream input) method.This method returns a CassandraSinkBuilder, which offers methods to further configure the sink, and finally build() the sink instance.

The following configuration methods can be used:

  • setQuery(String query)
    • Sets the upsert query that is executed for every record the sink receives.
    • The query is internally treated as CQL statement.
    • DO set the upsert query for processing Tuple data type.
    • DO NOT set the query for processing POJO data types.
  • setClusterBuilder()
    • Sets the cluster builder that is used to configure the connection to cassandra with more sophisticated settings such as consistency level, retry policy and etc.
  • setHost(String host[, int port])
    • Simple version of setClusterBuilder() with host/port information to connect to Cassandra instances
  • setMapperOptions(MapperOptions options)
    • Sets the mapper options that are used to configure the DataStax ObjectMapper.
    • Only applies when processing POJO data types.
  • setMaxConcurrentRequests(int maxConcurrentRequests, Duration timeout)
    • Sets the maximum allowed number of concurrent requests with a timeout for acquiring permits to execute.
    • Only applies when enableWriteAheadLog() is not configured.
  • enableWriteAheadLog([CheckpointCommitter committer])
    • An optional setting
    • Allows exactly-once processing for non-deterministic algorithms.
  • setFailureHandler([CassandraFailureHandler failureHandler])
    • An optional setting
    • Sets the custom failure handler.
  • build()
    • Finalizes the configuration and constructs the CassandraSink instance.

Write-ahead Log

A checkpoint committer stores additional information about completed checkpointsin some resource. This information is used to prevent a full replay of the lastcompleted checkpoint in case of a failure.You can use a CassandraCommitter to store these in a separate table in cassandra.Note that this table will NOT be cleaned up by Flink.

Flink can provide exactly-once guarantees if the query is idempotent (meaning it can be applied multipletimes without changing the result) and checkpointing is enabled. In case of a failure the failedcheckpoint will be replayed completely.

Furthermore, for non-deterministic programs the write-ahead log has to be enabled. For such a programthe replayed checkpoint may be completely different than the previous attempt, which may leave thedatabase in an inconsistent state since part of the first attempt may already be written.The write-ahead log guarantees that the replayed checkpoint is identical to the first attempt.Note that that enabling this feature will have an adverse impact on latency.

Note: The write-ahead log functionality is currently experimental. In many cases it is sufficient to use the connector without enabling it. Please report problems to the development mailing list.

Checkpointing and Fault Tolerance

With checkpointing enabled, Cassandra Sink guarantees at-least-once delivery of action requests to C* instance.

More details on checkpoints docs and fault tolerance guarantee docs

Examples

The Cassandra sinks currently support both Tuple and POJO data types, and Flink automatically detects which type of input is used. For general use case of those streaming data type, please refer to Supported Data Types. We show two implementations based on SocketWindowWordCount, for Pojo and Tuple data types respectively.

In all these examples, we assumed the associated Keyspace example and Table wordcount have been created.

  1. CREATE KEYSPACE IF NOT EXISTS example
  2. WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};
  3. CREATE TABLE IF NOT EXISTS example.wordcount (
  4. word text,
  5. count bigint,
  6. PRIMARY KEY(word)
  7. );

Cassandra Sink Example for Streaming Tuple Data Type

While storing the result with Java/Scala Tuple data type to a Cassandra sink, it is required to set a CQL upsert statement (via setQuery(‘stmt’)) to persist each record back to the database. With the upsert query cached as PreparedStatement, each Tuple element is converted to parameters of the statement.

For details about PreparedStatement and BoundStatement, please visit DataStax Java Driver manual

  1. // get the execution environment
  2. final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
  3. // get input data by connecting to the socket
  4. DataStream<String> text = env.socketTextStream(hostname, port, "\n");
  5. // parse the data, group it, window it, and aggregate the counts
  6. DataStream<Tuple2<String, Long>> result = text
  7. .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
  8. @Override
  9. public void flatMap(String value, Collector<Tuple2<String, Long>> out) {
  10. // normalize and split the line
  11. String[] words = value.toLowerCase().split("\\s");
  12. // emit the pairs
  13. for (String word : words) {
  14. //Do not accept empty word, since word is defined as primary key in C* table
  15. if (!word.isEmpty()) {
  16. out.collect(new Tuple2<String, Long>(word, 1L));
  17. }
  18. }
  19. }
  20. })
  21. .keyBy(0)
  22. .timeWindow(Time.seconds(5))
  23. .sum(1);
  24. CassandraSink.addSink(result)
  25. .setQuery("INSERT INTO example.wordcount(word, count) values (?, ?);")
  26. .setHost("127.0.0.1")
  27. .build();
  1. val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
  2. // get input data by connecting to the socket
  3. val text: DataStream[String] = env.socketTextStream(hostname, port, '\n')
  4. // parse the data, group it, window it, and aggregate the counts
  5. val result: DataStream[(String, Long)] = text
  6. // split up the lines in pairs (2-tuples) containing: (word,1)
  7. .flatMap(_.toLowerCase.split("\\s"))
  8. .filter(_.nonEmpty)
  9. .map((_, 1L))
  10. // group by the tuple field "0" and sum up tuple field "1"
  11. .keyBy(0)
  12. .timeWindow(Time.seconds(5))
  13. .sum(1)
  14. CassandraSink.addSink(result)
  15. .setQuery("INSERT INTO example.wordcount(word, count) values (?, ?);")
  16. .setHost("127.0.0.1")
  17. .build()
  18. result.print().setParallelism(1)

Cassandra Sink Example for Streaming POJO Data Type

An example of streaming a POJO data type and store the same POJO entity back to Cassandra. In addition, this POJO implementation needs to follow DataStax Java Driver Manual to annotate the class as each field of this entity is mapped to an associated column of the designated table using the DataStax Java Driver com.datastax.driver.mapping.Mapper class.

The mapping of each table column can be defined through annotations placed on a field declaration in the Pojo class. For details of the mapping, please refer to CQL documentation on Definition of Mapped Classes and CQL Data types

  1. // get the execution environment
  2. final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
  3. // get input data by connecting to the socket
  4. DataStream<String> text = env.socketTextStream(hostname, port, "\n");
  5. // parse the data, group it, window it, and aggregate the counts
  6. DataStream<WordCount> result = text
  7. .flatMap(new FlatMapFunction<String, WordCount>() {
  8. public void flatMap(String value, Collector<WordCount> out) {
  9. // normalize and split the line
  10. String[] words = value.toLowerCase().split("\\s");
  11. // emit the pairs
  12. for (String word : words) {
  13. if (!word.isEmpty()) {
  14. //Do not accept empty word, since word is defined as primary key in C* table
  15. out.collect(new WordCount(word, 1L));
  16. }
  17. }
  18. }
  19. })
  20. .keyBy("word")
  21. .timeWindow(Time.seconds(5))
  22. .reduce(new ReduceFunction<WordCount>() {
  23. @Override
  24. public WordCount reduce(WordCount a, WordCount b) {
  25. return new WordCount(a.getWord(), a.getCount() + b.getCount());
  26. }
  27. });
  28. CassandraSink.addSink(result)
  29. .setHost("127.0.0.1")
  30. .setMapperOptions(() -> new Mapper.Option[]{Mapper.Option.saveNullFields(true)})
  31. .build();
  32. @Table(keyspace = "example", name = "wordcount")
  33. public class WordCount {
  34. @Column(name = "word")
  35. private String word = "";
  36. @Column(name = "count")
  37. private long count = 0;
  38. public WordCount() {}
  39. public WordCount(String word, long count) {
  40. this.setWord(word);
  41. this.setCount(count);
  42. }
  43. public String getWord() {
  44. return word;
  45. }
  46. public void setWord(String word) {
  47. this.word = word;
  48. }
  49. public long getCount() {
  50. return count;
  51. }
  52. public void setCount(long count) {
  53. this.count = count;
  54. }
  55. @Override
  56. public String toString() {
  57. return getWord() + " : " + getCount();
  58. }
  59. }