การส่งข้อมูลระหว่าง task ด้วย XCom

Apache Airflow เบื้องต้นด้วย Python

Mike Metzger

Data Engineer

XCom คืออะไร?

  • "Cross Communication"
    • ช่วยให้ task สื่อสารกันได้
  • เก็บในฐานข้อมูล metadata ของ Airflow
    • ส่งข้อมูลขนาดเล็ก
    • เช่น ชื่อไฟล์, URI, จำนวนแถว

ภาพประกอบแสดง XCom ที่ส่งข้อมูลขนาดเล็กระหว่าง task ใน Airflow

Apache Airflow เบื้องต้นด้วย Python

สิ่งที่ไม่ควรส่งผ่าน XCom

  • ไฟล์ขนาดใหญ่
  • DataFrame
  • ฐานข้อมูลขนาดใหญ่
  • รูปภาพขนาดใหญ่

ภาพประกอบแสดงประเภทข้อมูลที่ไม่ควรส่งผ่าน XCom เช่น ไฟล์ขนาดใหญ่และ DataFrame

Apache Airflow เบื้องต้นด้วย Python

การใช้งาน XCom

  • ใช้งาน XCom ได้หลายวิธี
  • เราจะเน้นที่ TaskFlow API
  • ต่อยอดจากการใช้ @task ที่เรียนมาแล้ว
Apache Airflow เบื้องต้นด้วย Python

ตัวอย่าง XCom

@dag(dag_id='Example_XCom')
def example_xcom():

@task def get_data(): return data
@task(multiple_outputs=True) def clean_data(sourcedata): return clean(sourcedata) # Example, not implemented
clean_data(get_data()) example_xcom()
Apache Airflow เบื้องต้นด้วย Python

dependency ของ XCom

  • XCom กำหนดลำดับ dependency โดยอัตโนมัติ
  • ตัวอย่าง
    clean_data(get_data())
    
  • มีความหมายเดียวกับ get_data() >> clean_data()
  • ตัวอย่างเพิ่มเติม
     result = clean_data(get_data())
     result >> alert_when_complete()
    
Apache Airflow เบื้องต้นด้วย Python

การดูข้อมูล XCom

หน้า XCom ใน Airflow แสดงค่าที่บันทึกไว้ตาม key, DAG และ task

Apache Airflow เบื้องต้นด้วย Python

มาฝึกกันเถอะ!

Apache Airflow เบื้องต้นด้วย Python

Preparing Video For Download...