批处理示例

以下示例程序展示了Flink的不同应用程序,从简单的字数统计到图形算法。代码示例说明了Flink的DataSet API的使用

可以在Flink源存储库flink-examples-batch模块中找到以下和更多示例的完整源代码

运行一个例子

为了运行Flink示例,我们假设您有一个正在运行的Flink实例。导航中的“快速入门”和“设置”选项卡描述了启动Flink的各种方法。

最简单的方法是运行./bin/start-cluster.sh,默认情况下启动一个带有一个JobManager和一个TaskManager的本地集群。

Flink的每个二进制版本都包含一个examples目录,其中包含此页面上每个示例的jar文件。

要运行WordCount示例,请发出以下命令:

  1. ./bin/flink run ./examples/batch/WordCount.jar

其他示例可以以类似的方式启动。

请注意,通过使用内置数据,许多示例在不传递任何参数的情况下运行。要使用实际数据运行WordCount,您必须将路径传递给数据:

  1. ./bin/flink run ./examples/batch/WordCount.jar --input /path/to/some/text/data --output /path/to/result

请注意,非本地文件系统需要模式前缀,例如hdfs://

字数

WordCount是大数据处理系统的“HelloWorld”。它计算文本集合中单词的频率。该算法分两步进行:首先,文本将文本分成单个单词。其次,对单词进行分组和计数。

  1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
  2. DataSet<String> text = env.readTextFile("/path/to/file");
  3. DataSet<Tuple2<String, Integer>> counts =
  4. // split up the lines in pairs (2-tuples) containing: (word,1)
  5. text.flatMap(new Tokenizer())
  6. // group by the tuple field "0" and sum up tuple field "1"
  7. .groupBy(0)
  8. .sum(1);
  9. counts.writeAsCsv(outputPath, "\n", " ");
  10. // User-defined functions
  11. public static class Tokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> {
  12. @Override
  13. public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
  14. // normalize and split the line
  15. String[] tokens = value.toLowerCase().split("\\W+");
  16. // emit the pairs
  17. for (String token : tokens) {
  18. if (token.length() > 0) {
  19. out.collect(new Tuple2<String, Integer>(token, 1));
  20. }
  21. }
  22. }
  23. }

字计数示例实现上述算法的输入参数:—input <path> —output <path>作为测试数据,任何文本文件都可以。

  1. val env = ExecutionEnvironment.getExecutionEnvironment
  2. // get input data
  3. val text = env.readTextFile("/path/to/file")
  4. val counts = text.flatMap { _.toLowerCase.split("\\W+") filter { _.nonEmpty } }
  5. .map { (_, 1) }
  6. .groupBy(0)
  7. .sum(1)
  8. counts.writeAsCsv(outputPath, "\n", " ")

字计数示例实现上述算法的输入参数:—input <path> —output <path>作为测试数据,任何文本文件都可以。

网页排名

PageRank算法计算链接定义的图形中页面的“重要性”,链接指向一个页面到另一个页面。它是一种迭代图算法,这意味着它重复应用相同的计算。在每次迭代中,每个页面在其所有邻居上分配其当前等级,并将其新等级计算为从其邻居接收的等级的纳税总和。PageRank算法由Google搜索引擎推广,该搜索引擎利用网页的重要性对搜索查询的结果进行排名。

