repo_name
stringclasses 8
values | repo_url
stringclasses 8
values | repo_description
stringclasses 6
values | repo_stars
int64 6
15.8k
| repo_forks
int64 192
3.6k
| repo_last_updated
stringclasses 8
values | repo_created_at
stringclasses 8
values | repo_size
int64 34
2.13k
| repo_license
stringclasses 4
values | language
stringclasses 3
values | text
stringlengths 0
6.32M
| avg_line_length
float64 0
28.5k
| max_line_length
int64 0
945k
| alphnanum_fraction
float64 0
0.91
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import os
import logging
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
from google.cloud import storage
from airflow.providers.google.cloud.operators.bigquery import BigQueryCreateExternalTableOperator
import pyarrow.csv as pv
import pyarrow.parquet as pq
PROJECT_ID = os.environ.get("GCP_PROJECT_ID")
BUCKET = os.environ.get("GCP_GCS_BUCKET")
dataset_file = "yellow_tripdata_2021-01.csv"
dataset_url = f"https://s3.amazonaws.com/nyc-tlc/trip+data/{dataset_file}"
path_to_local_home = os.environ.get("AIRFLOW_HOME", "/opt/airflow/")
parquet_file = dataset_file.replace('.csv', '.parquet')
BIGQUERY_DATASET = os.environ.get("BIGQUERY_DATASET", 'trips_data_all')
def format_to_parquet(src_file):
if not src_file.endswith('.csv'):
logging.error("Can only accept source files in CSV format, for the moment")
return
table = pv.read_csv(src_file)
pq.write_table(table, src_file.replace('.csv', '.parquet'))
# NOTE: takes 20 mins, at an upload speed of 800kbps. Faster if your internet has a better upload speed
def upload_to_gcs(bucket, object_name, local_file):
"""
Ref: https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
:param bucket: GCS bucket name
:param object_name: target path & file-name
:param local_file: source path & file-name
:return:
"""
# WORKAROUND to prevent timeout for files > 6 MB on 800 kbps upload speed.
# (Ref: https://github.com/googleapis/python-storage/issues/74)
storage.blob._MAX_MULTIPART_SIZE = 5 * 1024 * 1024 # 5 MB
storage.blob._DEFAULT_CHUNKSIZE = 5 * 1024 * 1024 # 5 MB
# End of Workaround
client = storage.Client()
bucket = client.bucket(bucket)
blob = bucket.blob(object_name)
blob.upload_from_filename(local_file)
default_args = {
"owner": "airflow",
"start_date": days_ago(1),
"depends_on_past": False,
"retries": 1,
}
# NOTE: DAG declaration - using a Context Manager (an implicit way)
with DAG(
dag_id="data_ingestion_gcs_dag",
schedule_interval="@daily",
default_args=default_args,
catchup=False,
max_active_runs=1,
tags=['dtc-de'],
) as dag:
download_dataset_task = BashOperator(
task_id="download_dataset_task",
bash_command=f"curl -sSL {dataset_url} > {path_to_local_home}/{dataset_file}"
)
format_to_parquet_task = PythonOperator(
task_id="format_to_parquet_task",
python_callable=format_to_parquet,
op_kwargs={
"src_file": f"{path_to_local_home}/{dataset_file}",
},
)
# TODO: Homework - research and try XCOM to communicate output values between 2 tasks/operators
local_to_gcs_task = PythonOperator(
task_id="local_to_gcs_task",
python_callable=upload_to_gcs,
op_kwargs={
"bucket": BUCKET,
"object_name": f"raw/{parquet_file}",
"local_file": f"{path_to_local_home}/{parquet_file}",
},
)
bigquery_external_table_task = BigQueryCreateExternalTableOperator(
task_id="bigquery_external_table_task",
table_resource={
"tableReference": {
"projectId": PROJECT_ID,
"datasetId": BIGQUERY_DATASET,
"tableId": "external_table",
},
"externalDataConfiguration": {
"sourceFormat": "PARQUET",
"sourceUris": [f"gs://{BUCKET}/raw/{parquet_file}"],
},
},
)
download_dataset_task >> format_to_parquet_task >> local_to_gcs_task >> bigquery_external_table_task
| 32.423423 | 104 | 0.65031 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import os
from datetime import datetime
from airflow import DAG
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
from ingest_script import ingest_callable
AIRFLOW_HOME = os.environ.get("AIRFLOW_HOME", "/opt/airflow/")
PG_HOST = os.getenv('PG_HOST')
PG_USER = os.getenv('PG_USER')
PG_PASSWORD = os.getenv('PG_PASSWORD')
PG_PORT = os.getenv('PG_PORT')
PG_DATABASE = os.getenv('PG_DATABASE')
local_workflow = DAG(
"LocalIngestionDag",
schedule_interval="0 6 2 * *",
start_date=datetime(2021, 1, 1)
)
URL_PREFIX = 'https://s3.amazonaws.com/nyc-tlc/trip+data'
URL_TEMPLATE = URL_PREFIX + '/yellow_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.csv'
OUTPUT_FILE_TEMPLATE = AIRFLOW_HOME + '/output_{{ execution_date.strftime(\'%Y-%m\') }}.csv'
TABLE_NAME_TEMPLATE = 'yellow_taxi_{{ execution_date.strftime(\'%Y_%m\') }}'
with local_workflow:
wget_task = BashOperator(
task_id='wget',
bash_command=f'curl -sSL {URL_TEMPLATE} > {OUTPUT_FILE_TEMPLATE}'
)
ingest_task = PythonOperator(
task_id="ingest",
python_callable=ingest_callable,
op_kwargs=dict(
user=PG_USER,
password=PG_PASSWORD,
host=PG_HOST,
port=PG_PORT,
db=PG_DATABASE,
table_name=TABLE_NAME_TEMPLATE,
csv_file=OUTPUT_FILE_TEMPLATE
),
)
wget_task >> ingest_task | 25.327273 | 92 | 0.639945 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import os
from time import time
import pandas as pd
from sqlalchemy import create_engine
def ingest_callable(user, password, host, port, db, table_name, csv_file, execution_date):
print(table_name, csv_file, execution_date)
engine = create_engine(f'postgresql://{user}:{password}@{host}:{port}/{db}')
engine.connect()
print('connection established successfully, inserting data...')
t_start = time()
df_iter = pd.read_csv(csv_file, iterator=True, chunksize=100000)
df = next(df_iter)
df.tpep_pickup_datetime = pd.to_datetime(df.tpep_pickup_datetime)
df.tpep_dropoff_datetime = pd.to_datetime(df.tpep_dropoff_datetime)
df.head(n=0).to_sql(name=table_name, con=engine, if_exists='replace')
df.to_sql(name=table_name, con=engine, if_exists='append')
t_end = time()
print('inserted the first chunk, took %.3f second' % (t_end - t_start))
while True:
t_start = time()
try:
df = next(df_iter)
except StopIteration:
print("completed")
break
df.tpep_pickup_datetime = pd.to_datetime(df.tpep_pickup_datetime)
df.tpep_dropoff_datetime = pd.to_datetime(df.tpep_dropoff_datetime)
df.to_sql(name=table_name, con=engine, if_exists='append')
t_end = time()
print('inserted another chunk, took %.3f second' % (t_end - t_start))
| 27.306122 | 90 | 0.6443 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import os
from datetime import datetime
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
from google.cloud import storage
PROJECT_ID = os.environ.get("GCP_PROJECT_ID", "pivotal-surfer-336713")
BUCKET = os.environ.get("GCP_GCS_BUCKET", "dtc_data_lake_pivotal-surfer-336713")
dataset_file = "yellow_tripdata_2021-01.csv"
dataset_url = f"https://s3.amazonaws.com/nyc-tlc/trip+data/{dataset_file}"
path_to_local_home = os.environ.get("AIRFLOW_HOME", "/opt/airflow/")
path_to_creds = f"{path_to_local_home}/google_credentials.json"
default_args = {
"owner": "airflow",
"start_date": days_ago(1),
"depends_on_past": False,
"retries": 1,
}
# # Takes 15-20 mins to run. Good case for using Spark (distributed processing, in place of chunks)
# def upload_to_gcs(bucket, object_name, local_file):
# """
# Ref: https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
# :param bucket: GCS bucket name
# :param object_name: target path & file-name
# :param local_file: source path & file-name
# :return:
# """
# # WORKAROUND to prevent timeout for files > 6 MB on 800 kbps upload link.
# # (Ref: https://github.com/googleapis/python-storage/issues/74)
# storage.blob._MAX_MULTIPART_SIZE = 5 * 1024 * 1024 # 5 MB
# storage.blob._DEFAULT_CHUNKSIZE = 5 * 1024 * 1024 # 5 MB
#
# client = storage.Client()
# bucket = client.bucket(bucket)
#
# blob = bucket.blob(object_name)
# # blob.chunk_size = 5 * 1024 * 1024
# blob.upload_from_filename(local_file)
with DAG(
dag_id="data_ingestion_gcs_dag",
schedule_interval="@daily",
default_args=default_args,
catchup=True,
max_active_runs=1,
) as dag:
# Takes ~2 mins, depending upon your internet's download speed
download_dataset_task = BashOperator(
task_id="download_dataset_task",
bash_command=f"curl -sS {dataset_url} > {path_to_local_home}/{dataset_file}" # "&& unzip {zip_file} && rm {zip_file}"
)
# # APPROACH 1: (takes 20 mins, at an upload speed of 800Kbps. Faster if your internet has a better upload speed)
# upload_to_gcs_task = PythonOperator(
# task_id="upload_to_gcs_task",
# python_callable=upload_to_gcs,
# op_kwargs={
# "bucket": BUCKET,
# "object_name": f"raw/{dataset_file}",
# "local_file": f"{path_to_local_home}/{dataset_file}",
#
# },
# )
# OR APPROACH 2: (takes 20 mins, at an upload speed of 800Kbps. Faster if your internet has a better upload speed)
# Ref: https://cloud.google.com/blog/products/gcp/optimizing-your-cloud-storage-performance-google-cloud-performance-atlas
upload_to_gcs_task = BashOperator(
task_id="upload_to_gcs_task",
bash_command=f"gcloud auth activate-service-account --key-file={path_to_creds} && \
gsutil -m cp {path_to_local_home}/{dataset_file} gs://{BUCKET}",
)
download_dataset_task >> upload_to_gcs_task | 36.421687 | 128 | 0.66087 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import os
import logging
from datetime import datetime
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
from google.cloud import storage
import pyarrow.csv as pv
import pyarrow.parquet as pq
PROJECT_ID = os.environ.get("GCP_PROJECT_ID")
BUCKET = os.environ.get("GCP_GCS_BUCKET")
AIRFLOW_HOME = os.environ.get("AIRFLOW_HOME", "/opt/airflow/")
def format_to_parquet(src_file, dest_file):
if not src_file.endswith('.csv'):
logging.error("Can only accept source files in CSV format, for the moment")
return
table = pv.read_csv(src_file)
pq.write_table(table, dest_file)
def upload_to_gcs(bucket, object_name, local_file):
client = storage.Client()
bucket = client.bucket(bucket)
blob = bucket.blob(object_name)
blob.upload_from_filename(local_file)
default_args = {
"owner": "airflow",
#"start_date": days_ago(1),
"depends_on_past": False,
"retries": 1,
}
def donwload_parquetize_upload_dag(
dag,
url_template,
local_csv_path_template,
local_parquet_path_template,
gcs_path_template
):
with dag:
download_dataset_task = BashOperator(
task_id="download_dataset_task",
bash_command=f"curl -sSLf {url_template} > {local_csv_path_template}"
)
format_to_parquet_task = PythonOperator(
task_id="format_to_parquet_task",
python_callable=format_to_parquet,
op_kwargs={
"src_file": local_csv_path_template,
"dest_file": local_parquet_path_template
},
)
local_to_gcs_task = PythonOperator(
task_id="local_to_gcs_task",
python_callable=upload_to_gcs,
op_kwargs={
"bucket": BUCKET,
"object_name": gcs_path_template,
"local_file": local_parquet_path_template,
},
)
rm_task = BashOperator(
task_id="rm_task",
bash_command=f"rm {local_csv_path_template} {local_parquet_path_template}"
)
download_dataset_task >> format_to_parquet_task >> local_to_gcs_task >> rm_task
URL_PREFIX = 'https://s3.amazonaws.com/nyc-tlc/trip+data'
YELLOW_TAXI_URL_TEMPLATE = URL_PREFIX + '/yellow_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.csv'
YELLOW_TAXI_CSV_FILE_TEMPLATE = AIRFLOW_HOME + '/yellow_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.csv'
YELLOW_TAXI_PARQUET_FILE_TEMPLATE = AIRFLOW_HOME + '/yellow_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.parquet'
YELLOW_TAXI_GCS_PATH_TEMPLATE = "raw/yellow_tripdata/{{ execution_date.strftime(\'%Y\') }}/yellow_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.parquet"
yellow_taxi_data_dag = DAG(
dag_id="yellow_taxi_data_v2",
schedule_interval="0 6 2 * *",
start_date=datetime(2019, 1, 1),
default_args=default_args,
catchup=True,
max_active_runs=3,
tags=['dtc-de'],
)
donwload_parquetize_upload_dag(
dag=yellow_taxi_data_dag,
url_template=YELLOW_TAXI_URL_TEMPLATE,
local_csv_path_template=YELLOW_TAXI_CSV_FILE_TEMPLATE,
local_parquet_path_template=YELLOW_TAXI_PARQUET_FILE_TEMPLATE,
gcs_path_template=YELLOW_TAXI_GCS_PATH_TEMPLATE
)
# https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2021-01.csv
GREEN_TAXI_URL_TEMPLATE = URL_PREFIX + '/green_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.csv'
GREEN_TAXI_CSV_FILE_TEMPLATE = AIRFLOW_HOME + '/green_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.csv'
GREEN_TAXI_PARQUET_FILE_TEMPLATE = AIRFLOW_HOME + '/green_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.parquet'
GREEN_TAXI_GCS_PATH_TEMPLATE = "raw/green_tripdata/{{ execution_date.strftime(\'%Y\') }}/green_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.parquet"
green_taxi_data_dag = DAG(
dag_id="green_taxi_data_v1",
schedule_interval="0 7 2 * *",
start_date=datetime(2019, 1, 1),
default_args=default_args,
catchup=True,
max_active_runs=3,
tags=['dtc-de'],
)
donwload_parquetize_upload_dag(
dag=green_taxi_data_dag,
url_template=GREEN_TAXI_URL_TEMPLATE,
local_csv_path_template=GREEN_TAXI_CSV_FILE_TEMPLATE,
local_parquet_path_template=GREEN_TAXI_PARQUET_FILE_TEMPLATE,
gcs_path_template=GREEN_TAXI_GCS_PATH_TEMPLATE
)
# https://nyc-tlc.s3.amazonaws.com/trip+data/fhv_tripdata_2021-01.csv
FHV_TAXI_URL_TEMPLATE = URL_PREFIX + '/fhv_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.csv'
FHV_TAXI_CSV_FILE_TEMPLATE = AIRFLOW_HOME + '/fhv_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.csv'
FHV_TAXI_PARQUET_FILE_TEMPLATE = AIRFLOW_HOME + '/fhv_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.parquet'
FHV_TAXI_GCS_PATH_TEMPLATE = "raw/fhv_tripdata/{{ execution_date.strftime(\'%Y\') }}/fhv_tripdata_{{ execution_date.strftime(\'%Y-%m\') }}.parquet"
fhv_taxi_data_dag = DAG(
dag_id="hfv_taxi_data_v1",
schedule_interval="0 8 2 * *",
start_date=datetime(2019, 1, 1),
end_date=datetime(2020, 1, 1),
default_args=default_args,
catchup=True,
max_active_runs=3,
tags=['dtc-de'],
)
donwload_parquetize_upload_dag(
dag=fhv_taxi_data_dag,
url_template=FHV_TAXI_URL_TEMPLATE,
local_csv_path_template=FHV_TAXI_CSV_FILE_TEMPLATE,
local_parquet_path_template=FHV_TAXI_PARQUET_FILE_TEMPLATE,
gcs_path_template=FHV_TAXI_GCS_PATH_TEMPLATE
)
# https://s3.amazonaws.com/nyc-tlc/misc/taxi+_zone_lookup.csv
ZONES_URL_TEMPLATE = 'https://s3.amazonaws.com/nyc-tlc/misc/taxi+_zone_lookup.csv'
ZONES_CSV_FILE_TEMPLATE = AIRFLOW_HOME + '/taxi_zone_lookup.csv'
ZONES_PARQUET_FILE_TEMPLATE = AIRFLOW_HOME + '/taxi_zone_lookup.parquet'
ZONES_GCS_PATH_TEMPLATE = "raw/taxi_zone/taxi_zone_lookup.parquet"
zones_data_dag = DAG(
dag_id="zones_data_v1",
schedule_interval="@once",
start_date=days_ago(1),
default_args=default_args,
catchup=True,
max_active_runs=3,
tags=['dtc-de'],
)
donwload_parquetize_upload_dag(
dag=zones_data_dag,
url_template=ZONES_URL_TEMPLATE,
local_csv_path_template=ZONES_CSV_FILE_TEMPLATE,
local_parquet_path_template=ZONES_PARQUET_FILE_TEMPLATE,
gcs_path_template=ZONES_GCS_PATH_TEMPLATE
) | 32.393617 | 156 | 0.665127 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import os
import logging
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.providers.google.cloud.operators.bigquery import BigQueryCreateExternalTableOperator, BigQueryInsertJobOperator
from airflow.providers.google.cloud.transfers.gcs_to_gcs import GCSToGCSOperator
PROJECT_ID = os.environ.get("GCP_PROJECT_ID")
BUCKET = os.environ.get("GCP_GCS_BUCKET")
path_to_local_home = os.environ.get("AIRFLOW_HOME", "/opt/airflow/")
BIGQUERY_DATASET = os.environ.get("BIGQUERY_DATASET", 'trips_data_all')
DATASET = "tripdata"
COLOUR_RANGE = {'yellow': 'tpep_pickup_datetime', 'green': 'lpep_pickup_datetime'}
INPUT_PART = "raw"
INPUT_FILETYPE = "parquet"
default_args = {
"owner": "airflow",
"start_date": days_ago(1),
"depends_on_past": False,
"retries": 1,
}
# NOTE: DAG declaration - using a Context Manager (an implicit way)
with DAG(
dag_id="gcs_2_bq_dag",
schedule_interval="@daily",
default_args=default_args,
catchup=False,
max_active_runs=1,
tags=['dtc-de'],
) as dag:
for colour, ds_col in COLOUR_RANGE.items():
move_files_gcs_task = GCSToGCSOperator(
task_id=f'move_{colour}_{DATASET}_files_task',
source_bucket=BUCKET,
source_object=f'{INPUT_PART}/{colour}_{DATASET}*.{INPUT_FILETYPE}',
destination_bucket=BUCKET,
destination_object=f'{colour}/{colour}_{DATASET}',
move_object=True
)
bigquery_external_table_task = BigQueryCreateExternalTableOperator(
task_id=f"bq_{colour}_{DATASET}_external_table_task",
table_resource={
"tableReference": {
"projectId": PROJECT_ID,
"datasetId": BIGQUERY_DATASET,
"tableId": f"{colour}_{DATASET}_external_table",
},
"externalDataConfiguration": {
"autodetect": "True",
"sourceFormat": f"{INPUT_FILETYPE.upper()}",
"sourceUris": [f"gs://{BUCKET}/{colour}/*"],
},
},
)
CREATE_BQ_TBL_QUERY = (
f"CREATE OR REPLACE TABLE {BIGQUERY_DATASET}.{colour}_{DATASET} \
PARTITION BY DATE({ds_col}) \
AS \
SELECT * FROM {BIGQUERY_DATASET}.{colour}_{DATASET}_external_table;"
)
# Create a partitioned table from external table
bq_create_partitioned_table_job = BigQueryInsertJobOperator(
task_id=f"bq_create_{colour}_{DATASET}_partitioned_table_task",
configuration={
"query": {
"query": CREATE_BQ_TBL_QUERY,
"useLegacySql": False,
}
}
)
move_files_gcs_task >> bigquery_external_table_task >> bq_create_partitioned_table_job
| 33.890244 | 124 | 0.58951 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | from confluent_kafka import Producer
import argparse
import csv
from typing import Dict
from time import sleep
from settings import CONFLUENT_CLOUD_CONFIG, \
GREEN_TAXI_TOPIC, FHV_TAXI_TOPIC, \
GREEN_TRIP_DATA_PATH, FHV_TRIP_DATA_PATH
class RideCSVProducer:
def __init__(self, probs: Dict, ride_type: str):
self.producer = Producer(**probs)
self.ride_type = ride_type
def parse_row(self, row):
if self.ride_type == 'green':
record = f'{row[5]}, {row[6]}' # PULocationID, DOLocationID
key = str(row[0]) # vendor_id
elif self.ride_type == 'fhv':
record = f'{row[3]}, {row[4]}' # PULocationID, DOLocationID,
key = str(row[0]) # dispatching_base_num
return key, record
def read_records(self, resource_path: str):
records, ride_keys = [], []
with open(resource_path, 'r') as f:
reader = csv.reader(f)
header = next(reader) # skip the header
for row in reader:
key, record = self.parse_row(row)
ride_keys.append(key)
records.append(record)
return zip(ride_keys, records)
def publish(self, records: [str, str], topic: str):
for key_value in records:
key, value = key_value
try:
self.producer.poll(0)
self.producer.produce(topic=topic, key=key, value=value)
print(f"Producing record for <key: {key}, value:{value}>")
except KeyboardInterrupt:
break
except BufferError as bfer:
self.producer.poll(0.1)
except Exception as e:
print(f"Exception while producing record - {value}: {e}")
self.producer.flush()
sleep(10)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Kafka Consumer')
parser.add_argument('--type', type=str, default='green')
args = parser.parse_args()
if args.type == 'green':
kafka_topic = GREEN_TAXI_TOPIC
data_path = GREEN_TRIP_DATA_PATH
elif args.type == 'fhv':
kafka_topic = FHV_TAXI_TOPIC
data_path = FHV_TRIP_DATA_PATH
producer = RideCSVProducer(ride_type=args.type, probs=CONFLUENT_CLOUD_CONFIG)
ride_records = producer.read_records(resource_path=data_path)
producer.publish(records=ride_records, topic=kafka_topic)
| 32.819444 | 81 | 0.587921 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import pyspark.sql.types as T
INPUT_DATA_PATH = '../../resources/rides.csv'
BOOTSTRAP_SERVERS = 'localhost:9092'
TOPIC_WINDOWED_VENDOR_ID_COUNT = 'vendor_counts_windowed'
PRODUCE_TOPIC_RIDES_CSV = CONSUME_TOPIC_RIDES_CSV = 'rides_csv'
RIDE_SCHEMA = T.StructType(
[T.StructField("vendor_id", T.IntegerType()),
T.StructField('tpep_pickup_datetime', T.TimestampType()),
T.StructField('tpep_dropoff_datetime', T.TimestampType()),
T.StructField("passenger_count", T.IntegerType()),
T.StructField("trip_distance", T.FloatType()),
T.StructField("payment_type", T.IntegerType()),
T.StructField("total_amount", T.FloatType()),
])
| 34 | 63 | 0.691265 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from settings import CONFLUENT_CLOUD_CONFIG, GREEN_TAXI_TOPIC, FHV_TAXI_TOPIC, RIDES_TOPIC, ALL_RIDE_SCHEMA
def read_from_kafka(consume_topic: str):
# Spark Streaming DataFrame, connect to Kafka topic served at host in bootrap.servers option
df_stream = spark \
.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", CONFLUENT_CLOUD_CONFIG['bootstrap.servers']) \
.option("subscribe", consume_topic) \
.option("startingOffsets", "earliest") \
.option("checkpointLocation", "checkpoint") \
.option("kafka.security.protocol", "SASL_SSL") \
.option("kafka.sasl.mechanism", "PLAIN") \
.option("kafka.sasl.jaas.config",
f"""org.apache.kafka.common.security.plain.PlainLoginModule required username="{CONFLUENT_CLOUD_CONFIG['sasl.username']}" password="{CONFLUENT_CLOUD_CONFIG['sasl.password']}";""") \
.option("failOnDataLoss", False) \
.load()
return df_stream
def parse_rides(df, schema):
""" take a Spark Streaming df and parse value col based on <schema>, return streaming df cols in schema """
assert df.isStreaming is True, "DataFrame doesn't receive streaming data"
df = df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
# split attributes to nested array in one Column
col = F.split(df['value'], ', ')
# expand col to multiple top-level columns
for idx, field in enumerate(schema):
df = df.withColumn(field.name, col.getItem(idx).cast(field.dataType))
df = df.na.drop()
df.printSchema()
return df.select([field.name for field in schema])
def sink_console(df, output_mode: str = 'complete', processing_time: str = '5 seconds'):
query = df.writeStream \
.outputMode(output_mode) \
.trigger(processingTime=processing_time) \
.format("console") \
.option("truncate", False) \
.start() \
.awaitTermination()
return query # pyspark.sql.streaming.StreamingQuery
def sink_kafka(df, topic, output_mode: str = 'complete'):
query = df.writeStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "pkc-75m1o.europe-west3.gcp.confluent.cloud:9092") \
.outputMode(output_mode) \
.option("topic", topic) \
.option("checkpointLocation", "checkpoint") \
.option("kafka.security.protocol", "SASL_SSL") \
.option("kafka.sasl.mechanism", "PLAIN") \
.option("kafka.sasl.jaas.config",
f"""org.apache.kafka.common.security.plain.PlainLoginModule required username="{CONFLUENT_CLOUD_CONFIG['sasl.username']}" password="{CONFLUENT_CLOUD_CONFIG['sasl.password']}";""") \
.option("failOnDataLoss", False) \
.start()
return query
def op_groupby(df, column_names):
df_aggregation = df.groupBy(column_names).count()
return df_aggregation
if __name__ == "__main__":
spark = SparkSession.builder.appName('streaming-homework').getOrCreate()
spark.sparkContext.setLogLevel('WARN')
# Step 1: Consume GREEN_TAXI_TOPIC and FHV_TAXI_TOPIC
df_green_rides = read_from_kafka(consume_topic=GREEN_TAXI_TOPIC)
df_fhv_rides = read_from_kafka(consume_topic=FHV_TAXI_TOPIC)
# Step 2: Publish green and fhv rides to RIDES_TOPIC
kafka_sink_green_query = sink_kafka(df=df_green_rides, topic=RIDES_TOPIC, output_mode='append')
kafka_sink_fhv_query = sink_kafka(df=df_fhv_rides, topic=RIDES_TOPIC, output_mode='append')
# Step 3: Read RIDES_TOPIC and parse it in ALL_RIDE_SCHEMA
df_all_rides = read_from_kafka(consume_topic=RIDES_TOPIC)
df_all_rides = parse_rides(df_all_rides, ALL_RIDE_SCHEMA)
# Step 4: Apply Aggregation on the all_rides
df_pu_location_count = op_groupby(df_all_rides, ['PULocationID'])
df_pu_location_count = df_pu_location_count.sort(F.col('count').desc())
# Step 5: Sink Aggregation Streams to Console
console_sink_pu_location = sink_console(df_pu_location_count, output_mode='complete')
| 39.87 | 197 | 0.666911 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | #!/usr/bin/env python
# coding: utf-8
import os
import argparse
from time import time
import pandas as pd
from sqlalchemy import create_engine
def main(params):
user = params.user
password = params.password
host = params.host
port = params.port
db = params.db
table_name = params.table_name
url = params.url
# the backup files are gzipped, and it's important to keep the correct extension
# for pandas to be able to open the file
if url.endswith('.csv.gz'):
csv_name = 'output.csv.gz'
else:
csv_name = 'output.csv'
os.system(f"wget {url} -O {csv_name}")
engine = create_engine(f'postgresql://{user}:{password}@{host}:{port}/{db}')
df_iter = pd.read_csv(csv_name, iterator=True, chunksize=100000)
df = next(df_iter)
df.tpep_pickup_datetime = pd.to_datetime(df.tpep_pickup_datetime)
df.tpep_dropoff_datetime = pd.to_datetime(df.tpep_dropoff_datetime)
df.head(n=0).to_sql(name=table_name, con=engine, if_exists='replace')
df.to_sql(name=table_name, con=engine, if_exists='append')
while True:
try:
t_start = time()
df = next(df_iter)
df.tpep_pickup_datetime = pd.to_datetime(df.tpep_pickup_datetime)
df.tpep_dropoff_datetime = pd.to_datetime(df.tpep_dropoff_datetime)
df.to_sql(name=table_name, con=engine, if_exists='append')
t_end = time()
print('inserted another chunk, took %.3f second' % (t_end - t_start))
except StopIteration:
print("Finished ingesting data into the postgres database")
break
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Ingest CSV data to Postgres')
parser.add_argument('--user', required=True, help='user name for postgres')
parser.add_argument('--password', required=True, help='password for postgres')
parser.add_argument('--host', required=True, help='host for postgres')
parser.add_argument('--port', required=True, help='port for postgres')
parser.add_argument('--db', required=True, help='database name for postgres')
parser.add_argument('--table_name', required=True, help='name of the table where we will write the results to')
parser.add_argument('--url', required=True, help='url of the csv file')
args = parser.parse_args()
main(args)
| 29.417722 | 115 | 0.642798 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import sys
import pandas as pd
print(sys.argv)
day = sys.argv[1]
# some fancy stuff with pandas
print(f'job finished successfully for day = {day}') | 12.909091 | 51 | 0.723684 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import io
import os
import requests
import pandas as pd
from google.cloud import storage
"""
Pre-reqs:
1. `pip install pandas pyarrow google-cloud-storage`
2. Set GOOGLE_APPLICATION_CREDENTIALS to your project/service-account key
3. Set GCP_GCS_BUCKET as your bucket or change default value of BUCKET
"""
# services = ['fhv','green','yellow']
init_url = 'https://github.com/DataTalksClub/nyc-tlc-data/releases/download/'
# switch out the bucketname
BUCKET = os.environ.get("GCP_GCS_BUCKET", "dtc-data-lake-bucketname")
def upload_to_gcs(bucket, object_name, local_file):
"""
Ref: https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
"""
# # WORKAROUND to prevent timeout for files > 6 MB on 800 kbps upload speed.
# # (Ref: https://github.com/googleapis/python-storage/issues/74)
# storage.blob._MAX_MULTIPART_SIZE = 5 * 1024 * 1024 # 5 MB
# storage.blob._DEFAULT_CHUNKSIZE = 5 * 1024 * 1024 # 5 MB
client = storage.Client()
bucket = client.bucket(bucket)
blob = bucket.blob(object_name)
blob.upload_from_filename(local_file)
def web_to_gcs(year, service):
for i in range(12):
# sets the month part of the file_name string
month = '0'+str(i+1)
month = month[-2:]
# csv file_name
file_name = f"{service}_tripdata_{year}-{month}.csv.gz"
# download it using requests via a pandas df
request_url = f"{init_url}{service}/{file_name}"
r = requests.get(request_url)
open(file_name, 'wb').write(r.content)
print(f"Local: {file_name}")
# read it back into a parquet file
df = pd.read_csv(file_name, compression='gzip')
file_name = file_name.replace('.csv.gz', '.parquet')
df.to_parquet(file_name, engine='pyarrow')
print(f"Parquet: {file_name}")
# upload it to gcs
upload_to_gcs(BUCKET, f"{service}/{file_name}", file_name)
print(f"GCS: {service}/{file_name}")
web_to_gcs('2019', 'green')
web_to_gcs('2020', 'green')
# web_to_gcs('2019', 'yellow')
# web_to_gcs('2020', 'yellow')
| 30.671642 | 93 | 0.642621 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | #!/usr/bin/env python
# coding: utf-8
import argparse
import pyspark
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
parser = argparse.ArgumentParser()
parser.add_argument('--input_green', required=True)
parser.add_argument('--input_yellow', required=True)
parser.add_argument('--output', required=True)
args = parser.parse_args()
input_green = args.input_green
input_yellow = args.input_yellow
output = args.output
spark = SparkSession.builder \
.appName('test') \
.getOrCreate()
df_green = spark.read.parquet(input_green)
df_green = df_green \
.withColumnRenamed('lpep_pickup_datetime', 'pickup_datetime') \
.withColumnRenamed('lpep_dropoff_datetime', 'dropoff_datetime')
df_yellow = spark.read.parquet(input_yellow)
df_yellow = df_yellow \
.withColumnRenamed('tpep_pickup_datetime', 'pickup_datetime') \
.withColumnRenamed('tpep_dropoff_datetime', 'dropoff_datetime')
common_colums = [
'VendorID',
'pickup_datetime',
'dropoff_datetime',
'store_and_fwd_flag',
'RatecodeID',
'PULocationID',
'DOLocationID',
'passenger_count',
'trip_distance',
'fare_amount',
'extra',
'mta_tax',
'tip_amount',
'tolls_amount',
'improvement_surcharge',
'total_amount',
'payment_type',
'congestion_surcharge'
]
df_green_sel = df_green \
.select(common_colums) \
.withColumn('service_type', F.lit('green'))
df_yellow_sel = df_yellow \
.select(common_colums) \
.withColumn('service_type', F.lit('yellow'))
df_trips_data = df_green_sel.unionAll(df_yellow_sel)
df_trips_data.registerTempTable('trips_data')
df_result = spark.sql("""
SELECT
-- Reveneue grouping
PULocationID AS revenue_zone,
date_trunc('month', pickup_datetime) AS revenue_month,
service_type,
-- Revenue calculation
SUM(fare_amount) AS revenue_monthly_fare,
SUM(extra) AS revenue_monthly_extra,
SUM(mta_tax) AS revenue_monthly_mta_tax,
SUM(tip_amount) AS revenue_monthly_tip_amount,
SUM(tolls_amount) AS revenue_monthly_tolls_amount,
SUM(improvement_surcharge) AS revenue_monthly_improvement_surcharge,
SUM(total_amount) AS revenue_monthly_total_amount,
SUM(congestion_surcharge) AS revenue_monthly_congestion_surcharge,
-- Additional calculations
AVG(passenger_count) AS avg_montly_passenger_count,
AVG(trip_distance) AS avg_montly_trip_distance
FROM
trips_data
GROUP BY
1, 2, 3
""")
df_result.coalesce(1) \
.write.parquet(output, mode='overwrite')
| 21.75 | 72 | 0.690224 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | #!/usr/bin/env python
# coding: utf-8
import argparse
import pyspark
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
parser = argparse.ArgumentParser()
parser.add_argument('--input_green', required=True)
parser.add_argument('--input_yellow', required=True)
parser.add_argument('--output', required=True)
args = parser.parse_args()
input_green = args.input_green
input_yellow = args.input_yellow
output = args.output
spark = SparkSession.builder \
.appName('test') \
.getOrCreate()
spark.conf.set('temporaryGcsBucket', 'dataproc-temp-europe-west6-828225226997-fckhkym8')
df_green = spark.read.parquet(input_green)
df_green = df_green \
.withColumnRenamed('lpep_pickup_datetime', 'pickup_datetime') \
.withColumnRenamed('lpep_dropoff_datetime', 'dropoff_datetime')
df_yellow = spark.read.parquet(input_yellow)
df_yellow = df_yellow \
.withColumnRenamed('tpep_pickup_datetime', 'pickup_datetime') \
.withColumnRenamed('tpep_dropoff_datetime', 'dropoff_datetime')
common_colums = [
'VendorID',
'pickup_datetime',
'dropoff_datetime',
'store_and_fwd_flag',
'RatecodeID',
'PULocationID',
'DOLocationID',
'passenger_count',
'trip_distance',
'fare_amount',
'extra',
'mta_tax',
'tip_amount',
'tolls_amount',
'improvement_surcharge',
'total_amount',
'payment_type',
'congestion_surcharge'
]
df_green_sel = df_green \
.select(common_colums) \
.withColumn('service_type', F.lit('green'))
df_yellow_sel = df_yellow \
.select(common_colums) \
.withColumn('service_type', F.lit('yellow'))
df_trips_data = df_green_sel.unionAll(df_yellow_sel)
df_trips_data.registerTempTable('trips_data')
df_result = spark.sql("""
SELECT
-- Reveneue grouping
PULocationID AS revenue_zone,
date_trunc('month', pickup_datetime) AS revenue_month,
service_type,
-- Revenue calculation
SUM(fare_amount) AS revenue_monthly_fare,
SUM(extra) AS revenue_monthly_extra,
SUM(mta_tax) AS revenue_monthly_mta_tax,
SUM(tip_amount) AS revenue_monthly_tip_amount,
SUM(tolls_amount) AS revenue_monthly_tolls_amount,
SUM(improvement_surcharge) AS revenue_monthly_improvement_surcharge,
SUM(total_amount) AS revenue_monthly_total_amount,
SUM(congestion_surcharge) AS revenue_monthly_congestion_surcharge,
-- Additional calculations
AVG(passenger_count) AS avg_montly_passenger_count,
AVG(trip_distance) AS avg_montly_trip_distance
FROM
trips_data
GROUP BY
1, 2, 3
""")
df_result.write.format('bigquery') \
.option('table', output) \
.save()
| 22.069565 | 88 | 0.690422 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import argparse
from typing import Dict, List
from kafka import KafkaConsumer
from settings import BOOTSTRAP_SERVERS, CONSUME_TOPIC_RIDES_CSV
class RideCSVConsumer:
def __init__(self, props: Dict):
self.consumer = KafkaConsumer(**props)
def consume_from_kafka(self, topics: List[str]):
self.consumer.subscribe(topics=topics)
print('Consuming from Kafka started')
print('Available topics to consume: ', self.consumer.subscription())
while True:
try:
# SIGINT can't be handled when polling, limit timeout to 1 second.
msg = self.consumer.poll(1.0)
if msg is None or msg == {}:
continue
for msg_key, msg_values in msg.items():
for msg_val in msg_values:
print(f'Key:{msg_val.key}-type({type(msg_val.key)}), '
f'Value:{msg_val.value}-type({type(msg_val.value)})')
except KeyboardInterrupt:
break
self.consumer.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Kafka Consumer')
parser.add_argument('--topic', type=str, default=CONSUME_TOPIC_RIDES_CSV)
args = parser.parse_args()
topic = args.topic
config = {
'bootstrap_servers': [BOOTSTRAP_SERVERS],
'auto_offset_reset': 'earliest',
'enable_auto_commit': True,
'key_deserializer': lambda key: int(key.decode('utf-8')),
'value_deserializer': lambda value: value.decode('utf-8'),
'group_id': 'consumer.group.id.csv-example.1',
}
csv_consumer = RideCSVConsumer(props=config)
csv_consumer.consume_from_kafka(topics=[topic])
| 35.25 | 83 | 0.59632 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import csv
from time import sleep
from typing import Dict
from kafka import KafkaProducer
from settings import BOOTSTRAP_SERVERS, INPUT_DATA_PATH, PRODUCE_TOPIC_RIDES_CSV
def delivery_report(err, msg):
if err is not None:
print("Delivery failed for record {}: {}".format(msg.key(), err))
return
print('Record {} successfully produced to {} [{}] at offset {}'.format(
msg.key(), msg.topic(), msg.partition(), msg.offset()))
class RideCSVProducer:
def __init__(self, props: Dict):
self.producer = KafkaProducer(**props)
# self.producer = Producer(producer_props)
@staticmethod
def read_records(resource_path: str):
records, ride_keys = [], []
i = 0
with open(resource_path, 'r') as f:
reader = csv.reader(f)
header = next(reader) # skip the header
for row in reader:
# vendor_id, passenger_count, trip_distance, payment_type, total_amount
records.append(f'{row[0]}, {row[1]}, {row[2]}, {row[3]}, {row[4]}, {row[9]}, {row[16]}')
ride_keys.append(str(row[0]))
i += 1
if i == 5:
break
return zip(ride_keys, records)
def publish(self, topic: str, records: [str, str]):
for key_value in records:
key, value = key_value
try:
self.producer.send(topic=topic, key=key, value=value)
print(f"Producing record for <key: {key}, value:{value}>")
except KeyboardInterrupt:
break
except Exception as e:
print(f"Exception while producing record - {value}: {e}")
self.producer.flush()
sleep(1)
if __name__ == "__main__":
config = {
'bootstrap_servers': [BOOTSTRAP_SERVERS],
'key_serializer': lambda x: x.encode('utf-8'),
'value_serializer': lambda x: x.encode('utf-8')
}
producer = RideCSVProducer(props=config)
ride_records = producer.read_records(resource_path=INPUT_DATA_PATH)
print(ride_records)
producer.publish(topic=PRODUCE_TOPIC_RIDES_CSV, records=ride_records)
| 33.571429 | 104 | 0.574644 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | from typing import List, Dict
class RideRecord:
def __init__(self, arr: List[str]):
self.vendor_id = int(arr[0])
self.passenger_count = int(arr[1])
self.trip_distance = float(arr[2])
self.payment_type = int(arr[3])
self.total_amount = float(arr[4])
@classmethod
def from_dict(cls, d: Dict):
return cls(arr=[
d['vendor_id'],
d['passenger_count'],
d['trip_distance'],
d['payment_type'],
d['total_amount']
]
)
def __repr__(self):
return f'{self.__class__.__name__}: {self.__dict__}'
def dict_to_ride_record(obj, ctx):
if obj is None:
return None
return RideRecord.from_dict(obj)
def ride_record_to_dict(ride_record: RideRecord, ctx):
return ride_record.__dict__
| 21.648649 | 60 | 0.540024 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | from typing import Dict
class RideRecordKey:
def __init__(self, vendor_id):
self.vendor_id = vendor_id
@classmethod
def from_dict(cls, d: Dict):
return cls(vendor_id=d['vendor_id'])
def __repr__(self):
return f'{self.__class__.__name__}: {self.__dict__}'
def dict_to_ride_record_key(obj, ctx):
if obj is None:
return None
return RideRecordKey.from_dict(obj)
def ride_record_key_to_dict(ride_record_key: RideRecordKey, ctx):
return ride_record_key.__dict__
| 20.04 | 65 | 0.619048 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | from typing import List, Dict
from decimal import Decimal
from datetime import datetime
class Ride:
def __init__(self, arr: List[str]):
self.vendor_id = arr[0]
self.tpep_pickup_datetime = datetime.strptime(arr[1], "%Y-%m-%d %H:%M:%S"),
self.tpep_dropoff_datetime = datetime.strptime(arr[2], "%Y-%m-%d %H:%M:%S"),
self.passenger_count = int(arr[3])
self.trip_distance = Decimal(arr[4])
self.rate_code_id = int(arr[5])
self.store_and_fwd_flag = arr[6]
self.pu_location_id = int(arr[7])
self.do_location_id = int(arr[8])
self.payment_type = arr[9]
self.fare_amount = Decimal(arr[10])
self.extra = Decimal(arr[11])
self.mta_tax = Decimal(arr[12])
self.tip_amount = Decimal(arr[13])
self.tolls_amount = Decimal(arr[14])
self.improvement_surcharge = Decimal(arr[15])
self.total_amount = Decimal(arr[16])
self.congestion_surcharge = Decimal(arr[17])
@classmethod
def from_dict(cls, d: Dict):
return cls(arr=[
d['vendor_id'],
d['tpep_pickup_datetime'][0],
d['tpep_dropoff_datetime'][0],
d['passenger_count'],
d['trip_distance'],
d['rate_code_id'],
d['store_and_fwd_flag'],
d['pu_location_id'],
d['do_location_id'],
d['payment_type'],
d['fare_amount'],
d['extra'],
d['mta_tax'],
d['tip_amount'],
d['tolls_amount'],
d['improvement_surcharge'],
d['total_amount'],
d['congestion_surcharge'],
]
)
def __repr__(self):
return f'{self.__class__.__name__}: {self.__dict__}'
| 32.396226 | 84 | 0.520068 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import faust
from taxi_rides import TaxiRide
from faust import current_event
app = faust.App('datatalksclub.stream.v3', broker='kafka://localhost:9092', consumer_auto_offset_reset="earliest")
topic = app.topic('datatalkclub.yellow_taxi_ride.json', value_type=TaxiRide)
high_amount_rides = app.topic('datatalks.yellow_taxi_rides.high_amount')
low_amount_rides = app.topic('datatalks.yellow_taxi_rides.low_amount')
@app.agent(topic)
async def process(stream):
async for event in stream:
if event.total_amount >= 40.0:
await current_event().forward(high_amount_rides)
else:
await current_event().forward(low_amount_rides)
if __name__ == '__main__':
app.main()
| 31.318182 | 114 | 0.701408 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import csv
from json import dumps
from kafka import KafkaProducer
from time import sleep
producer = KafkaProducer(bootstrap_servers=['localhost:9092'],
key_serializer=lambda x: dumps(x).encode('utf-8'),
value_serializer=lambda x: dumps(x).encode('utf-8'))
file = open('../../resources/rides.csv')
csvreader = csv.reader(file)
header = next(csvreader)
for row in csvreader:
key = {"vendorId": int(row[0])}
value = {"vendorId": int(row[0]), "passenger_count": int(row[3]), "trip_distance": float(row[4]), "payment_type": int(row[9]), "total_amount": float(row[16])}
producer.send('datatalkclub.yellow_taxi_ride.json', value=value, key=key)
print("producing")
sleep(1) | 36 | 162 | 0.648173 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import faust
from taxi_rides import TaxiRide
app = faust.App('datatalksclub.stream.v2', broker='kafka://localhost:9092')
topic = app.topic('datatalkclub.yellow_taxi_ride.json', value_type=TaxiRide)
@app.agent(topic)
async def start_reading(records):
async for record in records:
print(record)
if __name__ == '__main__':
app.main()
| 19.823529 | 76 | 0.694051 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import faust
from taxi_rides import TaxiRide
app = faust.App('datatalksclub.stream.v2', broker='kafka://localhost:9092')
topic = app.topic('datatalkclub.yellow_taxi_ride.json', value_type=TaxiRide)
vendor_rides = app.Table('vendor_rides', default=int)
@app.agent(topic)
async def process(stream):
async for event in stream.group_by(TaxiRide.vendorId):
vendor_rides[event.vendorId] += 1
if __name__ == '__main__':
app.main()
| 23.833333 | 76 | 0.704036 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | import faust
class TaxiRide(faust.Record, validation=True):
vendorId: str
passenger_count: int
trip_distance: float
payment_type: int
total_amount: float
| 16.7 | 46 | 0.704545 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | from datetime import timedelta
import faust
from taxi_rides import TaxiRide
app = faust.App('datatalksclub.stream.v2', broker='kafka://localhost:9092')
topic = app.topic('datatalkclub.yellow_taxi_ride.json', value_type=TaxiRide)
vendor_rides = app.Table('vendor_rides_windowed', default=int).tumbling(
timedelta(minutes=1),
expires=timedelta(hours=1),
)
@app.agent(topic)
async def process(stream):
async for event in stream.group_by(TaxiRide.vendorId):
vendor_rides[event.vendorId] += 1
if __name__ == '__main__':
app.main()
| 23.26087 | 76 | 0.710952 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Python | from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from settings import RIDE_SCHEMA, CONSUME_TOPIC_RIDES_CSV, TOPIC_WINDOWED_VENDOR_ID_COUNT
def read_from_kafka(consume_topic: str):
# Spark Streaming DataFrame, connect to Kafka topic served at host in bootrap.servers option
df_stream = spark \
.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "localhost:9092,broker:29092") \
.option("subscribe", consume_topic) \
.option("startingOffsets", "earliest") \
.option("checkpointLocation", "checkpoint") \
.load()
return df_stream
def parse_ride_from_kafka_message(df, schema):
""" take a Spark Streaming df and parse value col based on <schema>, return streaming df cols in schema """
assert df.isStreaming is True, "DataFrame doesn't receive streaming data"
df = df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
# split attributes to nested array in one Column
col = F.split(df['value'], ', ')
# expand col to multiple top-level columns
for idx, field in enumerate(schema):
df = df.withColumn(field.name, col.getItem(idx).cast(field.dataType))
return df.select([field.name for field in schema])
def sink_console(df, output_mode: str = 'complete', processing_time: str = '5 seconds'):
write_query = df.writeStream \
.outputMode(output_mode) \
.trigger(processingTime=processing_time) \
.format("console") \
.option("truncate", False) \
.start()
return write_query # pyspark.sql.streaming.StreamingQuery
def sink_memory(df, query_name, query_template):
query_df = df \
.writeStream \
.queryName(query_name) \
.format("memory") \
.start()
query_str = query_template.format(table_name=query_name)
query_results = spark.sql(query_str)
return query_results, query_df
def sink_kafka(df, topic):
write_query = df.writeStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "localhost:9092,broker:29092") \
.outputMode('complete') \
.option("topic", topic) \
.option("checkpointLocation", "checkpoint") \
.start()
return write_query
def prepare_df_to_kafka_sink(df, value_columns, key_column=None):
columns = df.columns
df = df.withColumn("value", F.concat_ws(', ', *value_columns))
if key_column:
df = df.withColumnRenamed(key_column, "key")
df = df.withColumn("key", df.key.cast('string'))
return df.select(['key', 'value'])
def op_groupby(df, column_names):
df_aggregation = df.groupBy(column_names).count()
return df_aggregation
def op_windowed_groupby(df, window_duration, slide_duration):
df_windowed_aggregation = df.groupBy(
F.window(timeColumn=df.tpep_pickup_datetime, windowDuration=window_duration, slideDuration=slide_duration),
df.vendor_id
).count()
return df_windowed_aggregation
if __name__ == "__main__":
spark = SparkSession.builder.appName('streaming-examples').getOrCreate()
spark.sparkContext.setLogLevel('WARN')
# read_streaming data
df_consume_stream = read_from_kafka(consume_topic=CONSUME_TOPIC_RIDES_CSV)
print(df_consume_stream.printSchema())
# parse streaming data
df_rides = parse_ride_from_kafka_message(df_consume_stream, RIDE_SCHEMA)
print(df_rides.printSchema())
sink_console(df_rides, output_mode='append')
df_trip_count_by_vendor_id = op_groupby(df_rides, ['vendor_id'])
df_trip_count_by_pickup_date_vendor_id = op_windowed_groupby(df_rides, window_duration="10 minutes",
slide_duration='5 minutes')
# write the output out to the console for debugging / testing
sink_console(df_trip_count_by_vendor_id)
# write the output to the kafka topic
df_trip_count_messages = prepare_df_to_kafka_sink(df=df_trip_count_by_pickup_date_vendor_id,
value_columns=['count'], key_column='vendor_id')
kafka_sink_query = sink_kafka(df=df_trip_count_messages, topic=TOPIC_WINDOWED_VENDOR_ID_COUNT)
spark.streams.awaitAnyTermination()
| 35.586207 | 115 | 0.65449 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package schemaregistry;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@org.apache.avro.specific.AvroGenerated
public class RideRecord extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 6805437803204402942L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"RideRecord\",\"namespace\":\"schemaregistry\",\"fields\":[{\"name\":\"vendor_id\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}},{\"name\":\"passenger_count\",\"type\":\"int\"},{\"name\":\"trip_distance\",\"type\":\"double\"}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<RideRecord> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<RideRecord> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<RideRecord> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<RideRecord> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<RideRecord> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this RideRecord to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a RideRecord from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a RideRecord instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static RideRecord fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.lang.String vendor_id;
private int passenger_count;
private double trip_distance;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public RideRecord() {}
/**
* All-args constructor.
* @param vendor_id The new value for vendor_id
* @param passenger_count The new value for passenger_count
* @param trip_distance The new value for trip_distance
*/
public RideRecord(java.lang.String vendor_id, java.lang.Integer passenger_count, java.lang.Double trip_distance) {
this.vendor_id = vendor_id;
this.passenger_count = passenger_count;
this.trip_distance = trip_distance;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return vendor_id;
case 1: return passenger_count;
case 2: return trip_distance;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: vendor_id = value$ != null ? value$.toString() : null; break;
case 1: passenger_count = (java.lang.Integer)value$; break;
case 2: trip_distance = (java.lang.Double)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'vendor_id' field.
* @return The value of the 'vendor_id' field.
*/
public java.lang.String getVendorId() {
return vendor_id;
}
/**
* Sets the value of the 'vendor_id' field.
* @param value the value to set.
*/
public void setVendorId(java.lang.String value) {
this.vendor_id = value;
}
/**
* Gets the value of the 'passenger_count' field.
* @return The value of the 'passenger_count' field.
*/
public int getPassengerCount() {
return passenger_count;
}
/**
* Sets the value of the 'passenger_count' field.
* @param value the value to set.
*/
public void setPassengerCount(int value) {
this.passenger_count = value;
}
/**
* Gets the value of the 'trip_distance' field.
* @return The value of the 'trip_distance' field.
*/
public double getTripDistance() {
return trip_distance;
}
/**
* Sets the value of the 'trip_distance' field.
* @param value the value to set.
*/
public void setTripDistance(double value) {
this.trip_distance = value;
}
/**
* Creates a new RideRecord RecordBuilder.
* @return A new RideRecord RecordBuilder
*/
public static schemaregistry.RideRecord.Builder newBuilder() {
return new schemaregistry.RideRecord.Builder();
}
/**
* Creates a new RideRecord RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new RideRecord RecordBuilder
*/
public static schemaregistry.RideRecord.Builder newBuilder(schemaregistry.RideRecord.Builder other) {
if (other == null) {
return new schemaregistry.RideRecord.Builder();
} else {
return new schemaregistry.RideRecord.Builder(other);
}
}
/**
* Creates a new RideRecord RecordBuilder by copying an existing RideRecord instance.
* @param other The existing instance to copy.
* @return A new RideRecord RecordBuilder
*/
public static schemaregistry.RideRecord.Builder newBuilder(schemaregistry.RideRecord other) {
if (other == null) {
return new schemaregistry.RideRecord.Builder();
} else {
return new schemaregistry.RideRecord.Builder(other);
}
}
/**
* RecordBuilder for RideRecord instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<RideRecord>
implements org.apache.avro.data.RecordBuilder<RideRecord> {
private java.lang.String vendor_id;
private int passenger_count;
private double trip_distance;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(schemaregistry.RideRecord.Builder other) {
super(other);
if (isValidValue(fields()[0], other.vendor_id)) {
this.vendor_id = data().deepCopy(fields()[0].schema(), other.vendor_id);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.passenger_count)) {
this.passenger_count = data().deepCopy(fields()[1].schema(), other.passenger_count);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.trip_distance)) {
this.trip_distance = data().deepCopy(fields()[2].schema(), other.trip_distance);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
}
/**
* Creates a Builder by copying an existing RideRecord instance
* @param other The existing instance to copy.
*/
private Builder(schemaregistry.RideRecord other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.vendor_id)) {
this.vendor_id = data().deepCopy(fields()[0].schema(), other.vendor_id);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.passenger_count)) {
this.passenger_count = data().deepCopy(fields()[1].schema(), other.passenger_count);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.trip_distance)) {
this.trip_distance = data().deepCopy(fields()[2].schema(), other.trip_distance);
fieldSetFlags()[2] = true;
}
}
/**
* Gets the value of the 'vendor_id' field.
* @return The value.
*/
public java.lang.String getVendorId() {
return vendor_id;
}
/**
* Sets the value of the 'vendor_id' field.
* @param value The value of 'vendor_id'.
* @return This builder.
*/
public schemaregistry.RideRecord.Builder setVendorId(java.lang.String value) {
validate(fields()[0], value);
this.vendor_id = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'vendor_id' field has been set.
* @return True if the 'vendor_id' field has been set, false otherwise.
*/
public boolean hasVendorId() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'vendor_id' field.
* @return This builder.
*/
public schemaregistry.RideRecord.Builder clearVendorId() {
vendor_id = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'passenger_count' field.
* @return The value.
*/
public int getPassengerCount() {
return passenger_count;
}
/**
* Sets the value of the 'passenger_count' field.
* @param value The value of 'passenger_count'.
* @return This builder.
*/
public schemaregistry.RideRecord.Builder setPassengerCount(int value) {
validate(fields()[1], value);
this.passenger_count = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'passenger_count' field has been set.
* @return True if the 'passenger_count' field has been set, false otherwise.
*/
public boolean hasPassengerCount() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'passenger_count' field.
* @return This builder.
*/
public schemaregistry.RideRecord.Builder clearPassengerCount() {
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'trip_distance' field.
* @return The value.
*/
public double getTripDistance() {
return trip_distance;
}
/**
* Sets the value of the 'trip_distance' field.
* @param value The value of 'trip_distance'.
* @return This builder.
*/
public schemaregistry.RideRecord.Builder setTripDistance(double value) {
validate(fields()[2], value);
this.trip_distance = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'trip_distance' field has been set.
* @return True if the 'trip_distance' field has been set, false otherwise.
*/
public boolean hasTripDistance() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'trip_distance' field.
* @return This builder.
*/
public schemaregistry.RideRecord.Builder clearTripDistance() {
fieldSetFlags()[2] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public RideRecord build() {
try {
RideRecord record = new RideRecord();
record.vendor_id = fieldSetFlags()[0] ? this.vendor_id : (java.lang.String) defaultValue(fields()[0]);
record.passenger_count = fieldSetFlags()[1] ? this.passenger_count : (java.lang.Integer) defaultValue(fields()[1]);
record.trip_distance = fieldSetFlags()[2] ? this.trip_distance : (java.lang.Double) defaultValue(fields()[2]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<RideRecord>
WRITER$ = (org.apache.avro.io.DatumWriter<RideRecord>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<RideRecord>
READER$ = (org.apache.avro.io.DatumReader<RideRecord>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override protected boolean hasCustomCoders() { return true; }
@Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeString(this.vendor_id);
out.writeInt(this.passenger_count);
out.writeDouble(this.trip_distance);
}
@Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.vendor_id = in.readString();
this.passenger_count = in.readInt();
this.trip_distance = in.readDouble();
} else {
for (int i = 0; i < 3; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.vendor_id = in.readString();
break;
case 1:
this.passenger_count = in.readInt();
break;
case 2:
this.trip_distance = in.readDouble();
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
| 29.533473 | 377 | 0.659381 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package schemaregistry;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@org.apache.avro.specific.AvroGenerated
public class RideRecordCompatible extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 7163300507090021229L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"RideRecordCompatible\",\"namespace\":\"schemaregistry\",\"fields\":[{\"name\":\"vendorId\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}},{\"name\":\"passenger_count\",\"type\":\"int\"},{\"name\":\"trip_distance\",\"type\":\"double\"},{\"name\":\"pu_location_id\",\"type\":[\"null\",\"long\"],\"default\":null}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<RideRecordCompatible> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<RideRecordCompatible> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<RideRecordCompatible> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<RideRecordCompatible> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<RideRecordCompatible> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this RideRecordCompatible to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a RideRecordCompatible from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a RideRecordCompatible instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static RideRecordCompatible fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.lang.String vendorId;
private int passenger_count;
private double trip_distance;
private java.lang.Long pu_location_id;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public RideRecordCompatible() {}
/**
* All-args constructor.
* @param vendorId The new value for vendorId
* @param passenger_count The new value for passenger_count
* @param trip_distance The new value for trip_distance
* @param pu_location_id The new value for pu_location_id
*/
public RideRecordCompatible(java.lang.String vendorId, java.lang.Integer passenger_count, java.lang.Double trip_distance, java.lang.Long pu_location_id) {
this.vendorId = vendorId;
this.passenger_count = passenger_count;
this.trip_distance = trip_distance;
this.pu_location_id = pu_location_id;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return vendorId;
case 1: return passenger_count;
case 2: return trip_distance;
case 3: return pu_location_id;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: vendorId = value$ != null ? value$.toString() : null; break;
case 1: passenger_count = (java.lang.Integer)value$; break;
case 2: trip_distance = (java.lang.Double)value$; break;
case 3: pu_location_id = (java.lang.Long)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'vendorId' field.
* @return The value of the 'vendorId' field.
*/
public java.lang.String getVendorId() {
return vendorId;
}
/**
* Sets the value of the 'vendorId' field.
* @param value the value to set.
*/
public void setVendorId(java.lang.String value) {
this.vendorId = value;
}
/**
* Gets the value of the 'passenger_count' field.
* @return The value of the 'passenger_count' field.
*/
public int getPassengerCount() {
return passenger_count;
}
/**
* Sets the value of the 'passenger_count' field.
* @param value the value to set.
*/
public void setPassengerCount(int value) {
this.passenger_count = value;
}
/**
* Gets the value of the 'trip_distance' field.
* @return The value of the 'trip_distance' field.
*/
public double getTripDistance() {
return trip_distance;
}
/**
* Sets the value of the 'trip_distance' field.
* @param value the value to set.
*/
public void setTripDistance(double value) {
this.trip_distance = value;
}
/**
* Gets the value of the 'pu_location_id' field.
* @return The value of the 'pu_location_id' field.
*/
public java.lang.Long getPuLocationId() {
return pu_location_id;
}
/**
* Sets the value of the 'pu_location_id' field.
* @param value the value to set.
*/
public void setPuLocationId(java.lang.Long value) {
this.pu_location_id = value;
}
/**
* Creates a new RideRecordCompatible RecordBuilder.
* @return A new RideRecordCompatible RecordBuilder
*/
public static schemaregistry.RideRecordCompatible.Builder newBuilder() {
return new schemaregistry.RideRecordCompatible.Builder();
}
/**
* Creates a new RideRecordCompatible RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new RideRecordCompatible RecordBuilder
*/
public static schemaregistry.RideRecordCompatible.Builder newBuilder(schemaregistry.RideRecordCompatible.Builder other) {
if (other == null) {
return new schemaregistry.RideRecordCompatible.Builder();
} else {
return new schemaregistry.RideRecordCompatible.Builder(other);
}
}
/**
* Creates a new RideRecordCompatible RecordBuilder by copying an existing RideRecordCompatible instance.
* @param other The existing instance to copy.
* @return A new RideRecordCompatible RecordBuilder
*/
public static schemaregistry.RideRecordCompatible.Builder newBuilder(schemaregistry.RideRecordCompatible other) {
if (other == null) {
return new schemaregistry.RideRecordCompatible.Builder();
} else {
return new schemaregistry.RideRecordCompatible.Builder(other);
}
}
/**
* RecordBuilder for RideRecordCompatible instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<RideRecordCompatible>
implements org.apache.avro.data.RecordBuilder<RideRecordCompatible> {
private java.lang.String vendorId;
private int passenger_count;
private double trip_distance;
private java.lang.Long pu_location_id;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(schemaregistry.RideRecordCompatible.Builder other) {
super(other);
if (isValidValue(fields()[0], other.vendorId)) {
this.vendorId = data().deepCopy(fields()[0].schema(), other.vendorId);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.passenger_count)) {
this.passenger_count = data().deepCopy(fields()[1].schema(), other.passenger_count);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.trip_distance)) {
this.trip_distance = data().deepCopy(fields()[2].schema(), other.trip_distance);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
if (isValidValue(fields()[3], other.pu_location_id)) {
this.pu_location_id = data().deepCopy(fields()[3].schema(), other.pu_location_id);
fieldSetFlags()[3] = other.fieldSetFlags()[3];
}
}
/**
* Creates a Builder by copying an existing RideRecordCompatible instance
* @param other The existing instance to copy.
*/
private Builder(schemaregistry.RideRecordCompatible other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.vendorId)) {
this.vendorId = data().deepCopy(fields()[0].schema(), other.vendorId);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.passenger_count)) {
this.passenger_count = data().deepCopy(fields()[1].schema(), other.passenger_count);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.trip_distance)) {
this.trip_distance = data().deepCopy(fields()[2].schema(), other.trip_distance);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.pu_location_id)) {
this.pu_location_id = data().deepCopy(fields()[3].schema(), other.pu_location_id);
fieldSetFlags()[3] = true;
}
}
/**
* Gets the value of the 'vendorId' field.
* @return The value.
*/
public java.lang.String getVendorId() {
return vendorId;
}
/**
* Sets the value of the 'vendorId' field.
* @param value The value of 'vendorId'.
* @return This builder.
*/
public schemaregistry.RideRecordCompatible.Builder setVendorId(java.lang.String value) {
validate(fields()[0], value);
this.vendorId = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'vendorId' field has been set.
* @return True if the 'vendorId' field has been set, false otherwise.
*/
public boolean hasVendorId() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'vendorId' field.
* @return This builder.
*/
public schemaregistry.RideRecordCompatible.Builder clearVendorId() {
vendorId = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'passenger_count' field.
* @return The value.
*/
public int getPassengerCount() {
return passenger_count;
}
/**
* Sets the value of the 'passenger_count' field.
* @param value The value of 'passenger_count'.
* @return This builder.
*/
public schemaregistry.RideRecordCompatible.Builder setPassengerCount(int value) {
validate(fields()[1], value);
this.passenger_count = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'passenger_count' field has been set.
* @return True if the 'passenger_count' field has been set, false otherwise.
*/
public boolean hasPassengerCount() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'passenger_count' field.
* @return This builder.
*/
public schemaregistry.RideRecordCompatible.Builder clearPassengerCount() {
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'trip_distance' field.
* @return The value.
*/
public double getTripDistance() {
return trip_distance;
}
/**
* Sets the value of the 'trip_distance' field.
* @param value The value of 'trip_distance'.
* @return This builder.
*/
public schemaregistry.RideRecordCompatible.Builder setTripDistance(double value) {
validate(fields()[2], value);
this.trip_distance = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'trip_distance' field has been set.
* @return True if the 'trip_distance' field has been set, false otherwise.
*/
public boolean hasTripDistance() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'trip_distance' field.
* @return This builder.
*/
public schemaregistry.RideRecordCompatible.Builder clearTripDistance() {
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'pu_location_id' field.
* @return The value.
*/
public java.lang.Long getPuLocationId() {
return pu_location_id;
}
/**
* Sets the value of the 'pu_location_id' field.
* @param value The value of 'pu_location_id'.
* @return This builder.
*/
public schemaregistry.RideRecordCompatible.Builder setPuLocationId(java.lang.Long value) {
validate(fields()[3], value);
this.pu_location_id = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'pu_location_id' field has been set.
* @return True if the 'pu_location_id' field has been set, false otherwise.
*/
public boolean hasPuLocationId() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'pu_location_id' field.
* @return This builder.
*/
public schemaregistry.RideRecordCompatible.Builder clearPuLocationId() {
pu_location_id = null;
fieldSetFlags()[3] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public RideRecordCompatible build() {
try {
RideRecordCompatible record = new RideRecordCompatible();
record.vendorId = fieldSetFlags()[0] ? this.vendorId : (java.lang.String) defaultValue(fields()[0]);
record.passenger_count = fieldSetFlags()[1] ? this.passenger_count : (java.lang.Integer) defaultValue(fields()[1]);
record.trip_distance = fieldSetFlags()[2] ? this.trip_distance : (java.lang.Double) defaultValue(fields()[2]);
record.pu_location_id = fieldSetFlags()[3] ? this.pu_location_id : (java.lang.Long) defaultValue(fields()[3]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<RideRecordCompatible>
WRITER$ = (org.apache.avro.io.DatumWriter<RideRecordCompatible>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<RideRecordCompatible>
READER$ = (org.apache.avro.io.DatumReader<RideRecordCompatible>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override protected boolean hasCustomCoders() { return true; }
@Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeString(this.vendorId);
out.writeInt(this.passenger_count);
out.writeDouble(this.trip_distance);
if (this.pu_location_id == null) {
out.writeIndex(0);
out.writeNull();
} else {
out.writeIndex(1);
out.writeLong(this.pu_location_id);
}
}
@Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.vendorId = in.readString();
this.passenger_count = in.readInt();
this.trip_distance = in.readDouble();
if (in.readIndex() != 1) {
in.readNull();
this.pu_location_id = null;
} else {
this.pu_location_id = in.readLong();
}
} else {
for (int i = 0; i < 4; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.vendorId = in.readString();
break;
case 1:
this.passenger_count = in.readInt();
break;
case 2:
this.trip_distance = in.readDouble();
break;
case 3:
if (in.readIndex() != 1) {
in.readNull();
this.pu_location_id = null;
} else {
this.pu_location_id = in.readLong();
}
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
| 30.317073 | 462 | 0.657858 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package schemaregistry;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@org.apache.avro.specific.AvroGenerated
public class RideRecordNoneCompatible extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -4618980179396772493L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"RideRecordNoneCompatible\",\"namespace\":\"schemaregistry\",\"fields\":[{\"name\":\"vendorId\",\"type\":\"int\"},{\"name\":\"passenger_count\",\"type\":\"int\"},{\"name\":\"trip_distance\",\"type\":\"double\"}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<RideRecordNoneCompatible> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<RideRecordNoneCompatible> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<RideRecordNoneCompatible> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<RideRecordNoneCompatible> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<RideRecordNoneCompatible> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this RideRecordNoneCompatible to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a RideRecordNoneCompatible from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a RideRecordNoneCompatible instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static RideRecordNoneCompatible fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private int vendorId;
private int passenger_count;
private double trip_distance;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public RideRecordNoneCompatible() {}
/**
* All-args constructor.
* @param vendorId The new value for vendorId
* @param passenger_count The new value for passenger_count
* @param trip_distance The new value for trip_distance
*/
public RideRecordNoneCompatible(java.lang.Integer vendorId, java.lang.Integer passenger_count, java.lang.Double trip_distance) {
this.vendorId = vendorId;
this.passenger_count = passenger_count;
this.trip_distance = trip_distance;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return vendorId;
case 1: return passenger_count;
case 2: return trip_distance;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: vendorId = (java.lang.Integer)value$; break;
case 1: passenger_count = (java.lang.Integer)value$; break;
case 2: trip_distance = (java.lang.Double)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'vendorId' field.
* @return The value of the 'vendorId' field.
*/
public int getVendorId() {
return vendorId;
}
/**
* Sets the value of the 'vendorId' field.
* @param value the value to set.
*/
public void setVendorId(int value) {
this.vendorId = value;
}
/**
* Gets the value of the 'passenger_count' field.
* @return The value of the 'passenger_count' field.
*/
public int getPassengerCount() {
return passenger_count;
}
/**
* Sets the value of the 'passenger_count' field.
* @param value the value to set.
*/
public void setPassengerCount(int value) {
this.passenger_count = value;
}
/**
* Gets the value of the 'trip_distance' field.
* @return The value of the 'trip_distance' field.
*/
public double getTripDistance() {
return trip_distance;
}
/**
* Sets the value of the 'trip_distance' field.
* @param value the value to set.
*/
public void setTripDistance(double value) {
this.trip_distance = value;
}
/**
* Creates a new RideRecordNoneCompatible RecordBuilder.
* @return A new RideRecordNoneCompatible RecordBuilder
*/
public static schemaregistry.RideRecordNoneCompatible.Builder newBuilder() {
return new schemaregistry.RideRecordNoneCompatible.Builder();
}
/**
* Creates a new RideRecordNoneCompatible RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new RideRecordNoneCompatible RecordBuilder
*/
public static schemaregistry.RideRecordNoneCompatible.Builder newBuilder(schemaregistry.RideRecordNoneCompatible.Builder other) {
if (other == null) {
return new schemaregistry.RideRecordNoneCompatible.Builder();
} else {
return new schemaregistry.RideRecordNoneCompatible.Builder(other);
}
}
/**
* Creates a new RideRecordNoneCompatible RecordBuilder by copying an existing RideRecordNoneCompatible instance.
* @param other The existing instance to copy.
* @return A new RideRecordNoneCompatible RecordBuilder
*/
public static schemaregistry.RideRecordNoneCompatible.Builder newBuilder(schemaregistry.RideRecordNoneCompatible other) {
if (other == null) {
return new schemaregistry.RideRecordNoneCompatible.Builder();
} else {
return new schemaregistry.RideRecordNoneCompatible.Builder(other);
}
}
/**
* RecordBuilder for RideRecordNoneCompatible instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<RideRecordNoneCompatible>
implements org.apache.avro.data.RecordBuilder<RideRecordNoneCompatible> {
private int vendorId;
private int passenger_count;
private double trip_distance;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(schemaregistry.RideRecordNoneCompatible.Builder other) {
super(other);
if (isValidValue(fields()[0], other.vendorId)) {
this.vendorId = data().deepCopy(fields()[0].schema(), other.vendorId);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.passenger_count)) {
this.passenger_count = data().deepCopy(fields()[1].schema(), other.passenger_count);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.trip_distance)) {
this.trip_distance = data().deepCopy(fields()[2].schema(), other.trip_distance);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
}
/**
* Creates a Builder by copying an existing RideRecordNoneCompatible instance
* @param other The existing instance to copy.
*/
private Builder(schemaregistry.RideRecordNoneCompatible other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.vendorId)) {
this.vendorId = data().deepCopy(fields()[0].schema(), other.vendorId);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.passenger_count)) {
this.passenger_count = data().deepCopy(fields()[1].schema(), other.passenger_count);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.trip_distance)) {
this.trip_distance = data().deepCopy(fields()[2].schema(), other.trip_distance);
fieldSetFlags()[2] = true;
}
}
/**
* Gets the value of the 'vendorId' field.
* @return The value.
*/
public int getVendorId() {
return vendorId;
}
/**
* Sets the value of the 'vendorId' field.
* @param value The value of 'vendorId'.
* @return This builder.
*/
public schemaregistry.RideRecordNoneCompatible.Builder setVendorId(int value) {
validate(fields()[0], value);
this.vendorId = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'vendorId' field has been set.
* @return True if the 'vendorId' field has been set, false otherwise.
*/
public boolean hasVendorId() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'vendorId' field.
* @return This builder.
*/
public schemaregistry.RideRecordNoneCompatible.Builder clearVendorId() {
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'passenger_count' field.
* @return The value.
*/
public int getPassengerCount() {
return passenger_count;
}
/**
* Sets the value of the 'passenger_count' field.
* @param value The value of 'passenger_count'.
* @return This builder.
*/
public schemaregistry.RideRecordNoneCompatible.Builder setPassengerCount(int value) {
validate(fields()[1], value);
this.passenger_count = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'passenger_count' field has been set.
* @return True if the 'passenger_count' field has been set, false otherwise.
*/
public boolean hasPassengerCount() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'passenger_count' field.
* @return This builder.
*/
public schemaregistry.RideRecordNoneCompatible.Builder clearPassengerCount() {
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'trip_distance' field.
* @return The value.
*/
public double getTripDistance() {
return trip_distance;
}
/**
* Sets the value of the 'trip_distance' field.
* @param value The value of 'trip_distance'.
* @return This builder.
*/
public schemaregistry.RideRecordNoneCompatible.Builder setTripDistance(double value) {
validate(fields()[2], value);
this.trip_distance = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'trip_distance' field has been set.
* @return True if the 'trip_distance' field has been set, false otherwise.
*/
public boolean hasTripDistance() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'trip_distance' field.
* @return This builder.
*/
public schemaregistry.RideRecordNoneCompatible.Builder clearTripDistance() {
fieldSetFlags()[2] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public RideRecordNoneCompatible build() {
try {
RideRecordNoneCompatible record = new RideRecordNoneCompatible();
record.vendorId = fieldSetFlags()[0] ? this.vendorId : (java.lang.Integer) defaultValue(fields()[0]);
record.passenger_count = fieldSetFlags()[1] ? this.passenger_count : (java.lang.Integer) defaultValue(fields()[1]);
record.trip_distance = fieldSetFlags()[2] ? this.trip_distance : (java.lang.Double) defaultValue(fields()[2]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<RideRecordNoneCompatible>
WRITER$ = (org.apache.avro.io.DatumWriter<RideRecordNoneCompatible>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<RideRecordNoneCompatible>
READER$ = (org.apache.avro.io.DatumReader<RideRecordNoneCompatible>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override protected boolean hasCustomCoders() { return true; }
@Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeInt(this.vendorId);
out.writeInt(this.passenger_count);
out.writeDouble(this.trip_distance);
}
@Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.vendorId = in.readInt();
this.passenger_count = in.readInt();
this.trip_distance = in.readDouble();
} else {
for (int i = 0; i < 3; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.vendorId = in.readInt();
break;
case 1:
this.passenger_count = in.readInt();
break;
case 2:
this.trip_distance = in.readDouble();
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
| 30.607966 | 344 | 0.675975 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.streams.StreamsConfig;
import schemaregistry.RideRecord;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class AvroProducer {
private Properties props = new Properties();
public AvroProducer() {
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "pkc-75m1o.europe-west3.gcp.confluent.cloud:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='"+Secrets.KAFKA_CLUSTER_KEY+"' password='"+Secrets.KAFKA_CLUSTER_SECRET+"';");
props.put("sasl.mechanism", "PLAIN");
props.put("client.dns.lookup", "use_all_dns_ips");
props.put("session.timeout.ms", "45000");
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName());
props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "https://psrc-kk5gg.europe-west3.gcp.confluent.cloud");
props.put("basic.auth.credentials.source", "USER_INFO");
props.put("basic.auth.user.info", Secrets.SCHEMA_REGISTRY_KEY+":"+Secrets.SCHEMA_REGISTRY_SECRET);
}
public List<RideRecord> getRides() throws IOException, CsvException {
var ridesStream = this.getClass().getResource("/rides.csv");
var reader = new CSVReader(new FileReader(ridesStream.getFile()));
reader.skip(1);
return reader.readAll().stream().map(row ->
RideRecord.newBuilder()
.setVendorId(row[0])
.setTripDistance(Double.parseDouble(row[4]))
.setPassengerCount(Integer.parseInt(row[3]))
.build()
).collect(Collectors.toList());
}
public void publishRides(List<RideRecord> rides) throws ExecutionException, InterruptedException {
KafkaProducer<String, RideRecord> kafkaProducer = new KafkaProducer<>(props);
for (RideRecord ride : rides) {
var record = kafkaProducer.send(new ProducerRecord<>("rides_avro", String.valueOf(ride.getVendorId()), ride), (metadata, exception) -> {
if (exception != null) {
System.out.println(exception.getMessage());
}
});
System.out.println(record.get().offset());
Thread.sleep(500);
}
}
public static void main(String[] args) throws IOException, CsvException, ExecutionException, InterruptedException {
var producer = new AvroProducer();
var rideRecords = producer.getRides();
producer.publishRides(rideRecords);
}
}
| 44.767123 | 192 | 0.688323 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.example.data.Ride;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.List;
import java.util.Properties;
import io.confluent.kafka.serializers.KafkaJsonDeserializerConfig;
public class JsonConsumer {
private Properties props = new Properties();
private KafkaConsumer<String, Ride> consumer;
public JsonConsumer() {
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "pkc-75m1o.europe-west3.gcp.confluent.cloud:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='"+Secrets.KAFKA_CLUSTER_KEY+"' password='"+Secrets.KAFKA_CLUSTER_SECRET+"';");
props.put("sasl.mechanism", "PLAIN");
props.put("client.dns.lookup", "use_all_dns_ips");
props.put("session.timeout.ms", "45000");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "io.confluent.kafka.serializers.KafkaJsonDeserializer");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "kafka_tutorial_example.jsonconsumer.v2");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.put(KafkaJsonDeserializerConfig.JSON_VALUE_TYPE, Ride.class);
consumer = new KafkaConsumer<String, Ride>(props);
consumer.subscribe(List.of("rides"));
}
public void consumeFromKafka() {
System.out.println("Consuming form kafka started");
var results = consumer.poll(Duration.of(1, ChronoUnit.SECONDS));
var i = 0;
do {
for(ConsumerRecord<String, Ride> result: results) {
System.out.println(result.value().DOLocationID);
}
results = consumer.poll(Duration.of(1, ChronoUnit.SECONDS));
System.out.println("RESULTS:::" + results.count());
i++;
}
while(!results.isEmpty() || i < 10);
}
public static void main(String[] args) {
JsonConsumer jsonConsumer = new JsonConsumer();
jsonConsumer.consumeFromKafka();
}
}
| 42.631579 | 192 | 0.697104 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.example.customserdes.CustomSerdes;
import org.example.data.Ride;
import java.util.Properties;
public class JsonKStream {
private Properties props = new Properties();
public JsonKStream() {
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "pkc-75m1o.europe-west3.gcp.confluent.cloud:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='"+Secrets.KAFKA_CLUSTER_KEY+"' password='"+Secrets.KAFKA_CLUSTER_SECRET+"';");
props.put("sasl.mechanism", "PLAIN");
props.put("client.dns.lookup", "use_all_dns_ips");
props.put("session.timeout.ms", "45000");
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka_tutorial.kstream.count.plocation.v1");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
}
public Topology createTopology() {
StreamsBuilder streamsBuilder = new StreamsBuilder();
var ridesStream = streamsBuilder.stream("rides", Consumed.with(Serdes.String(), CustomSerdes.getSerde(Ride.class)));
var puLocationCount = ridesStream.groupByKey().count().toStream();
puLocationCount.to("rides-pulocation-count", Produced.with(Serdes.String(), Serdes.Long()));
return streamsBuilder.build();
}
public void countPLocation() throws InterruptedException {
var topology = createTopology();
var kStreams = new KafkaStreams(topology, props);
kStreams.start();
while (kStreams.state() != KafkaStreams.State.RUNNING) {
System.out.println(kStreams.state());
Thread.sleep(1000);
}
System.out.println(kStreams.state());
Runtime.getRuntime().addShutdownHook(new Thread(kStreams::close));
}
public static void main(String[] args) throws InterruptedException {
var object = new JsonKStream();
object.countPLocation();
}
}
| 42.175439 | 192 | 0.707724 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler;
import org.apache.kafka.streams.kstream.*;
import org.example.customserdes.CustomSerdes;
import org.example.data.PickupLocation;
import org.example.data.Ride;
import org.example.data.VendorInfo;
import java.time.Duration;
import java.util.Optional;
import java.util.Properties;
public class JsonKStreamJoins {
private Properties props = new Properties();
public JsonKStreamJoins() {
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "pkc-75m1o.europe-west3.gcp.confluent.cloud:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='"+Secrets.KAFKA_CLUSTER_KEY+"' password='"+Secrets.KAFKA_CLUSTER_SECRET+"';");
props.put("sasl.mechanism", "PLAIN");
props.put("client.dns.lookup", "use_all_dns_ips");
props.put("session.timeout.ms", "45000");
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka_tutorial.kstream.joined.rides.pickuplocation.v1");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
}
public Topology createTopology() {
StreamsBuilder streamsBuilder = new StreamsBuilder();
KStream<String, Ride> rides = streamsBuilder.stream(Topics.INPUT_RIDE_TOPIC, Consumed.with(Serdes.String(), CustomSerdes.getSerde(Ride.class)));
KStream<String, PickupLocation> pickupLocations = streamsBuilder.stream(Topics.INPUT_RIDE_LOCATION_TOPIC, Consumed.with(Serdes.String(), CustomSerdes.getSerde(PickupLocation.class)));
var pickupLocationsKeyedOnPUId = pickupLocations.selectKey((key, value) -> String.valueOf(value.PULocationID));
var joined = rides.join(pickupLocationsKeyedOnPUId, (ValueJoiner<Ride, PickupLocation, Optional<VendorInfo>>) (ride, pickupLocation) -> {
var period = Duration.between(ride.tpep_dropoff_datetime, pickupLocation.tpep_pickup_datetime);
if (period.abs().toMinutes() > 10) return Optional.empty();
else return Optional.of(new VendorInfo(ride.VendorID, pickupLocation.PULocationID, pickupLocation.tpep_pickup_datetime, ride.tpep_dropoff_datetime));
}, JoinWindows.ofTimeDifferenceAndGrace(Duration.ofMinutes(20), Duration.ofMinutes(5)),
StreamJoined.with(Serdes.String(), CustomSerdes.getSerde(Ride.class), CustomSerdes.getSerde(PickupLocation.class)));
joined.filter(((key, value) -> value.isPresent())).mapValues(Optional::get)
.to(Topics.OUTPUT_TOPIC, Produced.with(Serdes.String(), CustomSerdes.getSerde(VendorInfo.class)));
return streamsBuilder.build();
}
public void joinRidesPickupLocation() throws InterruptedException {
var topology = createTopology();
var kStreams = new KafkaStreams(topology, props);
kStreams.setUncaughtExceptionHandler(exception -> {
System.out.println(exception.getMessage());
return StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_APPLICATION;
});
kStreams.start();
while (kStreams.state() != KafkaStreams.State.RUNNING) {
System.out.println(kStreams.state());
Thread.sleep(1000);
}
System.out.println(kStreams.state());
Runtime.getRuntime().addShutdownHook(new Thread(kStreams::close));
}
public static void main(String[] args) throws InterruptedException {
var object = new JsonKStreamJoins();
object.joinRidesPickupLocation();
}
}
| 50.922078 | 192 | 0.718039 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.WindowedSerdes;
import org.example.customserdes.CustomSerdes;
import org.example.data.Ride;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Properties;
public class JsonKStreamWindow {
private Properties props = new Properties();
public JsonKStreamWindow() {
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "pkc-75m1o.europe-west3.gcp.confluent.cloud:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='"+Secrets.KAFKA_CLUSTER_KEY+"' password='"+Secrets.KAFKA_CLUSTER_SECRET+"';");
props.put("sasl.mechanism", "PLAIN");
props.put("client.dns.lookup", "use_all_dns_ips");
props.put("session.timeout.ms", "45000");
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka_tutorial.kstream.count.plocation.v1");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
}
public Topology createTopology() {
StreamsBuilder streamsBuilder = new StreamsBuilder();
var ridesStream = streamsBuilder.stream("rides", Consumed.with(Serdes.String(), CustomSerdes.getSerde(Ride.class)));
var puLocationCount = ridesStream.groupByKey()
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofSeconds(10), Duration.ofSeconds(5)))
.count().toStream();
var windowSerde = WindowedSerdes.timeWindowedSerdeFrom(String.class, 10*1000);
puLocationCount.to("rides-pulocation-window-count", Produced.with(windowSerde, Serdes.Long()));
return streamsBuilder.build();
}
public void countPLocationWindowed() {
var topology = createTopology();
var kStreams = new KafkaStreams(topology, props);
kStreams.start();
Runtime.getRuntime().addShutdownHook(new Thread(kStreams::close));
}
public static void main(String[] args) {
var object = new JsonKStreamWindow();
object.countPLocationWindowed();
}
}
| 41.983607 | 192 | 0.724151 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.streams.StreamsConfig;
import org.example.data.Ride;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class JsonProducer {
private Properties props = new Properties();
public JsonProducer() {
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "pkc-75m1o.europe-west3.gcp.confluent.cloud:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='"+Secrets.KAFKA_CLUSTER_KEY+"' password='"+Secrets.KAFKA_CLUSTER_SECRET+"';");
props.put("sasl.mechanism", "PLAIN");
props.put("client.dns.lookup", "use_all_dns_ips");
props.put("session.timeout.ms", "45000");
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "io.confluent.kafka.serializers.KafkaJsonSerializer");
}
public List<Ride> getRides() throws IOException, CsvException {
var ridesStream = this.getClass().getResource("/rides.csv");
var reader = new CSVReader(new FileReader(ridesStream.getFile()));
reader.skip(1);
return reader.readAll().stream().map(arr -> new Ride(arr))
.collect(Collectors.toList());
}
public void publishRides(List<Ride> rides) throws ExecutionException, InterruptedException {
KafkaProducer<String, Ride> kafkaProducer = new KafkaProducer<String, Ride>(props);
for(Ride ride: rides) {
ride.tpep_pickup_datetime = LocalDateTime.now().minusMinutes(20);
ride.tpep_dropoff_datetime = LocalDateTime.now();
var record = kafkaProducer.send(new ProducerRecord<>("rides", String.valueOf(ride.DOLocationID), ride), (metadata, exception) -> {
if(exception != null) {
System.out.println(exception.getMessage());
}
});
System.out.println(record.get().offset());
System.out.println(ride.DOLocationID);
Thread.sleep(500);
}
}
public static void main(String[] args) throws IOException, CsvException, ExecutionException, InterruptedException {
var producer = new JsonProducer();
var rides = producer.getRides();
producer.publishRides(rides);
}
} | 44.278689 | 192 | 0.682361 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import com.opencsv.exceptions.CsvException;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.example.data.PickupLocation;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
public class JsonProducerPickupLocation {
private Properties props = new Properties();
public JsonProducerPickupLocation() {
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "pkc-75m1o.europe-west3.gcp.confluent.cloud:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='"+Secrets.KAFKA_CLUSTER_KEY+"' password='"+Secrets.KAFKA_CLUSTER_SECRET+"';");
props.put("sasl.mechanism", "PLAIN");
props.put("client.dns.lookup", "use_all_dns_ips");
props.put("session.timeout.ms", "45000");
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "io.confluent.kafka.serializers.KafkaJsonSerializer");
}
public void publish(PickupLocation pickupLocation) throws ExecutionException, InterruptedException {
KafkaProducer<String, PickupLocation> kafkaProducer = new KafkaProducer<String, PickupLocation>(props);
var record = kafkaProducer.send(new ProducerRecord<>("rides_location", String.valueOf(pickupLocation.PULocationID), pickupLocation), (metadata, exception) -> {
if (exception != null) {
System.out.println(exception.getMessage());
}
});
System.out.println(record.get().offset());
}
public static void main(String[] args) throws IOException, CsvException, ExecutionException, InterruptedException {
var producer = new JsonProducerPickupLocation();
producer.publish(new PickupLocation(186, LocalDateTime.now()));
}
}
| 47.577778 | 192 | 0.730892 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
public class Secrets {
public static final String KAFKA_CLUSTER_KEY = "REPLACE_WITH_YOUR_KAFKA_CLUSTER_KEY";
public static final String KAFKA_CLUSTER_SECRET = "REPLACE_WITH_YOUR_KAFKA_CLUSTER_SECRET";
public static final String SCHEMA_REGISTRY_KEY = "REPLACE_WITH_SCHEMA_REGISTRY_KEY";
public static final String SCHEMA_REGISTRY_SECRET = "REPLACE_WITH_SCHEMA_REGISTRY_SECRET";
}
| 37.181818 | 95 | 0.761337 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
public class Topics {
public static final String INPUT_RIDE_TOPIC = "rides";
public static final String INPUT_RIDE_LOCATION_TOPIC = "rides_location";
public static final String OUTPUT_TOPIC = "vendor_info";
}
| 29.5 | 76 | 0.73251 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example.customserdes;
import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig;
import io.confluent.kafka.serializers.KafkaJsonDeserializer;
import io.confluent.kafka.serializers.KafkaJsonSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.avro.specific.SpecificRecordBase;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.example.data.PickupLocation;
import org.example.data.Ride;
import org.example.data.VendorInfo;
import java.util.HashMap;
import java.util.Map;
public class CustomSerdes {
public static <T> Serde<T> getSerde(Class<T> classOf) {
Map<String, Object> serdeProps = new HashMap<>();
serdeProps.put("json.value.type", classOf);
final Serializer<T> mySerializer = new KafkaJsonSerializer<>();
mySerializer.configure(serdeProps, false);
final Deserializer<T> myDeserializer = new KafkaJsonDeserializer<>();
myDeserializer.configure(serdeProps, false);
return Serdes.serdeFrom(mySerializer, myDeserializer);
}
public static <T extends SpecificRecordBase> SpecificAvroSerde getAvroSerde(boolean isKey, String schemaRegistryUrl) {
var serde = new SpecificAvroSerde<T>();
Map<String, Object> serdeProps = new HashMap<>();
serdeProps.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);
serde.configure(serdeProps, isKey);
return serde;
}
}
| 37.325581 | 122 | 0.763206 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example.data;
import java.time.LocalDateTime;
public class PickupLocation {
public PickupLocation(long PULocationID, LocalDateTime tpep_pickup_datetime) {
this.PULocationID = PULocationID;
this.tpep_pickup_datetime = tpep_pickup_datetime;
}
public PickupLocation() {
}
public long PULocationID;
public LocalDateTime tpep_pickup_datetime;
}
| 22.352941 | 82 | 0.724747 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example.data;
import java.nio.DoubleBuffer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Ride {
public Ride(String[] arr) {
VendorID = arr[0];
tpep_pickup_datetime = LocalDateTime.parse(arr[1], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
tpep_dropoff_datetime = LocalDateTime.parse(arr[2], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
passenger_count = Integer.parseInt(arr[3]);
trip_distance = Double.parseDouble(arr[4]);
RatecodeID = Long.parseLong(arr[5]);
store_and_fwd_flag = arr[6];
PULocationID = Long.parseLong(arr[7]);
DOLocationID = Long.parseLong(arr[8]);
payment_type = arr[9];
fare_amount = Double.parseDouble(arr[10]);
extra = Double.parseDouble(arr[11]);
mta_tax = Double.parseDouble(arr[12]);
tip_amount = Double.parseDouble(arr[13]);
tolls_amount = Double.parseDouble(arr[14]);
improvement_surcharge = Double.parseDouble(arr[15]);
total_amount = Double.parseDouble(arr[16]);
congestion_surcharge = Double.parseDouble(arr[17]);
}
public Ride(){}
public String VendorID;
public LocalDateTime tpep_pickup_datetime;
public LocalDateTime tpep_dropoff_datetime;
public int passenger_count;
public double trip_distance;
public long RatecodeID;
public String store_and_fwd_flag;
public long PULocationID;
public long DOLocationID;
public String payment_type;
public double fare_amount;
public double extra;
public double mta_tax;
public double tip_amount;
public double tolls_amount;
public double improvement_surcharge;
public double total_amount;
public double congestion_surcharge;
}
| 35.56 | 112 | 0.681445 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example.data;
import java.time.LocalDateTime;
public class VendorInfo {
public VendorInfo(String vendorID, long PULocationID, LocalDateTime pickupTime, LocalDateTime lastDropoffTime) {
VendorID = vendorID;
this.PULocationID = PULocationID;
this.pickupTime = pickupTime;
this.lastDropoffTime = lastDropoffTime;
}
public VendorInfo() {
}
public String VendorID;
public long PULocationID;
public LocalDateTime pickupTime;
public LocalDateTime lastDropoffTime;
}
| 23.590909 | 116 | 0.72037 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.internals.Topic;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.example.customserdes.CustomSerdes;
import org.example.data.PickupLocation;
import org.example.data.Ride;
import org.example.data.VendorInfo;
import org.example.helper.DataGeneratorHelper;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.xml.crypto.Data;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.*;
class JsonKStreamJoinsTest {
private Properties props = new Properties();
private static TopologyTestDriver testDriver;
private TestInputTopic<String, Ride> ridesTopic;
private TestInputTopic<String, PickupLocation> pickLocationTopic;
private TestOutputTopic<String, VendorInfo> outputTopic;
private Topology topology = new JsonKStreamJoins().createTopology();
@BeforeEach
public void setup() {
props = new Properties();
props.setProperty(StreamsConfig.APPLICATION_ID_CONFIG, "testing_count_application");
props.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:1234");
if (testDriver != null) {
testDriver.close();
}
testDriver = new TopologyTestDriver(topology, props);
ridesTopic = testDriver.createInputTopic(Topics.INPUT_RIDE_TOPIC, Serdes.String().serializer(), CustomSerdes.getSerde(Ride.class).serializer());
pickLocationTopic = testDriver.createInputTopic(Topics.INPUT_RIDE_LOCATION_TOPIC, Serdes.String().serializer(), CustomSerdes.getSerde(PickupLocation.class).serializer());
outputTopic = testDriver.createOutputTopic(Topics.OUTPUT_TOPIC, Serdes.String().deserializer(), CustomSerdes.getSerde(VendorInfo.class).deserializer());
}
@Test
public void testIfJoinWorksOnSameDropOffPickupLocationId() {
Ride ride = DataGeneratorHelper.generateRide();
PickupLocation pickupLocation = DataGeneratorHelper.generatePickUpLocation(ride.DOLocationID);
ridesTopic.pipeInput(String.valueOf(ride.DOLocationID), ride);
pickLocationTopic.pipeInput(String.valueOf(pickupLocation.PULocationID), pickupLocation);
assertEquals(outputTopic.getQueueSize(), 1);
var expected = new VendorInfo(ride.VendorID, pickupLocation.PULocationID, pickupLocation.tpep_pickup_datetime, ride.tpep_dropoff_datetime);
var result = outputTopic.readKeyValue();
assertEquals(result.key, String.valueOf(ride.DOLocationID));
assertEquals(result.value.VendorID, expected.VendorID);
assertEquals(result.value.pickupTime, expected.pickupTime);
}
@AfterAll
public static void shutdown() {
testDriver.close();
}
} | 44.460317 | 178 | 0.754803 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.example.customserdes.CustomSerdes;
import org.example.data.Ride;
import org.example.helper.DataGeneratorHelper;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Properties;
class JsonKStreamTest {
private Properties props;
private static TopologyTestDriver testDriver;
private TestInputTopic<String, Ride> inputTopic;
private TestOutputTopic<String, Long> outputTopic;
private Topology topology = new JsonKStream().createTopology();
@BeforeEach
public void setup() {
props = new Properties();
props.setProperty(StreamsConfig.APPLICATION_ID_CONFIG, "testing_count_application");
props.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:1234");
if (testDriver != null) {
testDriver.close();
}
testDriver = new TopologyTestDriver(topology, props);
inputTopic = testDriver.createInputTopic("rides", Serdes.String().serializer(), CustomSerdes.getSerde(Ride.class).serializer());
outputTopic = testDriver.createOutputTopic("rides-pulocation-count", Serdes.String().deserializer(), Serdes.Long().deserializer());
}
@Test
public void testIfOneMessageIsPassedToInputTopicWeGetCountOfOne() {
Ride ride = DataGeneratorHelper.generateRide();
inputTopic.pipeInput(String.valueOf(ride.DOLocationID), ride);
assertEquals(outputTopic.readKeyValue(), KeyValue.pair(String.valueOf(ride.DOLocationID), 1L));
assertTrue(outputTopic.isEmpty());
}
@Test
public void testIfTwoMessageArePassedWithDifferentKey() {
Ride ride1 = DataGeneratorHelper.generateRide();
ride1.DOLocationID = 100L;
inputTopic.pipeInput(String.valueOf(ride1.DOLocationID), ride1);
Ride ride2 = DataGeneratorHelper.generateRide();
ride2.DOLocationID = 200L;
inputTopic.pipeInput(String.valueOf(ride2.DOLocationID), ride2);
assertEquals(outputTopic.readKeyValue(), KeyValue.pair(String.valueOf(ride1.DOLocationID), 1L));
assertEquals(outputTopic.readKeyValue(), KeyValue.pair(String.valueOf(ride2.DOLocationID), 1L));
assertTrue(outputTopic.isEmpty());
}
@Test
public void testIfTwoMessageArePassedWithSameKey() {
Ride ride1 = DataGeneratorHelper.generateRide();
ride1.DOLocationID = 100L;
inputTopic.pipeInput(String.valueOf(ride1.DOLocationID), ride1);
Ride ride2 = DataGeneratorHelper.generateRide();
ride2.DOLocationID = 100L;
inputTopic.pipeInput(String.valueOf(ride2.DOLocationID), ride2);
assertEquals(outputTopic.readKeyValue(), KeyValue.pair("100", 1L));
assertEquals(outputTopic.readKeyValue(), KeyValue.pair("100", 2L));
assertTrue(outputTopic.isEmpty());
}
@AfterAll
public static void tearDown() {
testDriver.close();
}
} | 37.7375 | 139 | 0.715623 |
data-engineering-zoomcamp | https://github.com/DataTalksClub/data-engineering-zoomcamp | Free Data Engineering course! | 15,757 | 3,602 | 2023-12-05 01:08:47+00:00 | 2021-10-21 09:32:50+00:00 | 1,561 | null | Java | package org.example.helper;
import org.example.data.PickupLocation;
import org.example.data.Ride;
import org.example.data.VendorInfo;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
public class DataGeneratorHelper {
public static Ride generateRide() {
var arrivalTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
var departureTime = LocalDateTime.now().minusMinutes(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
return new Ride(new String[]{"1", departureTime, arrivalTime,"1","1.50","1","N","238","75","2","8","0.5","0.5","0","0","0.3","9.3","0"});
}
public static PickupLocation generatePickUpLocation(long pickupLocationId) {
return new PickupLocation(pickupLocationId, LocalDateTime.now());
}
}
| 38 | 145 | 0.715286 |
awesome-data-engineering | https://github.com/igorbarinov/awesome-data-engineering | A curated list of data engineering tools for software developers | 5,457 | 1,029 | 2023-12-04 22:33:30+00:00 | 2015-06-18 19:39:42+00:00 | 226 | Creative Commons Zero v1.0 Universal | Misc | name: CI
on:
pull_request:
branches: [master]
jobs:
Awesome_Lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- run: npx awesome-lint
| 15.615385 | 33 | 0.576744 |
awesome-data-engineering | https://github.com/igorbarinov/awesome-data-engineering | A curated list of data engineering tools for software developers | 5,457 | 1,029 | 2023-12-04 22:33:30+00:00 | 2015-06-18 19:39:42+00:00 | 226 | Creative Commons Zero v1.0 Universal | Misc | # Awesome Data Engineering [![Awesome](https://awesome.re/badge-flat2.svg)](https://github.com/sindresorhus/awesome)
> A curated list of awesome things related to Data Engineering.
## Contents
- [Databases](#databases)
- [Data Ingestion](#data-ingestion)
- [File System](#file-system)
- [Serialization format](#serialization-format)
- [Stream Processing](#stream-processing)
- [Batch Processing](#batch-processing)
- [Charts and Dashboards](#charts-and-dashboards)
- [Workflow](#workflow)
- [Data Lake Management](#data-lake-management)
- [ELK Elastic Logstash Kibana](#elk-elastic-logstash-kibana)
- [Docker](#docker)
- [Datasets](#datasets)
- [Realtime](#realtime)
- [Data Dumps](#data-dumps)
- [Monitoring](#monitoring)
- [Prometheus](#prometheus)
- [Testing](#testing)
- [Community](#community)
- [Forums](#forums)
- [Conferences](#conferences)
- [Podcasts](#podcasts)
## Databases
- Relational
- [RQLite](https://github.com/rqlite/rqlite) - Replicated SQLite using the Raft consensus protocol.
- [MySQL](https://www.mysql.com/) - The world's most popular open source database.
- [TiDB](https://github.com/pingcap/tidb) - TiDB is a distributed NewSQL database compatible with MySQL protocol.
- [Percona XtraBackup](https://www.percona.com/software/mysql-database/percona-xtrabackup) - Percona XtraBackup is a free, open source, complete online backup solution for all versions of Percona Server, MySQL® and MariaDB®.
- [mysql_utils](https://github.com/pinterest/mysql_utils) - Pinterest MySQL Management Tools.
- [MariaDB](https://mariadb.org/) - An enhanced, drop-in replacement for MySQL.
- [PostgreSQL](https://www.postgresql.org/) - The world's most advanced open source database.
- [Amazon RDS](https://aws.amazon.com/rds/) - Amazon RDS makes it easy to set up, operate, and scale a relational database in the cloud.
- [Crate.IO](https://crate.io/) - Scalable SQL database with the NOSQL goodies.
- Key-Value
- [Redis](https://redis.io/) - An open source, BSD licensed, advanced key-value cache and store.
- [Riak](https://docs.basho.com/riak/kv/) - A distributed database designed to deliver maximum data availability by distributing data across multiple servers.
- [AWS DynamoDB](https://aws.amazon.com/dynamodb/) - A fast and flexible NoSQL database service for all applications that need consistent, single-digit millisecond latency at any scale.
- [HyperDex](https://github.com/rescrv/HyperDex) - HyperDex is a scalable, searchable key-value store. Deprecated.
- [SSDB](https://ssdb.io) - A high performance NoSQL database supporting many data structures, an alternative to Redis.
- [Kyoto Tycoon](https://github.com/alticelabs/kyoto) - Kyoto Tycoon is a lightweight network server on top of the Kyoto Cabinet key-value database, built for high-performance and concurrency.
- [IonDB](https://github.com/iondbproject/iondb) - A key-value store for microcontroller and IoT applications.
- Column
- [Cassandra](https://cassandra.apache.org/) - The right choice when you need scalability and high availability without compromising performance.
- [Cassandra Calculator](https://www.ecyrd.com/cassandracalculator/) - This simple form allows you to try out different values for your Apache Cassandra cluster and see what the impact is for your application.
- [CCM](https://github.com/pcmanus/ccm) - A script to easily create and destroy an Apache Cassandra cluster on localhost.
- [ScyllaDB](https://github.com/scylladb/scylla) - NoSQL data store using the seastar framework, compatible with Apache Cassandra.
- [HBase](https://hbase.apache.org/) - The Hadoop database, a distributed, scalable, big data store.
- [AWS Redshift](https://aws.amazon.com/redshift/) - A fast, fully managed, petabyte-scale data warehouse that makes it simple and cost-effective to analyze all your data using your existing business intelligence tools.
- [FiloDB](https://github.com/filodb/FiloDB) - Distributed. Columnar. Versioned. Streaming. SQL.
- [Vertica](https://www.vertica.com) - Distributed, MPP columnar database with extensive analytics SQL.
- [ClickHouse](https://clickhouse.tech) - Distributed columnar DBMS for OLAP. SQL.
- Document
- [MongoDB](https://www.mongodb.com) - An open-source, document database designed for ease of development and scaling.
- [Percona Server for MongoDB](https://www.percona.com/software/mongo-database/percona-server-for-mongodb) - Percona Server for MongoDB® is a free, enhanced, fully compatible, open source, drop-in replacement for the MongoDB® Community Edition that includes enterprise-grade features and functionality.
- [MemDB](https://github.com/rain1017/memdb) - Distributed Transactional In-Memory Database (based on MongoDB).
- [Elasticsearch](https://www.elastic.co/) - Search & Analyze Data in Real Time.
- [Couchbase](https://www.couchbase.com/) - The highest performing NoSQL distributed database.
- [RethinkDB](https://rethinkdb.com/) - The open-source database for the realtime web.
- [RavenDB](https://ravendb.net/) - Fully Transactional NoSQL Document Database.
- Graph
- [Neo4j](https://neo4j.com/) - The world's leading graph database.
- [OrientDB](https://orientdb.com) - 2nd Generation Distributed Graph Database with the flexibility of Documents in one product with an Open Source commercial friendly license.
- [ArangoDB](https://www.arangodb.com/) - A distributed free and open-source database with a flexible data model for documents, graphs, and key-values.
- [Titan](https://titan.thinkaurelius.com) - A scalable graph database optimized for storing and querying graphs containing hundreds of billions of vertices and edges distributed across a multi-machine cluster.
- [FlockDB](https://github.com/twitter-archive/flockdb) - A distributed, fault-tolerant graph database by Twitter. Deprecated.
- Distributed
- [DAtomic](https://www.datomic.com) - The fully transactional, cloud-ready, distributed database.
- [Apache Geode](https://geode.apache.org/) - An open source, distributed, in-memory database for scale-out applications.
- [Gaffer](https://github.com/gchq/Gaffer) - A large-scale graph database.
- Timeseries
- [InfluxDB](https://github.com/influxdata/influxdb) - Scalable datastore for metrics, events, and real-time analytics.
- [OpenTSDB](https://github.com/OpenTSDB/opentsdb) - A scalable, distributed Time Series Database.
- [QuestDB](https://questdb.io/) - A relational column-oriented database designed for real-time analytics on time series and event data.
- [kairosdb](https://github.com/kairosdb/kairosdb) - Fast scalable time series database.
- [Heroic](https://github.com/spotify/heroic) - A scalable time series database based on Cassandra and Elasticsearch, by Spotify.
- [Druid](https://github.com/apache/incubator-druid) - Column oriented distributed data store ideal for powering interactive applications.
- [Riak-TS](https://basho.com/products/riak-ts/) - Riak TS is the only enterprise-grade NoSQL time series database optimized specifically for IoT and Time Series data.
- [Akumuli](https://github.com/akumuli/Akumuli) - Akumuli is a numeric time-series database. It can be used to capture, store and process time-series data in real-time. The word "akumuli" can be translated from esperanto as "accumulate".
- [Rhombus](https://github.com/Pardot/Rhombus) - A time-series object store for Cassandra that handles all the complexity of building wide row indexes.
- [Dalmatiner DB](https://github.com/dalmatinerdb/dalmatinerdb) - Fast distributed metrics database.
- [Blueflood](https://github.com/rackerlabs/blueflood) - A distributed system designed to ingest and process time series data.
- [Timely](https://github.com/NationalSecurityAgency/timely) - Timely is a time series database application that provides secure access to time series data based on Accumulo and Grafana.
- Other
- [Tarantool](https://github.com/tarantool/tarantool/) - Tarantool is an in-memory database and application server.
- [GreenPlum](https://github.com/greenplum-db/gpdb) - The Greenplum Database (GPDB) - An advanced, fully featured, open source data warehouse. It provides powerful and rapid analytics on petabyte scale data volumes.
- [cayley](https://github.com/cayleygraph/cayley) - An open-source graph database. Google.
- [Snappydata](https://github.com/SnappyDataInc/snappydata) - SnappyData: OLTP + OLAP Database built on Apache Spark.
- [TimescaleDB](https://www.timescale.com/) - Built as an extension on top of PostgreSQL, TimescaleDB is a time-series SQL database providing fast analytics, scalability, with automated data management on a proven storage engine.
## Data Ingestion
- [Kafka](https://kafka.apache.org/) - Publish-subscribe messaging rethought as a distributed commit log.
- [BottledWater](https://github.com/confluentinc/bottledwater-pg) - Change data capture from PostgreSQL into Kafka. Deprecated.
- [kafkat](https://github.com/airbnb/kafkat) - Simplified command-line administration for Kafka brokers.
- [kafkacat](https://github.com/edenhill/kafkacat) - Generic command line non-JVM Apache Kafka producer and consumer.
- [pg-kafka](https://github.com/xstevens/pg_kafka) - A PostgreSQL extension to produce messages to Apache Kafka.
- [librdkafka](https://github.com/edenhill/librdkafka) - The Apache Kafka C/C++ library.
- [kafka-docker](https://github.com/wurstmeister/kafka-docker) - Kafka in Docker.
- [kafka-manager](https://github.com/yahoo/kafka-manager) - A tool for managing Apache Kafka.
- [kafka-node](https://github.com/SOHU-Co/kafka-node) - Node.js client for Apache Kafka 0.8.
- [Secor](https://github.com/pinterest/secor) - Pinterest's Kafka to S3 distributed consumer.
- [Kafka-logger](https://github.com/uber/kafka-logger) - Kafka-winston logger for Node.js from uber.
- [AWS Kinesis](https://aws.amazon.com/kinesis/) - A fully managed, cloud-based service for real-time data processing over large, distributed data streams.
- [RabbitMQ](https://www.rabbitmq.com/) - Robust messaging for applications.
- [FluentD](https://www.fluentd.org) - An open source data collector for unified logging layer.
- [Embulk](https://www.embulk.org) - An open source bulk data loader that helps data transfer between various databases, storages, file formats, and cloud services.
- [Apache Sqoop](https://sqoop.apache.org) - A tool designed for efficiently transferring bulk data between Apache Hadoop and structured datastores such as relational databases.
- [Heka](https://github.com/mozilla-services/heka) - Data Acquisition and Processing Made Easy. Deprecated.
- [Gobblin](https://github.com/apache/incubator-gobblin) - Universal data ingestion framework for Hadoop from Linkedin.
- [Nakadi](https://nakadi.io) - Nakadi is an open source event messaging platform that provides a REST API on top of Kafka-like queues.
- [Pravega](https://www.pravega.io) - Pravega provides a new storage abstraction - a stream - for continuous and unbounded data.
- [Apache Pulsar](https://pulsar.apache.org/) - Apache Pulsar is an open-source distributed pub-sub messaging system.
- [AWS Data Wranlger](https://github.com/awslabs/aws-data-wrangler) - Utility belt to handle data on AWS.
- [Airbyte](https://airbyte.io/) - Open-source data integration for modern data teams.
## File System
- [HDFS](https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html) - A distributed file system designed to run on commodity hardware.
- [Snakebite](https://github.com/spotify/snakebite) - A pure python HDFS client.
- [AWS S3](https://aws.amazon.com/s3/) - Object storage built to retrieve any amount of data from anywhere.
- [smart_open](https://github.com/RaRe-Technologies/smart_open) - Utils for streaming large files (S3, HDFS, gzip, bz2).
- [Alluxio](https://www.alluxio.org/) - Alluxio is a memory-centric distributed storage system enabling reliable data sharing at memory-speed across cluster frameworks, such as Spark and MapReduce.
- [CEPH](https://ceph.com/) - Ceph is a unified, distributed storage system designed for excellent performance, reliability and scalability.
- [OrangeFS](https://www.orangefs.org/) - Orange File System is a branch of the Parallel Virtual File System.
- [SnackFS](https://github.com/tuplejump/snackfs-release) - SnackFS is our bite-sized, lightweight HDFS compatible FileSystem built over Cassandra.
- [GlusterFS](https://www.gluster.org/) - Gluster Filesystem.
- [XtreemFS](https://www.xtreemfs.org/) - Fault-tolerant distributed file system for all storage needs.
- [SeaweedFS](https://github.com/chrislusf/seaweedfs) - Seaweed-FS is a simple and highly scalable distributed file system. There are two objectives: to store billions of files! to serve the files fast! Instead of supporting full POSIX file system semantics, Seaweed-FS choose to implement only a key~file mapping. Similar to the word "NoSQL", you can call it as "NoFS".
- [S3QL](https://github.com/s3ql/s3ql/) - S3QL is a file system that stores all its data online using storage services like Google Storage, Amazon S3, or OpenStack.
- [LizardFS](https://lizardfs.com/) - LizardFS Software Defined Storage is a distributed, parallel, scalable, fault-tolerant, Geo-Redundant and highly available file system.
## Serialization format
- [Apache Avro](https://avro.apache.org) - Apache Avro™ is a data serialization system.
- [Apache Parquet](https://parquet.apache.org) - Apache Parquet is a columnar storage format available to any project in the Hadoop ecosystem, regardless of the choice of data processing framework, data model or programming language.
- [Snappy](https://github.com/google/snappy) - A fast compressor/decompressor. Used with Parquet.
- [PigZ](https://zlib.net/pigz/) - A parallel implementation of gzip for modern multi-processor, multi-core machines.
- [Apache ORC](https://orc.apache.org/) - The smallest, fastest columnar storage for Hadoop workloads.
- [Apache Thrift](https://thrift.apache.org) - The Apache Thrift software framework, for scalable cross-language services development.
- [ProtoBuf](https://github.com/protocolbuffers/protobuf) - Protocol Buffers - Google's data interchange format.
- [SequenceFile](https://wiki.apache.org/hadoop/SequenceFile) - SequenceFile is a flat file consisting of binary key/value pairs. It is extensively used in MapReduce as input/output formats.
- [Kryo](https://github.com/EsotericSoftware/kryo) - Kryo is a fast and efficient object graph serialization framework for Java.
## Stream Processing
- [Apache Beam](https://beam.apache.org/) - Apache Beam is a unified programming model that implements both batch and streaming data processing jobs that run on many execution engines.
- [Spark Streaming](https://spark.apache.org/streaming/) - Spark Streaming makes it easy to build scalable fault-tolerant streaming applications.
- [Apache Flink](https://flink.apache.org/) - Apache Flink is a streaming dataflow engine that provides data distribution, communication, and fault tolerance for distributed computations over data streams.
- [Apache Storm](https://storm.apache.org) - Apache Storm is a free and open source distributed realtime computation system.
- [Apache Samza](https://samza.apache.org) - Apache Samza is a distributed stream processing framework.
- [Apache NiFi](https://nifi.apache.org/) - An easy to use, powerful, and reliable system to process and distribute data.
- [Apache Hudi](https://hudi.apache.org/) - An open source framework for managing storage for real time processing, one of the most interesting feature is the Upsert.
- [VoltDB](https://voltdb.com/) - VoltDb is an ACID-compliant RDBMS which uses a [shared nothing architecture](https://en.wikipedia.org/wiki/Shared-nothing_architecture).
- [PipelineDB](https://github.com/pipelinedb/pipelinedb) - The Streaming SQL Database.
- [Spring Cloud Dataflow](https://cloud.spring.io/spring-cloud-dataflow/) - Streaming and tasks execution between Spring Boot apps.
- [Bonobo](https://www.bonobo-project.org/) - Bonobo is a data-processing toolkit for python 3.5+.
- [Robinhood's Faust](https://github.com/faust-streaming/faust) - Forever scalable event processing & in-memory durable K/V store as a library with asyncio & static typing.
- [HStreamDB](https://github.com/hstreamdb/hstream) - The streaming database built for IoT data storage and real-time processing.
- [Kuiper](https://github.com/emqx/kuiper) - An edge lightweight IoT data analytics/streaming software implemented by Golang, and it can be run at all kinds of resource-constrained edge devices.
- [Zilla](https://github.com/aklivity/zilla) - - An API gateway built for event-driven architectures and streaming that supports standard protocols such as HTTP, SSE, gRPC, MQTT and the native Kafka protocol.
## Batch Processing
- [Hadoop MapReduce](https://hadoop.apache.org/docs/current/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html) - Hadoop MapReduce is a software framework for easily writing applications which process vast amounts of data (multi-terabyte data-sets) - in-parallel on large clusters (thousands of nodes) - of commodity hardware in a reliable, fault-tolerant manner.
- [Spark](https://spark.apache.org/) - A multi-language engine for executing data engineering, data science, and machine learning on single-node machines or clusters.
- [Spark Packages](https://spark-packages.org) - A community index of packages for Apache Spark.
- [Deep Spark](https://github.com/Stratio/deep-spark) - Connecting Apache Spark with different data stores. Deprecated.
- [Spark RDD API Examples](https://homepage.cs.latrobe.edu.au/zhe/ZhenHeSparkRDDAPIExamples.html) - Examples by Zhen He.
- [Livy](https://livy.incubator.apache.org) - The REST Spark Server.
- [Delight](https://github.com/datamechanics/delight) - A free & cross platform monitoring tool (Spark UI / Spark History Server alternative).
- [AWS EMR](https://aws.amazon.com/emr/) - A web service that makes it easy to quickly and cost-effectively process vast amounts of data.
- [Data Mechanics](https://www.datamechanics.co) - A cloud-based platform deployed on Kubernetes making Apache Spark more developer-friendly and cost-effective.
- [Tez](https://tez.apache.org/) - An application framework which allows for a complex directed-acyclic-graph of tasks for processing data.
- [Bistro](https://github.com/asavinov/bistro) - A light-weight engine for general-purpose data processing including both batch and stream analytics. It is based on a novel unique data model, which represents data via _functions_ and processes data via _columns operations_ as opposed to having only set operations in conventional approaches like MapReduce or SQL.
- Batch ML
- [H2O](https://www.h2o.ai/) - Fast scalable machine learning API for smarter applications.
- [Mahout](https://mahout.apache.org/) - An environment for quickly creating scalable performant machine learning applications.
- [Spark MLlib](https://spark.apache.org/docs/latest/ml-guide.html) - Spark's scalable machine learning library consisting of common learning algorithms and utilities, including classification, regression, clustering, collaborative filtering, dimensionality reduction, as well as underlying optimization primitives.
- Batch Graph
- [GraphLab Create](https://turi.com/products/create/docs/) - A machine learning platform that enables data scientists and app developers to easily create intelligent apps at scale.
- [Giraph](https://giraph.apache.org/) - An iterative graph processing system built for high scalability.
- [Spark GraphX](https://spark.apache.org/graphx/) - Apache Spark's API for graphs and graph-parallel computation.
- Batch SQL
- [Presto](https://prestodb.github.io/docs/current/index.html) - A distributed SQL query engine designed to query large data sets distributed over one or more heterogeneous data sources.
- [Hive](https://hive.apache.org) - Data warehouse software facilitates querying and managing large datasets residing in distributed storage.
- [Hivemall](https://github.com/apache/incubator-hivemall) - Scalable machine learning library for Hive/Hadoop.
- [PyHive](https://github.com/dropbox/PyHive) - Python interface to Hive and Presto.
- [Drill](https://drill.apache.org/) - Schema-free SQL Query Engine for Hadoop, NoSQL and Cloud Storage.
## Charts and Dashboards
- [Highcharts](https://www.highcharts.com/) - A charting library written in pure JavaScript, offering an easy way of adding interactive charts to your web site or web application.
- [ZingChart](https://www.zingchart.com/) - Fast JavaScript charts for any data set.
- [C3.js](https://c3js.org) - D3-based reusable chart library.
- [D3.js](https://d3js.org/) - A JavaScript library for manipulating documents based on data.
- [D3Plus](https://d3plus.org) - D3's simplier, easier to use cousin. Mostly predefined templates that you can just plug data in.
- [SmoothieCharts](https://smoothiecharts.org) - A JavaScript Charting Library for Streaming Data.
- [PyXley](https://github.com/stitchfix/pyxley) - Python helpers for building dashboards using Flask and React.
- [Plotly](https://github.com/plotly/dash) - Flask, JS, and CSS boilerplate for interactive, web-based visualization apps in Python.
- [Apache Superset](https://github.com/apache/incubator-superset) - Apache Superset (incubating) - A modern, enterprise-ready business intelligence web application.
- [Redash](https://redash.io/) - Make Your Company Data Driven. Connect to any data source, easily visualize and share your data.
- [Metabase](https://github.com/metabase/metabase) - Metabase is the easy, open source way for everyone in your company to ask questions and learn from data.
- [PyQtGraph](https://www.pyqtgraph.org/) - PyQtGraph is a pure-python graphics and GUI library built on PyQt4 / PySide and numpy. It is intended for use in mathematics / scientific / engineering applications.
## Workflow
- [Luigi](https://github.com/spotify/luigi) - Luigi is a Python module that helps you build complex pipelines of batch jobs.
- [CronQ](https://github.com/seatgeek/cronq) - An application cron-like system. [Used](https://chairnerd.seatgeek.com/building-out-the-seatgeek-data-pipeline/) w/Luige. Deprecated.
- [Cascading](https://www.cascading.org/) - Java based application development platform.
- [Airflow](https://github.com/apache/airflow) - Airflow is a system to programmaticaly author, schedule and monitor data pipelines.
- [Azkaban](https://azkaban.github.io/) - Azkaban is a batch workflow job scheduler created at LinkedIn to run Hadoop jobs. Azkaban resolves the ordering through job dependencies and provides an easy to use web user interface to maintain and track your workflows.
- [Oozie](https://oozie.apache.org/) - Oozie is a workflow scheduler system to manage Apache Hadoop jobs.
- [Pinball](https://github.com/pinterest/pinball) - DAG based workflow manager. Job flows are defined programmaticaly in Python. Support output passing between jobs.
- [Dagster](https://github.com/dagster-io/dagster) - Dagster is an open-source Python library for building data applications.
- [Kedro](https://kedro.readthedocs.io/en/latest/) - Kedro is a framework that makes it easy to build robust and scalable data pipelines by providing uniform project templates, data abstraction, configuration and pipeline assembly.
- [Dataform](https://dataform.co/) - An open-source framework and web based IDE to manage datasets and their dependencies. SQLX extends your existing SQL warehouse dialect to add features that support dependency management, testing, documentation and more.
- [Census](https://getcensus.com/) - A reverse-ETL tool that let you sync data from your cloud data warehouse to SaaS applications like Salesforce, Marketo, HubSpot, Zendesk, etc. No engineering favors required—just SQL.
- [dbt](https://getdbt.com/) - A command line tool that enables data analysts and engineers to transform data in their warehouses more effectively.
- [RudderStack](https://github.com/rudderlabs/rudder-server) - A warehouse-first Customer Data Platform that enables you to collect data from every application, website and SaaS platform, and then activate it in your warehouse and business tools.
## Data Lake Management
- [lakeFS](https://github.com/treeverse/lakeFS) - lakeFS is an open source platform that delivers resilience and manageability to object-storage based data lakes.
## ELK Elastic Logstash Kibana
- [docker-logstash](https://github.com/pblittle/docker-logstash) - A highly configurable logstash (1.4.4) - docker image running Elasticsearch (1.7.0) - and Kibana (3.1.2).
- [elasticsearch-jdbc](https://github.com/jprante/elasticsearch-jdbc) - JDBC importer for Elasticsearch.
- [ZomboDB](https://github.com/zombodb/zombodb) - Postgres Extension that allows creating an index backed by Elasticsearch.
## Docker
- [Gockerize](https://github.com/redbooth/gockerize) - Package golang service into minimal docker containers.
- [Flocker](https://github.com/ClusterHQ/flocker) - Easily manage Docker containers & their data.
- [Rancher](https://rancher.com/rancher-os/) - RancherOS is a 20mb Linux distro that runs the entire OS as Docker containers.
- [Kontena](https://www.kontena.io/) - Application Containers for Masses.
- [Weave](https://github.com/weaveworks/weave) - Weaving Docker containers into applications.
- [Zodiac](https://github.com/CenturyLinkLabs/zodiac) - A lightweight tool for easy deployment and rollback of dockerized applications.
- [cAdvisor](https://github.com/google/cadvisor) - Analyzes resource usage and performance characteristics of running containers.
- [Micro S3 persistence](https://github.com/figadore/micro-s3-persistence) - Docker microservice for saving/restoring volume data to S3.
- [Rocker-compose](https://github.com/grammarly/rocker-compose) - Docker composition tool with idempotency features for deploying apps composed of multiple containers. Deprecated.
- [Nomad](https://github.com/hashicorp/nomad) - Nomad is a cluster manager, designed for both long lived services and short lived batch processing workloads.
- [ImageLayers](https://imagelayers.io/) - Vizualize docker images and the layers that compose them.
## Datasets
### Realtime
- [Twitter Realtime](https://developer.twitter.com/en/docs/tweets/filter-realtime/overview) - The Streaming APIs give developers low latency access to Twitter's global stream of Tweet data.
- [Eventsim](https://github.com/Interana/eventsim) - Event data simulator. Generates a stream of pseudo-random events from a set of users, designed to simulate web traffic.
- [Reddit](https://www.reddit.com/r/datasets/comments/3mk1vg/realtime_data_is_available_including_comments/) - Real-time data is available including comments, submissions and links posted to reddit.
### Data Dumps
- [GitHub Archive](https://www.gharchive.org/) - GitHub's public timeline since 2011, updated every hour.
- [Common Crawl](https://commoncrawl.org/) - Open source repository of web crawl data.
- [Wikipedia](https://dumps.wikimedia.org/enwiki/latest/) - Wikipedia's complete copy of all wikis, in the form of wikitext source and metadata embedded in XML. A number of raw database tables in SQL form are also available.
## Monitoring
### Prometheus
- [Prometheus.io](https://github.com/prometheus/prometheus) - An open-source service monitoring system and time series database.
- [HAProxy Exporter](https://github.com/prometheus/haproxy_exporter) - Simple server that scrapes HAProxy stats and exports them via HTTP for Prometheus consumption.
## Testing
- [Grai](https://github.com/grai-io/grai-core/) - A data catalog tool that integrates into your CI system exposing downstream impact testing of data changes. These tests prevent data changes which might break data pipelines or BI dashboards from making it to production.
## Community
### Forums
- [/r/dataengineering](https://www.reddit.com/r/dataengineering/) - News, tips and background on Data Engineering.
- [/r/etl](https://www.reddit.com/r/ETL/) - Subreddit focused on ETL.
### Conferences
- [Data Council](https://www.datacouncil.ai/about) - Data Council is the first technical conference that bridges the gap between data scientists, data engineers and data analysts.
### Podcasts
- [Data Engineering Podcast](https://www.dataengineeringpodcast.com/) - The show about modern data infrastructure.
| 96.40411 | 388 | 0.766288 |
awesome-data-engineering | https://github.com/igorbarinov/awesome-data-engineering | A curated list of data engineering tools for software developers | 5,457 | 1,029 | 2023-12-04 22:33:30+00:00 | 2015-06-18 19:39:42+00:00 | 226 | Creative Commons Zero v1.0 Universal | Misc | # Contribution Guidelines
Please ensure your pull request adheres to the following guidelines:
- Search previous suggestions before making a new one, as yours may be a duplicate.
- Make sure your list is useful before submitting. That implies it having enough content and every item a good succinct description.
- Link name or description should only include alphanumeric text, no emojis or images.
- A link back to this list from yours, so users can discover more lists, would be appreciated.
- Make an individual pull request for each suggestion.
- Titles should be [capitalized](http://grammar.yourdictionary.com/capitalization/rules-for-capitalization-in-titles.html).
- Use the following format: `[List Name](link)`
- Link additions should be added to the bottom of the relevant category.
- New categories or improvements to the existing categorization are welcome.
- Check your spelling and grammar.
- Make sure your text editor is set to remove trailing whitespace.
- The pull request and commit should have a useful title.
Thank you for your suggestions!
| 52.4 | 132 | 0.794752 |
awesome-data-engineering | https://github.com/igorbarinov/awesome-data-engineering | A curated list of data engineering tools for software developers | 5,457 | 1,029 | 2023-12-04 22:33:30+00:00 | 2015-06-18 19:39:42+00:00 | 226 | Creative Commons Zero v1.0 Universal | Misc | CC0 1.0 Universal
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
For more information, please see https://creativecommons.org/publicdomain/zero/1.0
| 157.02439 | 1,460 | 0.810898 |
Data-Engineering-HowTo | https://github.com/adilkhash/Data-Engineering-HowTo | A list of useful resources to learn Data Engineering from scratch | 2,916 | 420 | 2023-12-04 22:40:42+00:00 | 2019-03-28 07:43:26+00:00 | 39 | null | Misc | # How To Become a Data Engineer
### Useful articles
- [The AI Hierarchy of Needs](https://hackernoon.com/the-ai-hierarchy-of-needs-18f111fcc007)
- [The Rise of Data Engineer](https://medium.freecodecamp.org/the-rise-of-the-data-engineer-91be18f1e603)
- [The Downfall of the Data Engineer](https://medium.com/@maximebeauchemin/the-downfall-of-the-data-engineer-5bfb701e5d6b)
- A Beginner’s Guide to Data Engineering
- [Part I](https://medium.com/@rchang/a-beginners-guide-to-data-engineering-part-i-4227c5c457d7)
- [Part II](https://medium.com/@rchang/a-beginners-guide-to-data-engineering-part-ii-47c4e7cbda71?source=---------5------------------)
- [Part III](https://medium.com/@rchang/a-beginners-guide-to-data-engineering-the-series-finale-2cc92ff14b0?source=---------4------------------)
- [Functional Data Engineering — a modern paradigm for batch data processing](https://medium.com/@maximebeauchemin/functional-data-engineering-a-modern-paradigm-for-batch-data-processing-2327ec32c42a)
- How to become a Data Engineer [Ru](https://khashtamov.com/ru/data-engineer/), [En](https://khashtamov.com/en/how-to-become-a-data-engineer/)
- Introduction to Apache Airflow [Ru](https://khashtamov.com/ru/apache-airflow-introduction/?utm_source=github&utm_medium=dataeng-repository&utm_campaign=dataeng), [En](https://khashtamov.com/en/introduction-to-apache-airflow/)
### Talks
- [Data Engineering Principles - Build frameworks not pipelines](https://www.youtube.com/watch?v=pzfgbSfzhXg) by Gatis Seja
- [Functional Data Engineering - A Set of Best Practices](https://www.youtube.com/watch?v=4Spo2QRTz1k) by Maxime Beauchemin
- [Advanced Data Engineering Patterns with Apache Airflow](https://www.youtube.com/watch?v=Fvu2oFyFCT0) by Maxime Beauchemin
- [Creating a Data Engineering Culture](https://www.youtube.com/watch?v=VkeleGIUSM8) by Jesse Anderson
- [Streaming 101: Hello Streaming](https://www.youtube.com/watch?v=A1YC_AC0qf8) by Josh Fischer
### Algorithms & Data Structures
- [Algorithmic Toolbox](https://stepik.org/course/217) in Russian
- [Data Structures](https://stepik.org/course/1547) in Russian
- [Data Structures & Algorithms Specialization](https://www.coursera.org/specializations/data-structures-algorithms) on Coursera
- [Algorithms Specialization](https://www.coursera.org/specializations/algorithms) from Stanford on Coursera
### SQL
- [Comprehensive SQL Tutorial](https://mode.com/sql-tutorial/introduction-to-sql/) by Mode Analytics
- [SQL Practice](https://leetcode.com/problemset/database/) on Leetcode
- [Modern SQL](https://modern-sql.com/) a website about modern SQL syntax
- Introduction to Window Functions [En](https://khashtamov.com/en/sql-window-functions/), [Ru](https://khashtamov.com/ru/window-functions-sql/)
### Programming
- [Scala School](https://twitter.github.io/scala_school/) by Twitter
- [Fluent Python](https://www.amazon.com/gp/product/1491946008/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491946008&linkCode=as2&tag=adilkhash-20&linkId=8a663e966770c24874e323133cc7a005) intermediate level book about Python
- [Intro to Scala](https://stepik.org/course/16243) in Russian on Stepik by Tinkoff Bank
- [The Hitchhiker’s Guide to Python](https://docs.python-guide.org/) by Kenneth Reitz & Tanya Schlusser
- [Learn Python 3 The Hard Way](https://learnpythonthehardway.org/python3/) by Zed A. Shaw
### Databases
- [Intro to Database Systems](https://www.youtube.com/playlist?list=PLSE8ODhjZXjYutVzTeAds8xUt1rcmyT7x) by Carnegie Mellon University
- [Advanced Database Systems](https://www.youtube.com/playlist?list=PLSE8ODhjZXja7K1hjZ01UTVDnGQdx5v5U) by Carnegie Mellon University
- On Disk IO
- I. [Flavors of IO](https://medium.com/databasss/on-disk-io-part-1-flavours-of-io-8e1ace1de017)
- II. [More Flavours of IO](https://medium.com/databasss/on-disk-io-part-2-more-flavours-of-io-c945db3edb13)
- III. [LSM Trees](https://medium.com/databasss/on-disk-io-part-3-lsm-trees-8b2da218496f)
- IV. [B-Trees and RUM Conjecture](https://medium.com/databasss/on-disk-storage-part-4-b-trees-30791060741)
- V. [Access Patterns in LSM Trees](https://medium.com/databasss/on-disk-io-access-patterns-in-lsm-trees-2ba8dffc05f9)
### Distributed Systems
- [Distributed systems for fun and profit](http://book.mixu.net/distsys/) by Mikito Takada
- [Distributed Systems](https://www.amazon.com/gp/product/1543057381/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1543057381&linkCode=as2&tag=adilkhash-20&linkId=721aedeb23c313bc46a92c134c5baafa) by Maarten van Steen & Andrew S. Tanenbaum
- [CSE138: Distributed Systems](https://www.youtube.com/playlist?list=PLNPUF5QyWU8O0Wd8QDh9KaM1ggsxspJ31) by Lindsey Kuper
- [CS 436: Distributed Computer Systems](https://www.youtube.com/watch?v=w8KFPWkK0bI&list=PLawkBQ15NDEkDJ5IyLIJUTZ1rRM9YQq6N&index=2) by University of Waterloo
- [MIT 6.824: Distributed Systems](https://www.youtube.com/playlist?list=PLrw6a1wE39_tb2fErI4-WkMbsvGQk9_UB) by Robert Morris from MIT
- [Distributed consensus reading list](https://github.com/heidi-ann/distributed-consensus-reading-list) maintained by Heidi Howard from University of Cambridge
### Books
- [Design Data-Intensive Applications](https://www.amazon.com/gp/product/1449373321/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449373321&linkCode=as2&tag=adilkhash-20&linkId=e7e0e096aa5761066245eb90965ac849) by Martin Kleppmann
- [Introduction to Algorithms](https://www.amazon.com/gp/product/0262033844/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0262033844&linkCode=as2&tag=adilkhash-20&linkId=74742875db503b1a899ca35159749067) by Thomas Cormen
- [The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling](https://www.amazon.com/gp/product/1118530802/ref=as_li_tl?ie=UTF8&tag=adilkhash-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=1118530802&linkId=6ca865e8e9817dca57718bdbe5e52cd5)
- [Star Schema The Complete Reference](https://www.amazon.com/gp/product/0071744320/ref=as_li_tl?ie=UTF8&tag=adilkhash-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=0071744320&linkId=2abf9ef1d327071f74f59c3659ed6223)
- [Database Internals: A Deep Dive into How Distributed Data Systems Work](https://www.amazon.com/gp/product/1492040347/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1492040347&linkCode=as2&tag=adilkhash-20&linkId=4a23dead1aeb11fd4debffb36487aa14)
- [Streaming Systems: The What, Where, When, and How of Large-Scale Data Processing](https://www.amazon.com/gp/product/1491983876/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491983876&linkCode=as2&tag=adilkhash-20&linkId=9869047f1ac02b597d8a0e67fd29ad68)
- [A Philosophy of Software Design](https://www.amazon.com/gp/product/1732102201/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1732102201&linkCode=as2&tag=adilkhash-20&linkId=b020fab52fa5f1fed2191ea12e824468)
- [Grokking Streaming Systems](https://www.manning.com/books/grokking-streaming-systems) by Josh Fischer & Ning Wang
- [Guide to High Performance Distributed Computing](https://www.amazon.com/Guide-High-Performance-Distributed-Computing/dp/3319134965) by K.G. Srinivasa & Anil Kumar Muppalla
- [Data Pipelines with Apache Airflow](https://www.manning.com/books/data-pipelines-with-apache-airflow) by Bas P. Harenslak and Julian Rutger de Ruiter
### Courses
- [Data Engineering on Google Cloud Platform Specialization](https://www.coursera.org/specializations/gcp-data-machine-learning) by Google
- [Data Engineer Nanodegree](https://udacity.com/course/data-engineer-nanodegree--nd027) by Udacity
- [Data Engineering with Python](https://www.datacamp.com/tracks/data-engineer-with-python) by DataCamp
### Blogs
- [Martin Kleppmann](https://martin.kleppmann.com/) author of Designing Data-Intensive Application
- [BaseDS](https://medium.com/baseds) by Vaidehi Joshi about Distributed Systems
### Tools
- [Apache Airflow](https://airflow.apache.org/) is a platform to programmatically author, schedule and monitor workflows in Python
- [Apache Spark](https://spark.apache.org/) is a unified analytics engine for large-scale data processing
- [Apache Kafka](https://kafka.apache.org/) is a distributed streaming platform
- [Luigi](https://luigi.readthedocs.io) is a Python package that helps you build complex pipelines of batch jobs.
- [Dagster.io](https://docs.dagster.io) is a system for building modern data applications.
- [Prefect](https://prefect.io) includes everything you need to create and run data applications.
- [Metaflow](https://github.com/Netflix/metaflow) build and manage real-life data science projects with ease
- [lakeFS](https://github.com/treeverse/lakeFS) build repeatable, atomic and versioned data lake operations – from complex ETL jobs to data science and analytics.
### Cloud Platforms
- [Amazon Web Services](https://aws.amazon.com/)
- [Google Cloud Platform](https://cloud.google.com/gcp/)
- [Microsoft Azure](https://azure.microsoft.com)
- [Yandex Cloud](https://cloud.yandex.ru/)
- [DigitalOcean](https://m.do.co/c/e92056c9e79b)
- [IBM Cloud](https://www.ibm.com/cloud/)
### Communities
- [data Engineering](https://t.me/dataeng_chat) - telegram chat about data engineering
- [Data Engineering Subreddit](https://www.reddit.com/r/dataengineering/) - subreddit about data engineering
### Data Engineering Jobs
- [Data Engineering jobs](http://bit.ly/2vk0R86)
### Other
- [Data Engineering Podcast](https://www.dataengineeringpodcast.com/)
### Newsletters & Digests
- [DataEng Telegram channel](https://t.me/dataeng) - Telegram channel about data engineering (rus/eng)
- [Data Engineering Weekly](https://www.dataengineeringweekly.com/)
- [SF Data Weekly](http://weekly.sfdata.io) - A weekly email of useful links for people interested in building data platforms
- [Data Elixir](https://dataelixir.com/) - Data Elixir is an email newsletter that keeps you on top of the tools and trends in Data Science.
- [Data Governance, Privacy and Security](https://dbadmin.news/) - DbAdmin News is a news letter on the technology behind Data Governance, Security and Privacy
| 86.565217 | 269 | 0.779919 |
Udacity-Data-Engineering-Projects | https://github.com/san089/Udacity-Data-Engineering-Projects | Few projects related to Data Engineering including Data Modeling, Infrastructure setup on cloud, Data Warehousing and Data Lake development. | 1,219 | 433 | 2023-12-04 20:08:27+00:00 | 2020-01-20 22:50:03+00:00 | 2,128 | Other | Misc | # Data Engineering Projects
![](https://github.com/san089/Udacity-Data-Engineering-Projects/blob/master/image.jpeg)
## Project 1: Data Modeling with Postgres
In this project, we apply Data Modeling with Postgres and build an ETL pipeline using Python. A startup wants to analyze the data they've been collecting on songs and user activity on their new music streaming app. Currently, they are collecting data in json format and the analytics team is particularly interested in understanding what songs users are listening to.
Link: [Data_Modeling_with_Postgres](https://github.com/san089/Udacity-Data-Engineering-Projects/tree/master/Data_Modeling_with_Postgres)
## Project 2: Data Modeling with Cassandra
In this project, we apply Data Modeling with Cassandra and build an ETL pipeline using Python. We will build a Data Model around our queries that we want to get answers for.
For our use case we want below answers:
- Get details of a song that was herad on the music app history during a particular session.
- Get songs played by a user during particular session on music app.
- Get all users from the music app history who listened to a particular song.
Link : [Data_Modeling_with_Apache_Cassandra](https://github.com/san089/Udacity-Data-Engineering-Projects/tree/master/Data_Modeling_with_Apache_Cassandra)
## Project 3: Data Warehouse
In this project, we apply the Data Warehouse architectures we learnt and build a Data Warehouse on AWS cloud. We build an ETL pipeline to extract and transform data stored in json format in s3 buckets and move the data to Warehouse hosted on Amazon Redshift.
Use Redshift IaC script - [Redshift_IaC_README](https://github.com/san089/Udacity-Data-Engineering-Projects/blob/master/Redshift_IaC_README.md)
Link - [Data_Warehouse](https://github.com/san089/Udacity-Data-Engineering-Projects/tree/master/Data_Warehouse)
## Project 4: Data Lake
In this project, we will build a Data Lake on AWS cloud using Spark and AWS EMR cluster. The data lake will serve as a Single Source of Truth for the Analytics Platform. We will write spark jobs to perform ELT operations that picks data from landing zone on S3 and transform and stores data on the S3 processed zone.
Link: [Data_Lake](https://github.com/san089/Udacity-Data-Engineering-Projects/tree/master/Data_Lake)
## Project 5: Data Pipelines with Airflow
In this project, we will orchestrate our Data Pipeline workflow using an open-source Apache project called Apache Airflow. We will schedule our ETL jobs in Airflow, create project related custom plugins and operators and automate the pipeline execution.
Link: [Airflow_Data_Pipelines](https://github.com/san089/Udacity-Data-Engineering-Projects/tree/master/Airflow_Data_Pipelines)
## Project 6: Api Data to Postgres
In this project, we build an etl pipeline to fetch data from yelp API and insert it into the Postgres Database. This project is a very basic example of fetching real time data from an open source API.
Link: [API to Postgres](https://github.com/san089/Udacity-Data-Engineering-Projects/tree/master/Data_Api_to_Postgres)
## CAPSTONE PROJECT
Udacity provides their own crafted Capstone project with dataset that include data on immigration to the United States, and supplementary datasets that include data on airport codes, U.S. city demographics, and temperature data.
I worked on my own open-ended project. <br />
Here is the link - [goodreads_etl_pipeline](https://github.com/san089/goodreads_etl_pipeline)
| 73.425532 | 367 | 0.794109 |
Udacity-Data-Engineering-Projects | https://github.com/san089/Udacity-Data-Engineering-Projects | Few projects related to Data Engineering including Data Modeling, Infrastructure setup on cloud, Data Warehousing and Data Lake development. | 1,219 | 433 | 2023-12-04 20:08:27+00:00 | 2020-01-20 22:50:03+00:00 | 2,128 | Other | Misc | �PNG
IHDR � 5��S �PLTEFFFIIIrqqUTT���MON�RC�VH�2$�RC��КRF[[Z���eee3Ȍ���������```lkk���������������xww}}}���������������������������;�pAmZtttnE;6���L:߮Cǀ7�?0̾�` �����{�.� ��IDATx��[�>�sV�L���mnӯ.g
����sO���AqZ�熋��-���=MbUS @��) �Z * �b * �b * �b * �b * �b * �b * �b * �bԴ�����h�l'�S�.���R��q
�� ' � * @�@ �Mh�V`|@ T @�@ T @�T.��' �R� ~L~+ :�E�Ue@ �afR�QD�`ź�V"ea=@\���X)�I5�Ef�X�EU�ePf����)�"�]�+'�Ƙ��R۩f��������͢��dDYd1@�:Q����}MJ��Sw�1�m]� ԓ�Af��*BL�_&��KS�q�f�.�X���(�{,�pܥ�kT�f`ˠ�l�7 �bI��������p�pٻ_c]�&��nɯ��Y��LE@ j#�c'Y����R@�2b)HE��M�3���R�g@T�M8ӓ}v/��4q�\��Q
גWDq%R��
���5��T.���B�(D���������9i%3 21���
@L��z ��ȅ ��_��W&��Tu`*����W�=�:�[x^1v�ۣ�8+ �h�/B3��KF�W��@Q?(�<�똅 J\/��e��
0s��[[iR�� U5�B �2�o2_$��N#���k��uo��]�^@ܩ���-FKu�@qzѤ��� �s�B�* 9���6�7�
�̈�A�����;$��l�p�e�v�J2F�NZ�:4@q�7�^�� ,�{#�KНM�C����g�� ��{�rĥ@��NB6�[f #4@\[t��3@��2���3�����e�� *�X"2���*��, ��>���� �)����fk�Ϫ�wȤ~"]�=@9�d�B�"�FtX0�\'Ԗ����^�͚�=�#�0��J%�&m� C��`�k<Ģ��n�P� ��t��P*!�;t��
��q��گ�5��G������� ��P������Q� �M�i��٣ � )� �g�^Tg��+�b�(��1�>z���<Y ����/�<�"i���l*`�xd&�&��?��9�^ �T�7f�q�(��5@6g���g���@SږSm0��"�Y����z�< |