streaming_word_count.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. ################################################################################
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. ################################################################################
  18. import argparse
  19. import logging
  20. import sys
  21. from pyflink.table import TableEnvironment, EnvironmentSettings, TableDescriptor, Schema,\
  22. DataTypes, FormatDescriptor
  23. from pyflink.table.expressions import col, lit
  24. from pyflink.table.udf import udf
  25. words = ["flink", "window", "timer", "event_time", "processing_time", "state",
  26. "connector", "pyflink", "checkpoint", "watermark", "sideoutput", "sql",
  27. "datastream", "broadcast", "asyncio", "catalog", "batch", "streaming"]
  28. max_word_id = len(words) - 1
  29. def streaming_word_count(output_path):
  30. t_env = TableEnvironment.create(EnvironmentSettings.in_streaming_mode())
  31. # define the source
  32. # randomly select 5 words per second from a predefined list
  33. t_env.create_temporary_table(
  34. 'source',
  35. TableDescriptor.for_connector('datagen')
  36. .schema(Schema.new_builder()
  37. .column('word_id', DataTypes.INT())
  38. .build())
  39. .option('fields.word_id.kind', 'random')
  40. .option('fields.word_id.min', '0')
  41. .option('fields.word_id.max', str(max_word_id))
  42. .option('rows-per-second', '5')
  43. .build())
  44. tab = t_env.from_path('source')
  45. # define the sink
  46. if output_path is not None:
  47. t_env.create_temporary_table(
  48. 'sink',
  49. TableDescriptor.for_connector('filesystem')
  50. .schema(Schema.new_builder()
  51. .column('word', DataTypes.STRING())
  52. .column('count', DataTypes.BIGINT())
  53. .build())
  54. .option('path', output_path)
  55. .format(FormatDescriptor.for_format('canal-json')
  56. .build())
  57. .build())
  58. else:
  59. print("Printing result to stdout. Use --output to specify output path.")
  60. t_env.create_temporary_table(
  61. 'sink',
  62. TableDescriptor.for_connector('print')
  63. .schema(Schema.new_builder()
  64. .column('word', DataTypes.STRING())
  65. .column('count', DataTypes.BIGINT())
  66. .build())
  67. .build())
  68. @udf(result_type='string')
  69. def id_to_word(word_id):
  70. return words[word_id]
  71. # compute word count
  72. tab.select(id_to_word(col('word_id'))).alias('word') \
  73. .group_by(col('word')) \
  74. .select(col('word'), lit(1).count) \
  75. .execute_insert('sink') \
  76. .wait()
  77. # remove .wait if submitting to a remote cluster, refer to
  78. # https://nightlies.apache.org/flink/flink-docs-stable/docs/dev/python/faq/#wait-for-jobs-to-finish-when-executing-jobs-in-mini-cluster
  79. # for more details
  80. if __name__ == '__main__':
  81. logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
  82. parser = argparse.ArgumentParser()
  83. parser.add_argument(
  84. '--output',
  85. dest='output',
  86. required=False,
  87. help='Output file to write results to.')
  88. argv = sys.argv[1:]
  89. known_args, _ = parser.parse_known_args(argv)
  90. streaming_word_count(known_args.output)