DataStream API Tutorial

    In this tutorial, you will learn how to write a simple Python DataStream pipeline. The pipeline will read data from a 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.

    If you get stuck, check out the . 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 8 or 11
    • Python 3.6, 3.7 or 3.8

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

    DataStream API applications begin by declaring an execution environment (StreamExecutionEnvironment), the context in which a streaming program is executed. This is what you will use to set the properties of your job (e.g. default parallelism, restart strategy), create your sources and finally trigger the execution of the job.

    1. env = StreamExecutionEnvironment.get_execution_environment()
    2. env.set_runtime_mode(RuntimeExecutionMode.BATCH)
    3. env.set_parallelism(1)

    Once a StreamExecutionEnvironment is created, you can use it to declare your source. Sources ingest data from external systems, such as Apache Kafka, Rabbit MQ, or Apache Pulsar, into Flink Jobs.

    To keep things simple, this walkthrough uses a source which reads data from a file.

    1. ds.sink_to(
    2. sink=FileSink.for_row_format(
    3. base_path=output_path,
    4. encoder=Encoder.simple_string_encoder())
    5. .with_output_file_config(
    6. OutputFileConfig.builder()
    7. .with_part_prefix("prefix")
    8. .with_part_suffix(".ext")
    9. .build())
    10. .with_rolling_policy(RollingPolicy.default_rolling_policy())
    11. .build()
    12. )
    13. def split(line):
    14. yield from line.split()
    15. # 计算词频
    16. ds = ds.flat_map(split) \
    17. .map(lambda i: (i, 1), output_type=Types.TUPLE([Types.STRING(), Types.INT()])) \
    18. .key_by(lambda i: i[0]) \
    19. .reduce(lambda i, j: (i[0], i[1] + j[1]))

    The last step is to execute the actual PyFlink DataStream API job. PyFlink applications are built lazily and shipped to the cluster for execution only once fully formed. To execute an application, you simply call env.execute().

    The complete code so far:

    1. import argparse
    2. import logging
    3. import sys
    4. from pyflink.common import WatermarkStrategy, Encoder, Types
    5. from pyflink.datastream import StreamExecutionEnvironment, RuntimeExecutionMode
    6. from pyflink.datastream.connectors import (FileSource, StreamFormat, FileSink, OutputFileConfig,
    7. RollingPolicy)
    8. word_count_data = ["To be, or not to be,--that is the question:--",
    9. "Whether 'tis nobler in the mind to suffer",
    10. "The slings and arrows of outrageous fortune",
    11. "Or to take arms against a sea of troubles,",
    12. "And by opposing end them?--To die,--to sleep,--",
    13. "No more; and by a sleep to say we end",
    14. "The heartache, and the thousand natural shocks",
    15. "That flesh is heir to,--'tis a consummation",
    16. "To sleep! perchance to dream:--ay, there's the rub;",
    17. "For in that sleep of death what dreams may come,",
    18. "Must give us pause: there's the respect",
    19. "That makes calamity of so long life;",
    20. "For who would bear the whips and scorns of time,",
    21. "The oppressor's wrong, the proud man's contumely,",
    22. "The pangs of despis'd love, the law's delay,",
    23. "The insolence of office, and the spurns",
    24. "That patient merit of the unworthy takes,",
    25. "When he himself might his quietus make",
    26. "With a bare bodkin? who would these fardels bear,",
    27. "To grunt and sweat under a weary life,",
    28. "But that the dread of something after death,--",
    29. "The undiscover'd country, from whose bourn",
    30. "No traveller returns,--puzzles the will,",
    31. "And makes us rather bear those ills we have",
    32. "Than fly to others that we know not of?",
    33. "Thus conscience does make cowards of us all;",
    34. "And thus the native hue of resolution",
    35. "Is sicklied o'er with the pale cast of thought;",
    36. "And enterprises of great pith and moment,",
    37. "With this regard, their currents turn awry,",
    38. "And lose the name of action.--Soft you now!",
    39. "The fair Ophelia!--Nymph, in thy orisons",
    40. "Be all my sins remember'd."]
    41. def word_count(input_path, output_path):
    42. env = StreamExecutionEnvironment.get_execution_environment()
    43. env.set_runtime_mode(RuntimeExecutionMode.BATCH)
    44. # write all the data to one file
    45. env.set_parallelism(1)
    46. # define the source
    47. if input_path is not None:
    48. ds = env.from_source(
    49. source=FileSource.for_record_stream_format(StreamFormat.text_line_format(),
    50. input_path)
    51. .process_static_file_set().build(),
    52. watermark_strategy=WatermarkStrategy.for_monotonous_timestamps(),
    53. source_name="file_source"
    54. )
    55. else:
    56. print("Executing word_count example with default input data set.")
    57. print("Use --input to specify file input.")
    58. ds = env.from_collection(word_count_data)
    59. def split(line):
    60. yield from line.split()
    61. # compute word count
    62. .map(lambda i: (i, 1), output_type=Types.TUPLE([Types.STRING(), Types.INT()])) \
    63. .key_by(lambda i: i[0]) \
    64. .reduce(lambda i, j: (i[0], i[1] + j[1]))
    65. # define the sink
    66. if output_path is not None:
    67. ds.sink_to(
    68. sink=FileSink.for_row_format(
    69. base_path=output_path,
    70. encoder=Encoder.simple_string_encoder())
    71. .with_output_file_config(
    72. OutputFileConfig.builder()
    73. .with_part_prefix("prefix")
    74. .with_part_suffix(".ext")
    75. .build())
    76. .with_rolling_policy(RollingPolicy.default_rolling_policy())
    77. .build()
    78. )
    79. else:
    80. print("Printing result to stdout. Use --output to specify output path.")
    81. ds.print()
    82. # submit for execution
    83. env.execute()
    84. if __name__ == '__main__':
    85. logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
    86. parser = argparse.ArgumentParser()
    87. parser.add_argument(
    88. '--input',
    89. dest='input',
    90. required=False,
    91. help='Input file to process.')
    92. parser.add_argument(
    93. '--output',
    94. dest='output',
    95. required=False,
    96. help='Output file to write results to.')
    97. argv = sys.argv[1:]
    98. known_args, _ = parser.parse_known_args(argv)
    99. word_count(known_args.input, known_args.output)

    Now that you defined your PyFlink program, you can run the example you just created on the command line:

    The command builds and runs your PyFlink program in a local mini cluster. You can alternatively submit it to a remote cluster using the instructions detailed in .

    1. (a,5)
    2. (Be,1)
    3. (Is,1)

    This walkthrough gives you the foundations to get started writing your own PyFlink DataStream API programs. You can also refer to PyFlink Examples for more examples. To learn more about the Python DataStream API, please refer to for more details.