Created
February 28, 2019 15:54
-
-
Save ravi-tejarockon/0d33e1e317180cd1c3e1068d85a7e5d5 to your computer and use it in GitHub Desktop.
Spark & Kafka Integration - Spark Structured Streaming Streaming (Spark 2.x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Running locations: | |
# Exeucing Command: bin\spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.11 <location_of_code>\structured_kafka_wc.py localhost:2181 <topic_name> | |
# Location to Execute: <location_of_spark_bin> | |
# https://github.com/apache/spark/blob/v2.3.1/examples/src/main/python/sql/streaming/structured_kafka_wordcount.py | |
from __future__ import print_function | |
import sys | |
import os | |
os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.3.1 pyspark-shell' | |
from pyspark.sql import SparkSession | |
from pyspark.sql.functions import explode | |
from pyspark.sql.functions import split | |
if __name__ == "__main__": | |
if len(sys.argv) != 4: | |
print(""" | |
Usage: structured_kafka_wordcount.py <bootstrap-servers> <subscribe-type> <topics> | |
""", file=sys.stderr) | |
exit(-1) | |
bootstrapServers = sys.argv[1] | |
subscribeType = sys.argv[2] | |
topics = sys.argv[3] | |
spark = SparkSession\ | |
.builder\ | |
.appName("StructuredKafkaWordCount")\ | |
.getOrCreate() | |
# Create DataSet representing the stream of input lines from kafka | |
lines = spark\ | |
.readStream\ | |
.format("kafka")\ | |
.option("kafka.bootstrap.servers", bootstrapServers)\ | |
.option(subscribeType, topics)\ | |
.load()\ | |
.selectExpr("CAST(value AS STRING)") | |
# Split the lines into words | |
words = lines.select( | |
# explode turns each item in an array into a separate row | |
explode( | |
split(lines.value, ' ') | |
).alias('word') | |
) | |
# Generate running word count | |
wordCounts = words.groupBy('word').count() | |
# Start running the query that prints the running counts to the console | |
query = wordCounts\ | |
.writeStream\ | |
.outputMode('complete')\ | |
.format('console')\ | |
.start() | |
query.awaitTermination() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment