You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2022/04/02 02:56:24 UTC

[GitHub] [flink] dianfu commented on a change in pull request #19328: [FLINK-26969][Examples] Write operation examples of tumbling window, sliding window, session window and count window based on pyflink

dianfu commented on a change in pull request #19328:
URL: https://github.com/apache/flink/pull/19328#discussion_r840997492



##########
File path: flink-python/pyflink/examples/datastream/windowing/sliding_windowing.py
##########
@@ -0,0 +1,70 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+import logging
+import sys
+
+import argparse
+from typing import Iterable
+
+from pyflink.common import Types, WatermarkStrategy, Time
+from pyflink.common.watermark_strategy import TimestampAssigner
+from pyflink.datastream import StreamExecutionEnvironment, ProcessWindowFunction
+from pyflink.datastream.window import CountWindow, SlidingEventTimeWindows
+
+
+class TimestampAssigner(TimestampAssigner):
+    def extract_timestamp(self, value, record_timestamp) -> int:
+        return int(value[1])
+
+
+class CountWindowProcessFunction(ProcessWindowFunction[tuple, tuple, str, CountWindow]):
+    def process(self,
+                key: str,
+                content: ProcessWindowFunction.Context,
+                elements: Iterable[tuple]) -> Iterable[tuple]:
+        return [(key, len([e for e in elements]))]
+
+    def clear(self, context: ProcessWindowFunction.Context) -> None:
+        pass
+
+
+if __name__ == '__main__':
+    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        '--output',
+        dest='output',
+        required=False,
+        help='Output file to write results to.')
+
+    env = StreamExecutionEnvironment.get_execution_environment()
+    env.set_parallelism(1)
+    data_stream = env.from_collection([
+        ('hi', 1), ('hi', 2), ('hi', 3), ('hi', 4), ('hi', 5), ('hi', 8), ('hi', 9), ('hi', 15)],
+        type_info=Types.TUPLE([Types.STRING(), Types.INT()]))  # type: DataStream
+    watermark_strategy = WatermarkStrategy.for_monotonous_timestamps() \
+        .with_timestamp_assigner(TimestampAssigner())
+
+    data_stream.assign_timestamps_and_watermarks(watermark_strategy) \
+        .key_by(lambda x: x[0], key_type=Types.STRING()) \
+        .window(SlidingEventTimeWindows.of(Time.milliseconds(5), Time.milliseconds(2), Time.seconds(0))) \
+        .process(CountWindowProcessFunction(), Types.TUPLE([Types.STRING(), Types.INT()])) \

Review comment:
       What about also outputs the window start and window end to make the output more readable?

##########
File path: flink-python/pyflink/examples/datastream/windowing/count_windowing.py
##########
@@ -0,0 +1,57 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+import logging
+import sys
+
+import argparse
+from typing import Iterable
+
+from pyflink.common import Types
+from pyflink.datastream import StreamExecutionEnvironment, WindowFunction
+from pyflink.datastream.window import CountWindow
+

Review comment:
       What about rename the file to count_window to keep the naming conversion consistent with the Table API examples? 

##########
File path: flink-python/pyflink/examples/datastream/windowing/sliding_windowing.py
##########
@@ -0,0 +1,70 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+import logging
+import sys
+
+import argparse
+from typing import Iterable
+
+from pyflink.common import Types, WatermarkStrategy, Time
+from pyflink.common.watermark_strategy import TimestampAssigner
+from pyflink.datastream import StreamExecutionEnvironment, ProcessWindowFunction
+from pyflink.datastream.window import CountWindow, SlidingEventTimeWindows
+
+
+class TimestampAssigner(TimestampAssigner):
+    def extract_timestamp(self, value, record_timestamp) -> int:
+        return int(value[1])
+
+
+class CountWindowProcessFunction(ProcessWindowFunction[tuple, tuple, str, CountWindow]):

Review comment:
       Why this is a CountWindow? Shouldn't it be a TimeWindow?

##########
File path: flink-python/pyflink/examples/datastream/windowing/tumbling_windowing.py
##########
@@ -0,0 +1,71 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+import logging
+import sys
+
+import argparse
+from typing import Iterable
+
+from pyflink.common import Types, WatermarkStrategy, Time
+from pyflink.common.watermark_strategy import TimestampAssigner
+from pyflink.datastream import StreamExecutionEnvironment, ProcessWindowFunction
+from pyflink.datastream.window import TumblingEventTimeWindows, CountWindow
+
+
+class TimestampAssigner(TimestampAssigner):
+    def extract_timestamp(self, value, record_timestamp) -> int:
+        return int(value[1])
+
+
+class CountWindowProcessFunction(ProcessWindowFunction[tuple, tuple, str, CountWindow]):
+    def process(self,
+                key: str,
+                content: ProcessWindowFunction.Context,
+                elements: Iterable[tuple]) -> Iterable[tuple]:
+        return [(key, len([e for e in elements]))]
+
+    def clear(self, context: ProcessWindowFunction.Context) -> None:
+        pass
+
+
+if __name__ == '__main__':
+    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        '--output',
+        dest='output',
+        required=False,
+        help='Output file to write results to.')
+
+    env = StreamExecutionEnvironment.get_execution_environment()
+    env.set_parallelism(1)
+
+    data_stream = env.from_collection([
+        ('hi', 1), ('hi', 2), ('hi', 3), ('hi', 4), ('hi', 5), ('hi', 8), ('hi', 9), ('hi', 15)],
+        type_info=Types.TUPLE([Types.STRING(), Types.INT()]))  # type: DataStream
+
+    watermark_strategy = WatermarkStrategy.for_monotonous_timestamps() \
+        .with_timestamp_assigner(TimestampAssigner())
+    data_stream.assign_timestamps_and_watermarks(watermark_strategy) \
+        .key_by(lambda x: x[0], key_type=Types.STRING()) \
+        .window(TumblingEventTimeWindows.of(Time.milliseconds(5))) \
+        .process(CountWindowProcessFunction(), Types.TUPLE([Types.STRING(), Types.INT()])) \

