部落格
2017/03/16
Python SDK 在 Apache Beam 0.6.0 版本中發布
Apache Beam 的最新版本 0.6.0,引入了一個新的 SDK – 這次是針對 Python 程式語言。Python SDK 加入 Java SDK,成為 Beam 程式設計模型的第二個實作。
Python SDK 包含了 Beam 模型的所有主要概念,包括 ParDo、GroupByKey、Windowing 等等。它具有可擴展的 IO API,用於撰寫有界來源和接收器,並提供讀寫文字、Avro 和 TensorFlow 記錄檔案的內建實作,以及連接到 Google BigQuery 和 Google Cloud Datastore 的連接器。
目前有兩個執行器能夠執行使用 Python SDK 撰寫的管線:Direct Runner 和 Dataflow Runner,兩者目前都僅限於批次執行。即將推出的功能將很快為其他執行器帶來 Python SDK 的好處。
試用 Apache Beam Python SDK
如果您想試用 Python SDK,一個好的起點是快速入門。之後,您可以查看其他範例,並深入研究 API 參考。
讓我們一起快速看一下範例。首先,從 PyPI 安裝 apache-beam
套件並啟動您的 Python 直譯器。
$ pip install apache-beam
$ python
我們將利用 Apache Beam 的強大功能來估算 Pi,以紀念最近過去的 Pi 日。
import random
import apache_beam as beam
def run_trials(count):
"""Throw darts into unit square and count how many fall into unit circle."""
inside = 0
for _ in xrange(count):
x, y = random.uniform(0, 1), random.uniform(0, 1)
inside += 1 if x*x + y*y <= 1.0 else 0
return count, inside
def combine_results(results):
"""Given all the trial results, estimate pi."""
total, inside = sum(r[0] for r in results), sum(r[1] for r in results)
return total, inside, 4 * float(inside) / total if total > 0 else 0
p = beam.Pipeline()
(p | beam.Create([500] * 10) # Create 10 experiments with 500 samples each.
| beam.Map(run_trials) # Run experiments in parallel.
| beam.CombineGlobally(combine_results) # Combine the results.
| beam.io.WriteToText('./pi_estimate.txt')) # Write PI estimate to a file.
p.run()
此範例透過將隨機飛鏢扔到單位正方形中,並追蹤落入單位圓的飛鏢比例來估算 Pi(有關詳細資訊,請參閱完整的範例)。如果您好奇,您可以查看輸出檔案來檢查我們估算的結果。
$ cat pi_estimate.txt*
路線圖
Python SDK 路線圖上的第一件事是解決它的兩個限制。首先,現有的執行器目前僅限於有界的 PCollections,我們期待擴展 SDK 以支援無界的 PCollections(「串流」)。此外,我們正在努力將支援擴展到更多 Apache Beam 執行器,而即將推出的 Fn API 將完成繁重的工作。
這兩項改進都將使 Python SDK 能夠實現 Apache Beam 的使命:一個用於批次和串流資料處理的統一程式設計模型,可以在任何執行引擎上執行。
加入我們!
請考慮加入我們,無論是作為使用者還是貢獻者,因為我們正努力發布第一個具有 API 穩定性的版本。如果您今天想試用 Apache Beam,請查看最新的 0.6.0 版本。我們歡迎任何人透過我們的郵寄清單、問題追蹤器、提取請求和活動來貢獻和參與。