github.com/apache/beam/sdks/v2@v2.48.2/python/apache_beam/examples/windowed_wordcount.py (about)

     1  #
     2  # Licensed to the Apache Software Foundation (ASF) under one or more
     3  # contributor license agreements.  See the NOTICE file distributed with
     4  # this work for additional information regarding copyright ownership.
     5  # The ASF licenses this file to You under the Apache License, Version 2.0
     6  # (the "License"); you may not use this file except in compliance with
     7  # the License.  You may obtain a copy of the License at
     8  #
     9  #    http://www.apache.org/licenses/LICENSE-2.0
    10  #
    11  # Unless required by applicable law or agreed to in writing, software
    12  # distributed under the License is distributed on an "AS IS" BASIS,
    13  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  # See the License for the specific language governing permissions and
    15  # limitations under the License.
    16  #
    17  
    18  """A streaming word-counting workflow.
    19  
    20  Important: streaming pipeline support in Python Dataflow is in development
    21  and is not yet available for use.
    22  """
    23  
    24  # pytype: skip-file
    25  
    26  import argparse
    27  import logging
    28  
    29  import apache_beam as beam
    30  from apache_beam.transforms import window
    31  
    32  TABLE_SCHEMA = (
    33      'word:STRING, count:INTEGER, '
    34      'window_start:TIMESTAMP, window_end:TIMESTAMP')
    35  
    36  
    37  def find_words(element):
    38    import re
    39    return re.findall(r'[A-Za-z\']+', element)
    40  
    41  
    42  class FormatDoFn(beam.DoFn):
    43    def process(self, element, window=beam.DoFn.WindowParam):
    44      ts_format = '%Y-%m-%d %H:%M:%S.%f UTC'
    45      window_start = window.start.to_utc_datetime().strftime(ts_format)
    46      window_end = window.end.to_utc_datetime().strftime(ts_format)
    47      return [{
    48          'word': element[0],
    49          'count': element[1],
    50          'window_start': window_start,
    51          'window_end': window_end
    52      }]
    53  
    54  
    55  def main(argv=None):
    56    """Build and run the pipeline."""
    57  
    58    parser = argparse.ArgumentParser()
    59    parser.add_argument(
    60        '--input_topic',
    61        required=True,
    62        help='Input PubSub topic of the form "/topics/<PROJECT>/<TOPIC>".')
    63    parser.add_argument(
    64        '--output_table',
    65        required=True,
    66        help=(
    67            'Output BigQuery table for results specified as: '
    68            'PROJECT:DATASET.TABLE or DATASET.TABLE.'))
    69    known_args, pipeline_args = parser.parse_known_args(argv)
    70  
    71    with beam.Pipeline(argv=pipeline_args) as p:
    72  
    73      # Read the text from PubSub messages.
    74      lines = p | beam.io.ReadFromPubSub(known_args.input_topic)
    75  
    76      # Get the number of appearances of a word.
    77      def count_ones(word_ones):
    78        (word, ones) = word_ones
    79        return (word, sum(ones))
    80  
    81      transformed = (
    82          lines
    83          | 'Split' >> (beam.FlatMap(find_words).with_output_types(str))
    84          | 'PairWithOne' >> beam.Map(lambda x: (x, 1))
    85          | beam.WindowInto(window.FixedWindows(2 * 60, 0))
    86          | 'Group' >> beam.GroupByKey()
    87          | 'Count' >> beam.Map(count_ones)
    88          | 'Format' >> beam.ParDo(FormatDoFn()))
    89  
    90      # Write to BigQuery.
    91      # pylint: disable=expression-not-assigned
    92      transformed | 'Write' >> beam.io.WriteToBigQuery(
    93          known_args.output_table,
    94          schema=TABLE_SCHEMA,
    95          create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
    96          write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)
    97  
    98  
    99  if __name__ == '__main__':
   100    logging.getLogger().setLevel(logging.INFO)
   101    main()