Review comment:
       What about also outputs the window start and window end to make the output more readable?

##########
File path: flink-python/pyflink/examples/datastream/windowing/tumbling_windowing.py
##########
@@ -0,0 +1,71 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+import logging
+import sys
+
+import argparse
+from typing import Iterable
+
+from pyflink.common import Types, WatermarkStrategy, Time
+from pyflink.common.watermark_strategy import TimestampAssigner
+from pyflink.datastream import StreamExecutionEnvironment, ProcessWindowFunction
+from pyflink.datastream.window import TumblingEventTimeWindows, CountWindow
+
+
+class TimestampAssigner(TimestampAssigner):

Review comment:
       Give it a different name other than TimestampAssigner to avoid duplicate with the base class name?
   

##########
File path: flink-python/pyflink/examples/datastream/windowing/sliding_windowing.py
##########
@@ -0,0 +1,70 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+import logging
+import sys
+
+import argparse
+from typing import Iterable
+
+from pyflink.common import Types, WatermarkStrategy, Time
+from pyflink.common.watermark_strategy import TimestampAssigner
+from pyflink.datastream import StreamExecutionEnvironment, ProcessWindowFunction
+from pyflink.datastream.window import CountWindow, SlidingEventTimeWindows
+
+
+class TimestampAssigner(TimestampAssigner):
+    def extract_timestamp(self, value, record_timestamp) -> int:
+        return int(value[1])
+
+
+class CountWindowProcessFunction(ProcessWindowFunction[tuple, tuple, str, CountWindow]):
+    def process(self,
+                key: str,
+                content: ProcessWindowFunction.Context,
+                elements: Iterable[tuple]) -> Iterable[tuple]:
+        return [(key, len([e for e in elements]))]
+
+    def clear(self, context: ProcessWindowFunction.Context) -> None:
+        pass
+
+
+if __name__ == '__main__':
+    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        '--output',
+        dest='output',
+        required=False,
+        help='Output file to write results to.')
+
+    env = StreamExecutionEnvironment.get_execution_environment()
+    env.set_parallelism(1)
+    data_stream = env.from_collection([
+        ('hi', 1), ('hi', 2), ('hi', 3), ('hi', 4), ('hi', 5), ('hi', 8), ('hi', 9), ('hi', 15)],
+        type_info=Types.TUPLE([Types.STRING(), Types.INT()]))  # type: DataStream
+    watermark_strategy = WatermarkStrategy.for_monotonous_timestamps() \
+        .with_timestamp_assigner(TimestampAssigner())
+
+    data_stream.assign_timestamps_and_watermarks(watermark_strategy) \
+        .key_by(lambda x: x[0], key_type=Types.STRING()) \
+        .window(SlidingEventTimeWindows.of(Time.milliseconds(5), Time.milliseconds(2), Time.seconds(0))) \

Review comment:
       fix the check style

##########
File path: flink-python/pyflink/examples/datastream/windowing/sliding_windowing.py
##########
@@ -0,0 +1,70 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+import logging
+import sys
+
+import argparse
+from typing import Iterable
+
+from pyflink.common import Types, WatermarkStrategy, Time
+from pyflink.common.watermark_strategy import TimestampAssigner
+from pyflink.datastream import StreamExecutionEnvironment, ProcessWindowFunction
+from pyflink.datastream.window import CountWindow, SlidingEventTimeWindows
+
+
+class TimestampAssigner(TimestampAssigner):
+    def extract_timestamp(self, value, record_timestamp) -> int:
+        return int(value[1])
+
+
+class CountWindowProcessFunction(ProcessWindowFunction[tuple, tuple, str, CountWindow]):
+    def process(self,
+                key: str,
+                content: ProcessWindowFunction.Context,

Review comment:
       ```suggestion
                   context: ProcessWindowFunction.Context,
   ```

##########
File path: flink-python/pyflink/examples/datastream/windowing/count_windowing.py
##########
@@ -0,0 +1,57 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+import logging
+import sys
+
+import argparse
+from typing import Iterable
+
+from pyflink.common import Types
+from pyflink.datastream import StreamExecutionEnvironment, WindowFunction
+from pyflink.datastream.window import CountWindow
+
+
+class SumWindowFunction(WindowFunction[tuple, tuple, str, CountWindow]):
+    def apply(self, key: str, window: CountWindow, inputs: Iterable[tuple]):
+        result = 0
+        for i in inputs:
+            result += i[0]
+        return [(key, result)]
+
+
+if __name__ == '__main__':
+    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument(

Review comment:
       Where this parameter is used?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org