gpt-4-0314· openai
Suzhen/CodeChat
flink code example
- User
flink code example
- Assistant
Apache Flink is a distributed stream-processing framework. It can be used to build highly scalable and fault-tolerant data processing pipelines.
flink code example
Apache Flink is a distributed stream-processing framework. It can be used to build highly scalable and fault-tolerant data processing pipelines.
Here is a simple Flink code example that demonstrates how to read data from a text file, perform Word Count operation, and write the output to a text file.
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
public class WordCount {
// Define a function to split input lines into words
public static final class Tokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> {
@Override
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
// Normalize input line and split it into words
String[] words = value.toLowerCase().split("\\W+");
for (String word : words) {
if (word.length() > 0) {
// Emit the word with count 1
out.collect(new Tuple2<>(word, 1));
}
}
}
}
public static void main(String[] args) throws Exception {
// Check that we have the correct number of arguments
if (args.length != 2) {
System.err.println("Usage: WordCount <input_file> <output_file>");
return;
}
// Set up the Flink execution environment
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
// Read input file and create a DataSet of string values
DataSet<String> text = env.readTextFile(args[0]);
// Tokenize the input, group by words, sum the counts, and write the result
DataSet<Tuple2<String, Integer>> counts = text
.flatMap(new Tokenizer())
.groupBy(0)
.sum(1);
// Write the output to a file
counts.writeAsText(args[1]).setParallelism(1);
// Execute the Flink program
env.execute("Word Count Example");
}
}
Before you can run this code, you'll need to set up a Flink development environment and include the required dependencies in your project. You can find more information on how to do this in the official Flink documentation.