![](/img/trans.png)
[英]How to create groups of N elements from a PCollection Apache Beam Python
[英]How to calculate the number of elements of a PCollection in Apache beam
number_items = lines | 'window' >> beam.WindowInto(window.GlobalWindows()) \
| 'CountGlobally' >> beam.combiners.Count.Globally() \
| 'print' >> beam.ParDo(PrintFn())
我嘗試通過打印和日志顯示該內容,但未發現任何內容
class PrintFn(beam.DoFn):
def process(self, element):
print(element)
logging.error(element)
return [element]
我發現要計算一個無界集合的元素很奇怪。 我的第一感覺是永遠不要追隨全局窗口,因為Beam等待無邊界集合的結尾...除了執行觸發器之外。
在文檔中, 我發現了這個
設置非默認觸發器。 這將允許全局窗口在其他條件下發出結果,因為默認的窗口行為(等待所有數據到達)將永遠不會發生
我是對的,有了觸發器,結局永遠不會發生,它是無限的,無限的。
您是否嘗試過跳過窗口並直接進行全局計數?
對於Batch ,您只需
def print_row(element):
print element
count_pcol = (
lines
| 'Count elements' >> beam.combiners.Count.Globally()
| 'Print result' >> beam.Map(print_row)
)
beam.combiners.Count.Globally()是一個PTransform,它使用全局合並對PCollection的所有元素進行計數並產生單個值。
對於Streaming ,無法計數元素,因為源是無限制的pcollection,即它永遠不會結束。 在您的情況下, CombineGlobally將繼續等待輸入,並且永遠不會產生輸出。
可能的解決方案是設置窗口功能和非默認觸發器。
我編寫了一個簡單的管道,該管道將元素划分為20秒的固定窗口,並對每個窗口的每個鍵計數。 您可以根據需要更改窗口並觸發。
def form_pair(data):
return 1, data
def print_row(element):
print element
count_pcol = (
p
| 'Read from pub sub' >> beam.io.ReadFromPubSub(subscription=input_subscription)
| 'Form key value pair' >> beam.Map(form_pair)
| 'Apply windowing and triggers' >>
beam.WindowInto(window.FixedWindows(20),
trigger=AfterProcessingTime(5),
accumulation_mode=AccumulationMode.DISCARDING)
| 'Count elements by key' >> beam.combiners.Count.PerKey()
| 'Print result' >> beam.Map(print_row)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.