Table API Tutorial

Apache Flink offers a Table API as a unified, relational API for batch and stream processing, i.e., queries are executed with the same semantics on unbounded, real-time streams or bounded, batch data sets and produce the same results. The Table API in Flink is commonly used to ease the definition of data analytics, data pipelining, and ETL applications.

What Will You Be Building?

In this tutorial, you will learn how to build a pure Python Flink Table API pipeline. The pipeline will read data from an input csv file, compute the word frequency and write the results to an output file.

Prerequisites

This walkthrough assumes that you have some familiarity with Python, but you should be able to follow along even if you come from a different programming language. It also assumes that you are familiar with basic relational concepts such as SELECT and GROUP BY clauses.

Help, I’m Stuck!

If you get stuck, check out the community support resources. In particular, Apache Flink’s user mailing list consistently ranks as one of the most active of any Apache project and a great way to get help quickly.

How To Follow Along

If you want to follow along, you will require a computer with:

  • Java 11
  • Python 3.7, 3.8, 3.9 or 3.10

Using Python Table API requires installing PyFlink, which is available on PyPI and can be easily installed using pip.

  1. $ python -m pip install apache-flink

Once PyFlink is installed, you can move on to write a Python Table API job.

Table API applications begin by declaring a table environment. This serves as the main entry point for interacting with the Flink runtime. It can be used for setting execution parameters such as restart strategy, default parallelism, etc. The table config allows setting Table API specific configurations.

  1. t_env = TableEnvironment.create(EnvironmentSettings.in_streaming_mode())
  2. t_env.get_config().set("parallelism.default", "1")

You can now create the source and sink tables:

  1. t_env.create_temporary_table(
  2. 'source',
  3. TableDescriptor.for_connector('filesystem')
  4. .schema(Schema.new_builder()
  5. .column('word', DataTypes.STRING())
  6. .build())
  7. .option('path', input_path)
  8. .format('csv')
  9. .build())
  10. tab = t_env.from_path('source')
  11. t_env.create_temporary_table(
  12. 'sink',
  13. TableDescriptor.for_connector('filesystem')
  14. .schema(Schema.new_builder()
  15. .column('word', DataTypes.STRING())
  16. .column('count', DataTypes.BIGINT())
  17. .build())
  18. .option('path', output_path)
  19. .format(FormatDescriptor.for_format('canal-json')
  20. .build())
  21. .build())

You can also use the TableEnvironment.execute_sql() method to register a source/sink table defined in DDL:

  1. my_source_ddl = """
  2. create table source (
  3. word STRING
  4. ) with (
  5. 'connector' = 'filesystem',
  6. 'format' = 'csv',
  7. 'path' = '{}'
  8. )
  9. """.format(input_path)
  10. my_sink_ddl = """
  11. create table sink (
  12. word STRING,
  13. `count` BIGINT
  14. ) with (
  15. 'connector' = 'filesystem',
  16. 'format' = 'canal-json',
  17. 'path' = '{}'
  18. )
  19. """.format(output_path)
  20. t_env.execute_sql(my_source_ddl)
  21. t_env.execute_sql(my_sink_ddl)

This registers a table named source and a table named sink in the table environment. The table source has only one column, word, and it consumes strings read from file specified by input_path. The table sink has two columns, word and count, and writes data to the file specified by output_path.

You can now create a job which reads input from table source, performs some transformations, and writes the results to table sink.

Finally, you must execute the actual Flink Python Table API job. All operations, such as creating sources, transformations and sinks are lazy. Only when execute_insert(sink_name) is called, the job will be submitted for execution.

  1. @udtf(result_types=[DataTypes.STRING()])
  2. def split(line: Row):
  3. for s in line[0].split():
  4. yield Row(s)
  5. # compute word count
  6. tab.flat_map(split).alias('word') \
  7. .group_by(col('word')) \
  8. .select(col('word'), lit(1).count) \
  9. .execute_insert('sink') \
  10. .wait()

