-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspark_structured_streaming.py
37 lines (29 loc) · 1.07 KB
/
spark_structured_streaming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from os import truncate
from pyspark.sql import SparkSession
from pyspark.sql import functions as f
BOOTSTRAP_SERVER = "localhost:29092"
TOPIC_NAME = "data_pengguna"
spark = SparkSession \
.builder \
.appName("StructuredStreamingContoh") \
.getOrCreate()
spark.sparkContext.setLogLevel('WARN')
df = spark \
.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", BOOTSTRAP_SERVER) \
.option("subscribe", TOPIC_NAME) \
.option("startingOffsets", "earliest") \
.load()
def foreach_batch_function(data, epoch_id):
data.show(truncate=False)
df \
.withColumn("value", f.col("value").cast("STRING")) \
.withColumn("nama", f.get_json_object(f.col("value"), "$.nama")) \
.withColumn("alamat", f.regexp_replace(f.get_json_object(f.col("value"), "$.alamat"), "[\n\r]", " ")) \
.withColumn("tanggal_lahir", f.get_json_object(f.col("value"), "$.tanggal_lahir").cast("date")) \
.select("nama", "alamat", "tanggal_lahir") \
.writeStream \
.foreachBatch(foreach_batch_function) \
.start() \
.awaitTermination()