在这个简单的例子中,PageRank通过批量迭代和固定数量的迭代来实现。

  1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
  2. // read the pages and initial ranks by parsing a CSV file
  3. DataSet<Tuple2<Long, Double>> pagesWithRanks = env.readCsvFile(pagesInputPath)
  4. .types(Long.class, Double.class)
  5. // the links are encoded as an adjacency list: (page-id, Array(neighbor-ids))
  6. DataSet<Tuple2<Long, Long[]>> pageLinkLists = getLinksDataSet(env);
  7. // set iterative data set
  8. IterativeDataSet<Tuple2<Long, Double>> iteration = pagesWithRanks.iterate(maxIterations);
  9. DataSet<Tuple2<Long, Double>> newRanks = iteration
  10. // join pages with outgoing edges and distribute rank
  11. .join(pageLinkLists).where(0).equalTo(0).flatMap(new JoinVertexWithEdgesMatch())
  12. // collect and sum ranks
  13. .groupBy(0).sum(1)
  14. // apply dampening factor
  15. .map(new Dampener(DAMPENING_FACTOR, numPages));
  16. DataSet<Tuple2<Long, Double>> finalPageRanks = iteration.closeWith(
  17. newRanks,
  18. newRanks.join(iteration).where(0).equalTo(0)
  19. // termination condition
  20. .filter(new EpsilonFilter()));
  21. finalPageRanks.writeAsCsv(outputPath, "\n", " ");
  22. // User-defined functions
  23. public static final class JoinVertexWithEdgesMatch
  24. implements FlatJoinFunction<Tuple2<Long, Double>, Tuple2<Long, Long[]>,
  25. Tuple2<Long, Double>> {
  26. @Override
  27. public void join(<Tuple2<Long, Double> page, Tuple2<Long, Long[]> adj,
  28. Collector<Tuple2<Long, Double>> out) {
  29. Long[] neighbors = adj.f1;
  30. double rank = page.f1;
  31. double rankToDistribute = rank / ((double) neigbors.length);
  32. for (int i = 0; i < neighbors.length; i++) {
  33. out.collect(new Tuple2<Long, Double>(neighbors[i], rankToDistribute));
  34. }
  35. }
  36. }
  37. public static final class Dampener implements MapFunction<Tuple2<Long,Double>, Tuple2<Long,Double>> {
  38. private final double dampening, randomJump;
  39. public Dampener(double dampening, double numVertices) {
  40. this.dampening = dampening;
  41. this.randomJump = (1 - dampening) / numVertices;
  42. }
  43. @Override
  44. public Tuple2<Long, Double> map(Tuple2<Long, Double> value) {
  45. value.f1 = (value.f1 * dampening) + randomJump;
  46. return value;
  47. }
  48. }
  49. public static final class EpsilonFilter
  50. implements FilterFunction<Tuple2<Tuple2<Long, Double>, Tuple2<Long, Double>>> {
  51. @Override
  52. public boolean filter(Tuple2<Tuple2<Long, Double>, Tuple2<Long, Double>> value) {
  53. return Math.abs(value.f0.f1 - value.f1.f1) > EPSILON;
  54. }
  55. }

所述的PageRank程序实现上述实施例。它需要运行以下参数:—pages<path> —links <path> —output <path> —numPages <n> —iterations <n>

  1. // User-defined types
  2. case class Link(sourceId: Long, targetId: Long)
  3. case class Page(pageId: Long, rank: Double)
  4. case class AdjacencyList(sourceId: Long, targetIds: Array[Long])
  5. // set up execution environment
  6. val env = ExecutionEnvironment.getExecutionEnvironment
  7. // read the pages and initial ranks by parsing a CSV file
  8. val pages = env.readCsvFile[Page](pagesInputPath)
  9. // the links are encoded as an adjacency list: (page-id, Array(neighbor-ids))
  10. val links = env.readCsvFile[Link](linksInputPath)
  11. // assign initial ranks to pages
  12. val pagesWithRanks = pages.map(p => Page(p, 1.0 / numPages))
  13. // build adjacency list from link input
  14. val adjacencyLists = links
  15. // initialize lists
  16. .map(e => AdjacencyList(e.sourceId, Array(e.targetId)))
  17. // concatenate lists
  18. .groupBy("sourceId").reduce {
  19. (l1, l2) => AdjacencyList(l1.sourceId, l1.targetIds ++ l2.targetIds)
  20. }
  21. // start iteration
  22. val finalRanks = pagesWithRanks.iterateWithTermination(maxIterations) {
  23. currentRanks =>
  24. val newRanks = currentRanks
  25. // distribute ranks to target pages
  26. .join(adjacencyLists).where("pageId").equalTo("sourceId") {
  27. (page, adjacent, out: Collector[Page]) =>
  28. for (targetId <- adjacent.targetIds) {
  29. out.collect(Page(targetId, page.rank / adjacent.targetIds.length))
  30. }
  31. }
  32. // collect ranks and sum them up
  33. .groupBy("pageId").aggregate(SUM, "rank")
  34. // apply dampening factor
  35. .map { p =>
  36. Page(p.pageId, (p.rank * DAMPENING_FACTOR) + ((1 - DAMPENING_FACTOR) / numPages))
  37. }
  38. // terminate if no rank update was significant
  39. val termination = currentRanks.join(newRanks).where("pageId").equalTo("pageId") {
  40. (current, next, out: Collector[Int]) =>
  41. // check for significant update
  42. if (math.abs(current.rank - next.rank) > EPSILON) out.collect(1)
  43. }
  44. (newRanks, termination)
  45. }
  46. val result = finalRanks
  47. // emit result
  48. result.writeAsCsv(outputPath, "\n", " ")

he PageRankprogram implements the above example.It requires the following parameters to run: —pages <path>—links <path> —output <path> —numPages <n> —iterations<n>.

输入文件是纯文本文件,必须格式如下:

  • 页面表示为由新行字符分隔的(长)ID。
    • 例如,"1\n2\n12\n42\n63\n"给出五个页面ID为1,2,12,42和63的页面。
  • 链接表示为由空格字符分隔的页面ID对。链接由换行符分隔:
    • 例如,"12\n2 12\n1 12\n42 63\n"给出四个(定向)链接(1) - >(2),(2) - >(12),(1) - >(12)和(42)- >(63)。对于这个简单的实现,要求每个页面至少有一个传入链接和一个传出链接(页面可以指向自身)。

连接组件

连通分量算法通过为同一连接部分中的所有顶点分配相同的组件ID来识别较大图形的部分。与PageRank类似,Connected Components是一种迭代算法。在每个步骤中,每个顶点将其当前组件ID传播到其所有邻居。如果顶点小于其自己的组件ID,则顶点接受来自邻居的组件ID。

此实现使用增量迭代:未更改其组件ID的顶点不参与下一步。这会产生更好的性能,因为后面的迭代通常只处理一些异常值顶点。

  1. // read vertex and edge data
  2. DataSet<Long> vertices = getVertexDataSet(env);
  3. DataSet<Tuple2<Long, Long>> edges = getEdgeDataSet(env).flatMap(new UndirectEdge());
  4. // assign the initial component IDs (equal to the vertex ID)
  5. DataSet<Tuple2<Long, Long>> verticesWithInitialId = vertices.map(new DuplicateValue<Long>());
  6. // open a delta iteration
  7. DeltaIteration<Tuple2<Long, Long>, Tuple2<Long, Long>> iteration =
  8. verticesWithInitialId.iterateDelta(verticesWithInitialId, maxIterations, 0);
  9. // apply the step logic:
  10. DataSet<Tuple2<Long, Long>> changes = iteration.getWorkset()
  11. // join with the edges
  12. .join(edges).where(0).equalTo(0).with(new NeighborWithComponentIDJoin())
  13. // select the minimum neighbor component ID
  14. .groupBy(0).aggregate(Aggregations.MIN, 1)
  15. // update if the component ID of the candidate is smaller
  16. .join(iteration.getSolutionSet()).where(0).equalTo(0)
  17. .flatMap(new ComponentIdFilter());
  18. // close the delta iteration (delta and new workset are identical)
  19. DataSet<Tuple2<Long, Long>> result = iteration.closeWith(changes, changes);
  20. // emit result
  21. result.writeAsCsv(outputPath, "\n", " ");
  22. // User-defined functions
  23. public static final class DuplicateValue<T> implements MapFunction<T, Tuple2<T, T>> {
  24. @Override
  25. public Tuple2<T, T> map(T vertex) {
  26. return new Tuple2<T, T>(vertex, vertex);
  27. }
  28. }
  29. public static final class UndirectEdge
  30. implements FlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Long>> {
  31. Tuple2<Long, Long> invertedEdge = new Tuple2<Long, Long>();
  32. @Override
  33. public void flatMap(Tuple2<Long, Long> edge, Collector<Tuple2<Long, Long>> out) {
  34. invertedEdge.f0 = edge.f1;
  35. invertedEdge.f1 = edge.f0;
  36. out.collect(edge);
  37. out.collect(invertedEdge);
  38. }
  39. }
  40. public static final class NeighborWithComponentIDJoin
  41. implements JoinFunction<Tuple2<Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>> {
  42. @Override
  43. public Tuple2<Long, Long> join(Tuple2<Long, Long> vertexWithComponent, Tuple2<Long, Long> edge) {
  44. return new Tuple2<Long, Long>(edge.f1, vertexWithComponent.f1);
  45. }
  46. }
  47. public static final class ComponentIdFilter
  48. implements FlatMapFunction<Tuple2<Tuple2<Long, Long>, Tuple2<Long, Long>>,
  49. Tuple2<Long, Long>> {
  50. @Override
  51. public void flatMap(Tuple2<Tuple2<Long, Long>, Tuple2<Long, Long>> value,
  52. Collector<Tuple2<Long, Long>> out) {
  53. if (value.f0.f1 < value.f1.f1) {
  54. out.collect(value.f0);
  55. }
  56. }
  57. }

