can you help me in creating an Airflow DAG to move and transform data from one table to…
- User
can you help me in creating an Airflow DAG to move and transform data from one table to another
- Assistant
Sure, I can help you with that. Here's an example DAG to move and transform data from one table to another using Airflow:
pythonfrom datetime import datetime, timedelta from airflow import DAG from airflow.operators.postgres_operator import PostgresOperator from airflow.operators.python_operator import PythonOperator from airflow.hooks.postgres_hook import PostgresHook default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2023, 3, 24), 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5), } dag = DAG( 'move_and_transform_data', default_args=default_args, description='A DAG to move and transform data from one table to another', schedule_interval='@daily', ) def move_and_transform_data(): """ Moves and transforms data from one table to another. """ source_conn = PostgresHook(postgres_conn_id='source_conn_id') dest_conn = PostgresHook(postgres_conn_id='dest_conn_id') # Get data from source table source_query = """ SELECT * FROM source_table """ source_data = source_conn.get_records(source_query) # Transform data transformed_data = [] for row in source_data: transformed_row = { 'id': row[0], 'name': row[1].title(), 'age': datetime.today().year - row[2].year, 'created_at': datetime.today() } transformed_data.append(transformed_row) # Load data into destination table dest_conn.insert_rows( table='dest_table', rows=transformed_data, replace=True ) move_and_transform = PythonOperator( task_id='move_and_transform', python_callable=move_and_transform_data, dag=dag ) start = DummyOperator( task_id='start', dag=dag ) end = DummyOperator( task_id='end', dag=dag ) start >> move_and_transform >> end - User
my source data contains following data ID col1 col2 col3 1 Chicago 340 100 2 New Delhi 430 200 3 London 120 300
- Assistant
- User
write an airflow dag to take this source data and create an output file which contains only three columns ID, col1, col2. col2 is just the sum of col2 and col3 from the source file
- Assistant
Sure! Here is an example of an Airflow DAG that takes the source data you provided and creates an output file with only three columns,
ID,col1, andcol2(which is the sum ofcol2andcol3from the source file):python - User
can you also add another field called insert_timestamp to the output file and the value in the field should be the timestamp of when it reads the source file
- Assistant
Sure! Here's an updated version of the Airflow DAG that adds a new field called
insert_timestampto the output file, with the value being the timestamp of when it reads the source file:python - User
can you also write unit tests for above code