PyFlink 需要 Python 版本(3.6、3.7、3.8 或 3.9)。请运行以下命令以确保它满足要求:
python --version
1.创建python3.9虚拟环境,具体请参考:
②. Jupyter Notebook中配置多版本Python
2. 安装PyFlink
python -m pip install apache-flink==1.16.0
如果速度太慢,可以设置国内源:
python -m pip install apache-flink==1.16.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
注意:从 Flink 1.11 开始,支持在 Windows 上本地运行 PyFlink 作业,因此你可以在 Windows 上开发和调试 PyFlink 作业。
3. 编写代码
word_count.py
import argparseimport loggingimport sysfrom pyflink.common import WatermarkStrategy, Encoder, Typesfrom pyflink.datastream import StreamExecutionEnvironment, RuntimeExecutionModefrom pyflink.datastream.connectors.file_system import (FileSource, StreamFormat, FileSink,OutputFileConfig, RollingPolicy)word_count_data = ["To be, or not to be,--that is the question:--","Whether 'tis nobler in the mind to suffer","The slings and arrows of outrageous fortune","Or to take arms against a sea of troubles,","And by opposing end them?--To die,--to sleep,--","No more; and by a sleep to say we end","The heartache, and the thousand natural shocks","That flesh is heir to,--'tis a consummation","Devoutly to be wish'd. To die,--to sleep;--","To sleep! perchance to dream:--ay, there's the rub;","For in that sleep of death what dreams may come,","When we have shuffled off this mortal coil,","Must give us pause: there's the respect","That makes calamity of so long life;","For who would bear the whips and scorns of time,","The oppressor's wrong, the proud man's contumely,","The pangs of despis'd love, the law's delay,","The insolence of office, and the spurns","That patient merit of the unworthy takes,","When he himself might his quietus make","With a bare bodkin? who would these fardels bear,","To grunt and sweat under a weary life,","But that the dread of something after death,--","The undiscover'd country, from whose bourn","No traveller returns,--puzzles the will,","And makes us rather bear those ills we have","Than fly to others that we know not of?","Thus conscience does make cowards of us all;","And thus the native hue of resolution","Is sicklied o'er with the pale cast of thought;","And enterprises of great pith and moment,","With this regard, their currents turn awry,","And lose the name of action.--Soft you now!","The fair Ophelia!--Nymph, in thy orisons","Be all my sins remember'd."]def word_count(input_path, output_path):env = StreamExecutionEnvironment.get_execution_environment()env.set_runtime_mode(RuntimeExecutionMode.BATCH)# write all the data to one fileenv.set_parallelism(1)# define the sourceif input_path is not None:ds = env.from_source(source=FileSource.for_record_stream_format(StreamFormat.text_line_format(),input_path).process_static_file_set().build(),watermark_strategy=WatermarkStrategy.for_monotonous_timestamps(),source_name="file_source")else:print("Executing word_count example with default input data set.")print("Use --input to specify file input.")ds = env.from_collection(word_count_data)def split(line):yield from line.split()# compute word countds = ds.flat_map(split) \.map(lambda i: (i, 1), output_type=Types.TUPLE([Types.STRING(), Types.INT()])) \.key_by(lambda i: i[0]) \.reduce(lambda i, j: (i[0], i[1] + j[1]))# define the sinkif output_path is not None:ds.sink_to(sink=FileSink.for_row_format(base_path=output_path,encoder=Encoder.simple_string_encoder()).with_output_file_config(OutputFileConfig.builder().with_part_prefix("prefix").with_part_suffix(".ext").build()).with_rolling_policy(RollingPolicy.default_rolling_policy()).build())else:print("Printing result to stdout. Use --output to specify output path.")ds.print()# submit for executionenv.execute()if __name__ == '__main__':logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")parser = argparse.ArgumentParser()parser.add_argument('--input',dest='input',required=False,help='Input file to process.')parser.add_argument('--output',dest='output',required=False,help='Output file to write results to.')argv = sys.argv[1:]known_args, _ = parser.parse_known_args(argv)word_count(known_args.input, known_args.output)
4. 运行代码
python word_count.py
5. 运行结果
(a,5)(Be,1)(Is,1)(No,2)(Or,1)(To,4)(be,1)(by,2)(he,1)(in,3)(is,2)(my,1)(of,14)(or,1)(so,1)(to,7)(us,3)(we,4)(And,5)(But,1)(For,2)(The,7)(all,1)(and,7)(be,,1)(end,2)(fly,1)(his,1)(hue,1)(may,1)(not,2)(of?,1)(off,1)(say,1)(sea,1)(the,15)(thy,1)(who,2)(you,1)('tis,1)(Must,1)(Than,1)(That,3)(Thus,1)(When,2)(With,2)(all;,1)(arms,1)(bare,1)(bear,2)(cast,1)(does,1)(fair,1)(from,1)(give,1)(have,2)(heir,1)(ills,1)(know,1)(long,1)(lose,1)(make,2)(mind,1)(name,1)(now!,1)(o'er,1)(pale,1)(pith,1)(rub;,1)(sins,1)(take,1)(that,3)(this,2)(thus,1)(turn,1)(what,1)(with,1)(after,1)(awry,,1)(bear,,1)(bourn,1)(coil,,1)(come,,1)(death,1)(dread,1)(flesh,1)(great,1)(grunt,1)(law's,1)(life,,1)(life;,1)(love,,1)(makes,2)(man's,1)(merit,1)(might,1)(more;,1)(pangs,1)(proud,1)(sleep,2)(sweat,1)(their,1)(these,1)(those,1)(time,,1)(under,1)(weary,1)(whips,1)(whose,1)(will,,1)(would,2)(arrows,1)(delay,,1)(dreams,1)(mortal,1)(native,1)(nobler,1)(others,1)(pause:,1)(rather,1)(scorns,1)(shocks,1)(sleep!,1)(slings,1)(spurns,1)(suffer,1)(takes,,1)(wrong,,1)(Whether,1)(against,1)(bodkin?,1)(cowards,1)(fardels,1)(fortune,1)(himself,1)(moment,,1)(natural,1)(office,,1)(orisons,1)(patient,1)(quietus,1)(regard,,1)(respect,1)(there's,2)(wish'd.,1)(Devoutly,1)(calamity,1)(country,,1)(currents,1)(death,--,1)(despis'd,1)(die,--to,2)(opposing,1)(shuffled,1)(sicklied,1)(sleep,--,1)(sleep;--,1)(thought;,1)(thousand,1)(unworthy,1)(be,--that,1)(insolence,1)(perchance,1)(something,1)(them?--To,1)(to,--'tis,1)(traveller,1)(troubles,,1)(conscience,1)(contumely,,1)(heartache,,1)(outrageous,1)(resolution,1)(dream:--ay,,1)(enterprises,1)(oppressor's,1)(question:--,1)(remember'd.,1)(consummation,1)(undiscover'd,1)(action.--Soft,1)(Ophelia!--Nymph,,1)(returns,--puzzles,1)
至此,Pyflink入门wordcount代码编写完成。
更多实战详情请关注字节智传公众号

往期精彩
16. FlinkSql 集成 hive catalog模式进行读写数据
17. PyFlink 集成 hive catalog模式读写数据
文章转载自大数据技能圈,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