ConnectedComponents程序实现上述实施例。它需要运行以下参数:—vertices<path> —edges <path> —output <path> —iterations <n>

  1. // set up execution environment
  2. val env = ExecutionEnvironment.getExecutionEnvironment
  3. // read vertex and edge data
  4. // assign the initial components (equal to the vertex id)
  5. val vertices = getVerticesDataSet(env).map { id => (id, id) }
  6. // undirected edges by emitting for each input edge the input edges itself and an inverted
  7. // version
  8. val edges = getEdgesDataSet(env).flatMap { edge => Seq(edge, (edge._2, edge._1)) }
  9. // open a delta iteration
  10. val verticesWithComponents = vertices.iterateDelta(vertices, maxIterations, Array(0)) {
  11. (s, ws) =>
  12. // apply the step logic: join with the edges
  13. val allNeighbors = ws.join(edges).where(0).equalTo(0) { (vertex, edge) =>
  14. (edge._2, vertex._2)
  15. }
  16. // select the minimum neighbor
  17. val minNeighbors = allNeighbors.groupBy(0).min(1)
  18. // update if the component of the candidate is smaller
  19. val updatedComponents = minNeighbors.join(s).where(0).equalTo(0) {
  20. (newVertex, oldVertex, out: Collector[(Long, Long)]) =>
  21. if (newVertex._2 < oldVertex._2) out.collect(newVertex)
  22. }
  23. // delta and new workset are identical
  24. (updatedComponents, updatedComponents)
  25. }
  26. verticesWithComponents.writeAsCsv(outputPath, "\n", " ")

这个PageRank程序实现了上面的例子。它需要运行以下参数:—pages <path>—links <path> —output <path> —numPages <n> —iterations<n>

输入文件是纯文本文件,必须格式如下:

  • 顶点表示为ID并用换行符分隔。
    • 例如,"1\n2\n12\n42\n63\n"给出五个顶点(1),(2),(12),(42)和(63)。
  • 边缘表示为由空格字符分隔的顶点ID的对。边线由换行符分隔:
    • 例如,"12\n2 12\n1 12\n42 63\n"给出四个(无向)链路(1) - (2),(2) - (12),(1) - (12)和(42) -(63)。