The complete code so far:

  1. import argparse
  2. import logging
  3. import sys
  4. from pyflink.common import Row
  5. from pyflink.table import (EnvironmentSettings, TableEnvironment, TableDescriptor, Schema,
  6. DataTypes, FormatDescriptor)
  7. from pyflink.table.expressions import lit, col
  8. from pyflink.table.udf import udtf
  9. word_count_data = ["To be, or not to be,--that is the question:--",
  10. "Whether 'tis nobler in the mind to suffer",
  11. "The slings and arrows of outrageous fortune",
  12. "Or to take arms against a sea of troubles,",
  13. "And by opposing end them?--To die,--to sleep,--",
  14. "No more; and by a sleep to say we end",
  15. "The heartache, and the thousand natural shocks",
  16. "That flesh is heir to,--'tis a consummation",
  17. "Devoutly to be wish'd. To die,--to sleep;--",
  18. "To sleep! perchance to dream:--ay, there's the rub;",
  19. "For in that sleep of death what dreams may come,",
  20. "When we have shuffled off this mortal coil,",
  21. "Must give us pause: there's the respect",
  22. "That makes calamity of so long life;",
  23. "For who would bear the whips and scorns of time,",
  24. "The oppressor's wrong, the proud man's contumely,",
  25. "The pangs of despis'd love, the law's delay,",
  26. "The insolence of office, and the spurns",
  27. "That patient merit of the unworthy takes,",
  28. "When he himself might his quietus make",
  29. "With a bare bodkin? who would these fardels bear,",
  30. "To grunt and sweat under a weary life,",
  31. "But that the dread of something after death,--",
  32. "The undiscover'd country, from whose bourn",
  33. "No traveller returns,--puzzles the will,",
  34. "And makes us rather bear those ills we have",
  35. "Than fly to others that we know not of?",
  36. "Thus conscience does make cowards of us all;",
  37. "And thus the native hue of resolution",
  38. "Is sicklied o'er with the pale cast of thought;",
  39. "And enterprises of great pith and moment,",
  40. "With this regard, their currents turn awry,",
  41. "And lose the name of action.--Soft you now!",
  42. "The fair Ophelia!--Nymph, in thy orisons",
  43. "Be all my sins remember'd."]
  44. def word_count(input_path, output_path):
  45. t_env = TableEnvironment.create(EnvironmentSettings.in_streaming_mode())
  46. # write all the data to one file
  47. t_env.get_config().set("parallelism.default", "1")
  48. # define the source
  49. if input_path is not None:
  50. t_env.create_temporary_table(
  51. 'source',
  52. TableDescriptor.for_connector('filesystem')
  53. .schema(Schema.new_builder()
  54. .column('word', DataTypes.STRING())
  55. .build())
  56. .option('path', input_path)
  57. .format('csv')
  58. .build())
  59. tab = t_env.from_path('source')
  60. else:
  61. print("Executing word_count example with default input data set.")
  62. print("Use --input to specify file input.")
  63. tab = t_env.from_elements(map(lambda i: (i,), word_count_data),
  64. DataTypes.ROW([DataTypes.FIELD('line', DataTypes.STRING())]))
  65. # define the sink
  66. if output_path is not None:
  67. t_env.create_temporary_table(
  68. 'sink',
  69. TableDescriptor.for_connector('filesystem')
  70. .schema(Schema.new_builder()
  71. .column('word', DataTypes.STRING())
  72. .column('count', DataTypes.BIGINT())
  73. .build())
  74. .option('path', output_path)
  75. .format(FormatDescriptor.for_format('canal-json')
  76. .build())
  77. .build())
  78. else:
  79. print("Printing result to stdout. Use --output to specify output path.")
  80. t_env.create_temporary_table(
  81. 'sink',
  82. TableDescriptor.for_connector('print')
  83. .schema(Schema.new_builder()
  84. .column('word', DataTypes.STRING())
  85. .column('count', DataTypes.BIGINT())
  86. .build())
  87. .build())
  88. @udtf(result_types=[DataTypes.STRING()])
  89. def split(line: Row):
  90. for s in line[0].split():
  91. yield Row(s)
  92. # compute word count
  93. tab.flat_map(split).alias('word') \
  94. .group_by(col('word')) \
  95. .select(col('word'), lit(1).count) \
  96. .execute_insert('sink') \
  97. .wait()
  98. # remove .wait if submitting to a remote cluster, refer to
  99. # https://nightlies.apache.org/flink/flink-docs-stable/docs/dev/python/faq/#wait-for-jobs-to-finish-when-executing-jobs-in-mini-cluster
  100. # for more details
  101. if __name__ == '__main__':
  102. logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
  103. parser = argparse.ArgumentParser()
  104. parser.add_argument(
  105. '--input',
  106. dest='input',
  107. required=False,
  108. help='Input file to process.')
  109. parser.add_argument(
  110. '--output',
  111. dest='output',
  112. required=False,
  113. help='Output file to write results to.')
  114. argv = sys.argv[1:]
  115. known_args, _ = parser.parse_known_args(argv)
  116. word_count(known_args.input, known_args.output)

You can run this example on the command line:

  1. $ python word_count.py

The command builds and runs the Python Table API program in a local mini cluster. You can also submit the Python Table API program to a remote cluster, you can refer Job Submission Examples for more details.

Finally, you can see the execution results similar to the following:

  1. +I[To, 1]
  2. +I[be,, 1]
  3. +I[or, 1]
  4. +I[not, 1]
  5. ...

This should get you started with writing your own Flink Python Table API programs. You can also refer to PyFlink Examples for more examples. To learn more about the Python Table API, you can refer Flink Python API Docs for more details.