编程语言
首页 > 编程语言> > Structured Streaming编程 Programming Guide

Structured Streaming编程 Programming Guide

作者:互联网

Structured Streaming编程 Programming Guide

Overview

Structured Streaming is a scalable and fault-tolerant stream processing engine built on the Spark SQL engine. You can express your streaming computation the same way you would express a batch computation on static data. The Spark SQL engine will take care of running it incrementally and continuously and updating the final result as streaming data continues to arrive. You can use the Dataset/DataFrame API in Scala, Java, Python or R to express streaming aggregations, event-time windows, stream-to-batch joins, etc. The computation is executed on the same optimized Spark SQL engine. Finally, the system ensures end-to-end exactly-once fault-tolerance guarantees through checkpointing and Write-Ahead Logs. In short, Structured Streaming provides fast, scalable, fault-tolerant, end-to-end exactly-once stream processing without the user having to reason about streaming.

Internally, by default, Structured Streaming queries are processed using a micro-batch processing engine, which processes data streams as a series of small batch jobs thereby achieving end-to-end latencies as low as 100 milliseconds and exactly-once fault-tolerance guarantees. However, since Spark 2.3, we have introduced a new low-latency processing mode called Continuous Processing, which can achieve end-to-end latencies as low as 1 millisecond with at-least-once guarantees. Without changing the Dataset/DataFrame operations in your queries, you will be able to choose the mode based on your application requirements.

In this guide, we are going to walk you through the programming model and the APIs. We are going to explain the concepts mostly using the default micro-batch processing model, and then later discuss Continuous Processing model. First, let’s start with a simple example of a Structured Streaming query - a streaming word count.

结构化流是基于Spark SQL引擎构建的可伸缩且容错的流处理引擎。可以像对静态数据进行批处理计算一样,来表示流计算。当流数据继续到达时,Spark SQL引擎负责递增地,连续地运行,并更新最终结果。可以在Scala,Java,Python或R中使用Dataset / DataFrame API来表示流聚合,事件时间窗口,流到批处理联接等。计算是在同一优化的Spark SQL引擎上执行的。最后,系统通过检查点和预写日志来确保端到端的一次容错。简而言之,结构化流提供了快速,可扩展,容错,端到端的一次精确流处理,而用户无需推理流。

在内部,默认情况下,结构化流查询是使用微批量处理引擎处理的,该引擎将数据流作为一系列小批量作业处理,从而实现了低至100毫秒的端到端延迟以及一次精确的容错保证。但是,从Spark 2.3开始,引入了一种称为“连续处理”的新低延迟处理模式,该模式可以实现一次最少保证的低至1毫秒的端到端延迟。在不更改查询中的Dataset / DataFrame操作的情况下,将能够根据应用程序需求选择模式。

本文将逐步了解编程模型和API。主要使用默认的微批处理模型来解释这些概念,然后讨论连续处理模型。首先,让从结构化流查询的简单示例开始-流字数。

Quick Example

Let’s say you want to maintain a running word count of text data received from a data server listening on a TCP socket. Let’s see how you can express this using Structured Streaming. You can see the full code in Scala/Java/Python/R. And if you download Spark, you can directly run the example. In any case, let’s walk through the example step-by-step and understand how it works. First, we have to import the necessary classes and create a local SparkSession, the starting point of all functionalities related to Spark.

假设要维护从侦听TCP套接字的数据服务器接收到的,文本数据的运行字数。看看如何使用结构化流来表达这一点。可以在Scala / Java / Python / R中看到完整的代码 。如果下载了Spark,则可以直接运行该示例。无论如何,逐步介绍该示例并了解其工作原理。首先,必须导入必要的类,创建一个本地SparkSession,这是与Spark相关的所有功能的起点。

import org.apache.spark.sql.functions._

import org.apache.spark.sql.SparkSession

 

val spark = SparkSession

  .builder

  .appName("StructuredNetworkWordCount")

  .getOrCreate()

 

import spark.implicits._

Next, let’s create a streaming DataFrame that represents text data received from a server listening on localhost:9999, and transform the DataFrame to calculate word counts. 接下来,创建一个流数据框架,该数据框架表示从在localhost:9999上侦听的服务器接收的文本数据,并对数据框架进行转换以计算字数。

// Create DataFrame representing the stream of input lines from connection to localhost:9999

val lines = spark.readStream

  .format("socket")

  .option("host", "localhost")

  .option("port", 9999)

  .load()

 

// Split the lines into words

val words = lines.as[String].flatMap(_.split(" "))

 

// Generate running word count

val wordCounts = words.groupBy("value").count()

This lines DataFrame represents an unbounded table containing the streaming text data. This table contains one column of strings named “value”, and each line in the streaming text data becomes a row in the table. Note, that this is not currently receiving any data as we are just setting up the transformation, and have not yet started it. Next, we have converted the DataFrame to a Dataset of String using .as[String], so that we can apply the flatMap operation to split each line into multiple words. The resultant words Dataset contains all the words. Finally, we have defined the wordCounts DataFrame by grouping by the unique values in the Dataset and counting them. Note that this is a streaming DataFrame which represents the running word counts of the stream.

We have now set up the query on the streaming data. All that is left is to actually start receiving data and computing the counts. To do this, we set it up to print the complete set of counts (specified by outputMode("complete")) to the console every time they are updated. And then start the streaming computation using start().

linesDataFrame表示一个包含流文本数据的无边界表。该表包含一列名为“值”的字符串,流文本数据中的每一行都成为表中的一行。由于正在设置转换,并且尚未开始转换,目前未接收任何数据。接下来,使用DataFrame转换为String的Dataset .as[String],以便可以应用该flatMap算子,将每一行拆分为多个单词。结果words数据集包含所有单词。最后,wordCounts通过对数据集中的唯一值进行分组,对其进行计数来定义DataFrame。这是一个流数据帧,表示流的运行字数。

现在,对流数据进行了查询。剩下的就是实际开始接收数据并计算计数了。为此,将其设置outputMode("complete")为在每次更新计数时,将完整的计数集(由指定)打印到控制台。然后使用start()开始流计算。

// Start running the query that prints the running counts to the console

val query = wordCounts.writeStream

  .outputMode("complete")

  .format("console")

  .start()

 

query.awaitTermination()

After this code is executed, the streaming computation will have started in the background. The query object is a handle to that active streaming query, and we have decided to wait for the termination of the query using awaitTermination() to prevent the process from exiting while the query is active.

To actually execute this example code, you can either compile the code in your own Spark application, or simply run the example once you have downloaded Spark. We are showing the latter. You will first need to run Netcat (a small utility found in most Unix-like systems) as a data server by using

执行此代码后,流计算将在后台开始。该query对象是该活动流查询的句柄,已决定等待查询终止,awaitTermination()以防止该查询处于活动状态时退出该过程。

要实际执行此示例代码,可以在Spark应用程序中编译代码,也可以在 下载Spark之后直接 运行示例。正在展示后者。首先需要通过使用以下命令将Netcat(在大多数类Unix系统中找到的一个小实用程序)作为数据服务器运行。

$ nc -lk 9999

Then, in a different terminal, you can start the example by using

$ ./bin/run-example org.apache.spark.examples.sql.streaming.StructuredNetworkWordCount localhost 9999

Then, any lines typed in the terminal running the netcat server will be counted and printed on screen every second. It will look something like the following.

然后,每秒钟在运行netcat服务器的终端中键入的任何行,都将被计数并打印在屏幕上。类似于以下内容。

# TERMINAL 1:

# Running Netcat

 

$ nc -lk 9999

apache spark

apache hadoop

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

...

 

# TERMINAL 2: RUNNING StructuredNetworkWordCount

 

$ ./bin/run-example org.apache.spark.examples.sql.streaming.StructuredNetworkWordCount localhost 9999

 

-------------------------------------------

Batch: 0

-------------------------------------------

+------+-----+

| value|count|

+------+-----+

|apache|    1|

| spark|    1|

+------+-----+

 

-------------------------------------------

Batch: 1

-------------------------------------------

+------+-----+

| value|count|

+------+-----+

|apache|    2|

| spark|    1|

|hadoop|    1|

+------+-----+

...

Programming Model

The key idea in Structured Streaming is to treat a live data stream as a table that is being continuously appended. This leads to a new stream processing model that is very similar to a batch processing model. You will express your streaming computation as standard batch-like query as on a static table, and Spark runs it as an incremental query on the unbounded input table. Let’s understand this model in more detail.

结构化流处理中的关键思想,将实时数据流视为被连续追加的表。这导致了一个新的流处理模型,该模型与批处理模型非常相似。将像在静态表上一样,将流计算表示为类似于批处理的标准查询,Spark在无界输入表上,将其作为增量查询运行。更详细地了解此模型。

Basic Concepts

Consider the input data stream as the “Input Table”. Every data item that is arriving on the stream is like a new row being appended to the Input Table.

将输入数据流视为“输入表”。流上到达的每个数据项都像是将新行附加到输入表中。

 

 

 A query on the input will generate the “Result Table”. Every trigger interval (say, every 1 second), new rows get appended to the Input Table, which eventually updates the Result Table. Whenever the result table gets updated, we would want to write the changed result rows to an external sink.

查询输入,生成“结果表”。在每个触发间隔(例如,每1秒钟),新行将附加到输入表中,并最终更新结果表。无论何时更新结果表,都希望将更改后的结果行写入外部接收器。

 

 

 The “Output” is defined as what gets written out to the external storage. The output can be defined in a different mode:

Note that each mode is applicable on certain types of queries. This is discussed in detail later.

To illustrate the use of this model, let’s understand the model in context of the Quick Example above. The first lines DataFrame is the input table, and the final wordCounts DataFrame is the result table. Note that the query on streaming lines DataFrame to generate wordCounts is exactly the same as it would be a static DataFrame. However, when this query is started, Spark will continuously check for new data from the socket connection. If there is new data, Spark will run an “incremental” query that combines the previous running counts with the new data to compute updated counts, as shown below.

“输出”定义为写到外部存储器的内容。可以在不同的模式下定义输出:

每种模式都适用于某些类型的查询。稍后将对此进行详细讨论。

为了说明此模型的用法,在上面的“快速示例”的上下文中了解该模型。第一个linesDataFrame是输入表,最后一个wordCountsDataFrame是结果表。在流媒体的查询lines数据帧生成wordCounts完全一样的,因为是一个静态的数据帧。但是,启动此查询时,Spark将不断检查套接字连接中是否有新数据。如果有新数据,Spark将运行一个“增量”查询,该查询将先前的运行计数与新数据结合起来以计算更新的计数,如下所示。

 

 

 Note that Structured Streaming does not materialize the entire table. It reads the latest available data from the streaming data source, processes it incrementally to update the result, and then discards the source data. It only keeps around the minimal intermediate state data as required to update the result (e.g. intermediate counts in the earlier example).

This model is significantly different from many other stream processing engines. Many streaming systems require the user to maintain running aggregations themselves, thus having to reason about fault-tolerance, and data consistency (at-least-once, or at-most-once, or exactly-once). In this model, Spark is responsible for updating the Result Table when there is new data, thus relieving the users from reasoning about it. As an example, let’s see how this model handles event-time based processing and late arriving data.

结构化流技术不会实现整个表。从流数据源读取最新的可用数据,对其进行增量处理以更新结果,然后丢弃该源数据。仅保留更新结果所需的最小中间状态数据(例如,前面示例中的中间计数)。

此模型与许多其它流处理引擎明显不同。许多流系统要求用户自己维护运行中的聚合,因此必须考虑容错和数据一致性(至少一次,最多一次或恰好一次)。在此模型中,Spark负责在有新数据时更新结果表,从而使用户免于推理。作为示例,看看该模型如何处理基于事件时间的处理和延迟到达的数据。

Handling Event-time and Late Data

Event-time is the time embedded in the data itself. For many applications, you may want to operate on this event-time. For example, if you want to get the number of events generated by IoT devices every minute, then you probably want to use the time when the data was generated (that is, event-time in the data), rather than the time Spark receives them. This event-time is very naturally expressed in this model – each event from the devices is a row in the table, and event-time is a column value in the row. This allows window-based aggregations (e.g. number of events every minute) to be just a special type of grouping and aggregation on the event-time column – each time window is a group and each row can belong to multiple windows/groups. Therefore, such event-time-window-based aggregation queries can be defined consistently on both a static dataset (e.g. from collected device events logs) as well as on a data stream, making the life of the user much easier.

Furthermore, this model naturally handles data that has arrived later than expected based on its event-time. Since Spark is updating the Result Table, it has full control over updating old aggregates when there is late data, as well as cleaning up old aggregates to limit the size of intermediate state data. Since Spark 2.1, we have support for watermarking which allows the user to specify the threshold of late data, and allows the engine to accordingly clean up old state. These are explained later in more detail in the Window Operations section.

事件时间是嵌入数据本身的时间。对于许多应用程序,可能希望在此事件时间进行操作。例如,如果要获取每分钟由IoT设备生成的事件数,则可能要使用生成数据的时间(即数据中的事件时间),而不是Spark收到的时间。此事件时间在此模型中非常自然地表达-设备中的每个事件,都是表中的一行,而事件时间是该行中的列值。允许基于窗口的聚合(例如,每分钟的事件数),只是事件时间列上的一种特殊类型的分组和聚合-每个时间窗口都是一个组,每行可以属于多个窗口/组。

此外,此模型自然会根据事件时间处理比预期时间晚到达的数据。由于Spark正在更新结果表,具有完全控制权,可以在有较晚数据时更新旧聚合,并可以清除旧聚合以限制中间状态数据的大小。从Spark 2.1开始,支持水印功能,该功能允许用户指定最新数据的阈值,并允许引擎相应地清除旧状态。这些将在后面的“窗口操作”部分中详细介绍。

Fault Tolerance Semantics

Delivering end-to-end exactly-once semantics was one of key goals behind the design of Structured Streaming. To achieve that, we have designed the Structured Streaming sources, the sinks and the execution engine to reliably track the exact progress of the processing so that it can handle any kind of failure by restarting and/or reprocessing. Every streaming source is assumed to have offsets (similar to Kafka offsets, or Kinesis sequence numbers) to track the read position in the stream. The engine uses checkpointing and write-ahead logs to record the offset range of the data being processed in each trigger. The streaming sinks are designed to be idempotent for handling reprocessing. Together, using replayable sources and idempotent sinks, Structured Streaming can ensure end-to-end exactly-once semantics under any failure.

提供端到端的一次语义是结构化流设计背后的主要目标之一。为此,设计了结构化流源,接收器和执行引擎,可靠地跟踪处理的确切进度,可以通过重新启动和/或重新处理来处理任何类型的故障。假定每个流源都有偏移量(类似于Kafka偏移量或Kinesis序列号),跟踪流中的读取位置。引擎使用检查点和预写日志,记录每个触发器中正在处理的数据的偏移范围。流接收器被设计为是幂等的idempotent,用于处理后处理。结合使用可重播的源和幂等的idempotent接收器,结构化流可以确保端到端的一次精确语义 在任何故障下。

API using Datasets and DataFrames

Since Spark 2.0, DataFrames and Datasets can represent static, bounded data, as well as streaming, unbounded data. Similar to static Datasets/DataFrames, you can use the common entry point SparkSession (Scala/Java/Python/R docs) to create streaming DataFrames/Datasets from streaming sources, and apply the same operations on them as static DataFrames/Datasets. If you are not familiar with Datasets/DataFrames, you are strongly advised to familiarize yourself with them using the DataFrame/Dataset Programming Guide.

从Spark 2.0开始,DataFrame和Dataset可以表示静态的有界数据,以及流式无界数据。与静态数据集/数据框类似,可以使用公共入口点SparkSession (Scala / Java / Python / R docs),从流源创建流式数据框/数据集,应用与静态数据框/数据集相同的操作。如果不熟悉Datasets / DataFrames,强烈建议使用DataFrame / Dataset编程指南来熟悉 。

Creating streaming DataFrames and streaming Datasets

Streaming DataFrames can be created through the DataStreamReader interface (Scala/Java/Python docs) returned by SparkSession.readStream(). In R, with the read.stream() method. Similar to the read interface for creating static DataFrame, you can specify the details of the source – data format, schema, options, etc.

可以通过由返回的DataStreamReader接口(Scala / Java / Python文档),创建Streaming DataFrames SparkSession.readStream()。在R中,使用read.stream()方法。与用于创建静态DataFrame的读取接口类似,可以指定源的详细信息-数据格式,架构,选项等。

Input Sources

There are a few built-in sources.

Some sources are not fault-tolerant because they do not guarantee that data can be replayed using checkpointed offsets after a failure. See the earlier section on fault-tolerance semantics. Here are the details of all the sources in Spark.

一些源不是容错的,因为不能保证故障后可以使用检查点偏移来重放数据。参见前面有关 容错语义的部分。以下是Spark中所有来源的详细信息。

Source

Options

Fault-tolerant

Notes

File source

path: path to the input directory, and common to all file formats.
maxFilesPerTrigger: maximum number of new files to be considered in every trigger (default: no max)
latestFirst: whether to process the latest new files first, useful when there is a large backlog of files (default: false)
fileNameOnly: whether to check new files based on only the filename instead of on the full path (default: false). With this set to `true`, the following files would be considered as the same file, because their filenames, "dataset.txt", are the same:
"file:///dataset.txt"
"s3://a/dataset.txt"
"s3n://a/b/dataset.txt"
"s3a://a/b/c/dataset.txt"
maxFileAge: Maximum age of a file that can be found in this directory, before it is ignored. For the first batch all files will be considered valid. If latestFirst is set to `true` and maxFilesPerTrigger is set, then this parameter will be ignored, because old files that are valid, and should be processed, may be ignored. The max age is specified with respect to the timestamp of the latest file, and not the timestamp of the current system.(default: 1 week)
cleanSource: option to clean up completed files after processing.
Available options are "archive", "delete", "off". If the option is not provided, the default value is "off".
When "archive" is provided, additional option sourceArchiveDir must be provided as well. The value of "sourceArchiveDir" must not match with source pattern in depth (the number of directories from the root directory), where the depth is minimum of depth on both paths. This will ensure archived files are never included as new source files.
For example, suppose you provide '/hello?/spark/*' as source pattern, '/hello1/spark/archive/dir' cannot be used as the value of "sourceArchiveDir", as '/hello?/spark/*' and '/hello1/spark/archive' will be matched. '/hello1/spark' cannot be also used as the value of "sourceArchiveDir", as '/hello?/spark' and '/hello1/spark' will be matched. '/archived/here' would be OK as it doesn't match.
Spark will move source files respecting their own path. For example, if the path of source file is /a/b/dataset.txt and the path of archive directory is /archived/here, file will be moved to /archived/here/a/b/dataset.txt.
NOTE: Both archiving (via moving) or deleting completed files will introduce overhead (slow down, even if it's happening in separate thread) in each micro-batch, so you need to understand the cost for each operation in your file system before enabling this option. On the other hand, enabling this option will reduce the cost to list source files which can be an expensive operation.
Number of threads used in completed file cleaner can be configured withspark.sql.streaming.fileSource.cleaner.numThreads (default: 1).
NOTE 2: The source path should not be used from multiple sources or queries when enabling this option. Similarly, you must ensure the source path doesn't match to any files in output directory of file stream sink.
NOTE 3: Both delete and move actions are best effort. Failing to delete or move files will not fail the streaming query. Spark may not clean up some source files in some circumstances - e.g. the application doesn't shut down gracefully, too many files are queued to clean up.

For file-format-specific options, see the related methods in DataStreamReader (Scala/Java/Python/R). E.g. for "parquet" format options see DataStreamReader.parquet().

In addition, there are session configurations that affect certain file-formats. See the SQL Programming Guide for more details. E.g., for "parquet", see Parquet configuration section.

Yes

Supports glob paths, but does not support multiple comma-separated paths/globs.

Socket Source

host: host to connect to, must be specified
port: port to connect to, must be specified

No

 

Rate Source

rowsPerSecond (e.g. 100, default: 1): How many rows should be generated per second.

rampUpTime (e.g. 5s, default: 0s): How long to ramp up before the generating speed becomes rowsPerSecond. Using finer granularities than seconds will be truncated to integer seconds.

numPartitions (e.g. 10, default: Spark's default parallelism): The partition number for the generated rows.

The source will try its best to reach rowsPerSecond, but the query may be resource constrained, and numPartitions can be tweaked to help reach the desired speed.

Yes

 

Kafka Source

See the Kafka Integration Guide.

Yes

 
       

Here are some examples.

val spark: SparkSession = ...

 

// Read text from socket

val socketDF = spark

  .readStream

  .format("socket")

  .option("host", "localhost")

  .option("port", 9999)

  .load()

 

socketDF.isStreaming    // Returns True for DataFrames that have streaming sources

 

socketDF.printSchema

 

// Read all the csv files written atomically in a directory

val userSchema = new StructType().add("name", "string").add("age", "integer")

val csvDF = spark

  .readStream

  .option("sep", ";")

  .schema(userSchema)      // Specify schema of the csv files

  .csv("/path/to/directory")    // Equivalent to format("csv").load("/path/to/directory")

These examples generate streaming DataFrames that are untyped, meaning that the schema of the DataFrame is not checked at compile time, only checked at runtime when the query is submitted. Some operations like map, flatMap, etc. need the type to be known at compile time. To do those, you can convert these untyped streaming DataFrames to typed streaming Datasets using the same methods as static DataFrame. See the SQL Programming Guide for more details. Additionally, more details on the supported streaming sources are discussed later in the document.

这些示例生成未类型化的流式DataFrame,意味着在编译时不检查DataFrame的架构,仅在提交查询时在运行时检查。有些操作(如map,flatMap等)需要在编译时知道类型。可以使用与静态DataFrame相同的方法,将这些未类型化的流式数据帧转换为类型化的流式数据集。有关更多详细信息,请参见《SQL编程指南》。此外,本文档后面将讨论有关受支持的流媒体源的更多详细信息。

从Spark 3.1开始,还可以使用从表DataStreamReader.table()创建流式DataFrame 。有关更多详细信息,请参见流表API

Since Spark 3.1, you can also create streaming DataFrames from tables with DataStreamReader.table(). See Streaming Table APIs for more details.

Schema inference and partition of streaming DataFrames/Datasets

By default, Structured Streaming from file based sources requires you to specify the schema, rather than rely on Spark to infer it automatically. This restriction ensures a consistent schema will be used for the streaming query, even in the case of failures. For ad-hoc use cases, you can reenable schema inference by setting spark.sql.streaming.schemaInference to true.

Partition discovery does occur when subdirectories that are named /key=value/ are present and listing will automatically recurse into these directories. If these columns appear in the user-provided schema, they will be filled in by Spark based on the path of the file being read. The directories that make up the partitioning scheme must be present when the query starts and must remain static. For example, it is okay to add /data/year=2016/ when /data/year=2015/ was present, but it is invalid to change the partitioning column (i.e. by creating the directory /data/date=2016-04-17/).

默认情况下,从基于文件的源进行结构化流传输需要指定架构,而不是依靠Spark自动推断。此限制确保即使在发生故障的情况下,也可以将一致的架构用于流查询。对于临时用例,可以通过将设置spark.sql.streaming.schemaInference,重新启用模式推断true。

当存在命名的子目录时,分区发现确实会发生,/key=value/列表,将自动递归到这些目录中。如果这些列出现在用户提供的架构中,Spark将根据读取文件的路径来填充。启动查询时,必须存在组成分区方案的目录,并且这些目录必须保持静态。例如,添加/data/year=2016/时/data/year=2015/,但是无效的改变分区列(即通过创建目录/data/date=2016-04-17/)。

Operations on streaming DataFrames/Datasets

You can apply all kinds of operations on streaming DataFrames/Datasets – ranging from untyped, SQL-like operations (e.g. select, where, groupBy), to typed RDD-like operations (e.g. map, filter, flatMap). See the SQL programming guide for more details. Let’s take a look at a few example operations that you can use.

可以将各种操作上的流DataFrames /数据集-从无类型,类似于SQL的操作(例如selectwheregroupBy),键入RDD般的操作(例如mapfilterflatMap)。有关更多详细信息,请参见SQL编程指南。可以使用的一些示例操作。

Basic Operations - Selection, Projection, Aggregation

Most of the common operations on DataFrame/Dataset are supported for streaming. The few operations that are not supported are discussed later in this section.

流上支持DataFrame / Dataset上的大多数常见操作。稍后讨论不支持的一些操作。

 

case class DeviceData(device: String, deviceType: String, signal: Double, time: DateTime)

 

val df: DataFrame = ... // streaming DataFrame with IOT device data with schema { device: string, deviceType: string, signal: double, time: string }

val ds: Dataset[DeviceData] = df.as[DeviceData]    // streaming Dataset with IOT device data

 

// Select the devices which have signal more than 10

df.select("device").where("signal > 10")      // using untyped APIs  

ds.filter(_.signal > 10).map(_.device)         // using typed APIs

 

// Running count of the number of updates for each device type

df.groupBy("deviceType").count()                          // using untyped API

 

// Running average signal for each device type

import org.apache.spark.sql.expressions.scalalang.typed

ds.groupByKey(_.deviceType).agg(typed.avg(_.signal))    // using typed API

You can also register a streaming DataFrame/Dataset as a temporary view and then apply SQL commands on it.

df.createOrReplaceTempView("updates")

spark.sql("select count(*) from updates")  // returns another streaming DF

Note, you can identify whether a DataFrame/Dataset has streaming data or not by using df.isStreaming.

df.isStreaming

You may want to check the query plan of the query, as Spark could inject stateful operations during interpret of SQL statement against streaming dataset. Once stateful operations are injected in the query plan, you may need to check your query with considerations in stateful operations. (e.g. output mode, watermark, state store size maintenance, etc.)

可能要检查查询的查询计划,因为Spark可能在针对流数据集解释SQL语​​句期间注入状态操作。将有状态操作注入查询计划后,可能需要检查有状态操作中的注意事项。(例如,输出模式,水印,状态存储大小维护等)。

Window Operations on Event Time

Aggregations over a sliding event-time window are straightforward with Structured Streaming and are very similar to grouped aggregations. In a grouped aggregation, aggregate values (e.g. counts) are maintained for each unique value in the user-specified grouping column. In case of window-based aggregations, aggregate values are maintained for each window the event-time of a row falls into. Let’s understand this with an illustration.

Imagine our quick example is modified and the stream now contains lines along with the time when the line was generated. Instead of running word counts, we want to count words within 10 minute windows, updating every 5 minutes. That is, word counts in words received between 10 minute windows 12:00 - 12:10, 12:05 - 12:15, 12:10 - 12:20, etc. Note that 12:00 - 12:10 means data that arrived after 12:00 but before 12:10. Now, consider a word that was received at 12:07. This word should increment the counts corresponding to two windows 12:00 - 12:10 and 12:05 - 12:15. So the counts will be indexed by both, the grouping key (i.e. the word) and the window (can be calculated from the event-time).

The result tables would look something like the following.

滑动事件时间窗口上的聚合对于结构化流而言非常简单,并且与分组聚合非常相似。在分组聚合中,在用户指定的分组列中为每个唯一维护聚合值(例如,计数)。在基于窗口的聚合的情况下,将为行的事件时间所属的每个窗口维护聚合值。通过插图来了解这一点。

想象一下快速示例已被修改,并且流现在包含行以及生成行的时间。而不是运行字数统计,希望在10分钟的窗口内对字数进行计数,每5分钟更新一次。也就是说,在10分钟窗口12:00-12:10、12:05-12:15、12:10-12:20等之间接收到的单词中的单词计数。注意,12:00-12:10表示数据12:00之后但12:10之前到达。现在,考虑一个在12:07收到的单词。此字应增加对应于两个窗口12:00-12:10和12:05-12:15的计数。因此,计数将通过分组键(即单词)和窗口(可以从事件时间计算)来索引。

结果表如下所示。

 

 

 Since this windowing is similar to grouping, in code, you can use groupBy() and window() operations to express windowed aggregations. You can see the full code for the below examples in Scala/Java/Python.

由于此窗口化类似于分组,因此在代码中,可以使用groupBy()window()操作来表示窗口化聚合。可以在Scala / Java / Python中看到以下示例的完整代码 。

import spark.implicits._

 

val words = ... // streaming DataFrame of schema { timestamp: Timestamp, word: String }

 

// Group the data by window and word and compute the count of each group

val windowedCounts = words.groupBy(

  window($"timestamp", "10 minutes", "5 minutes"),

  $"word"

).count()

Handling Late Data and Watermarking

Now consider what happens if one of the events arrives late to the application. For example, say, a word generated at 12:04 (i.e. event time) could be received by the application at 12:11. The application should use the time 12:04 instead of 12:11 to update the older counts for the window 12:00 - 12:10. This occurs naturally in our window-based grouping – Structured Streaming can maintain the intermediate state for partial aggregates for a long period of time such that late data can update aggregates of old windows correctly, as illustrated below.

现在考虑如果事件之一迟到了应用程序会发生什么。例如,应用程序可以在12:11接收在12:04(即事件时间)生成的单词。应用程序应使用12:04而不是12:11来更新窗口的旧计数12:00 - 12:10。基于窗口的分组中很自然地发生-结构化流可以长时间保持部分聚合的中间状态,以便后期数据可以正确更新旧窗口的聚合,如下所示。

 

 

 However, to run this query for days, it’s necessary for the system to bound the amount of intermediate in-memory state it accumulates. This means the system needs to know when an old aggregate can be dropped from the in-memory state because the application is not going to receive late data for that aggregate any more. To enable this, in Spark 2.1, we have introduced watermarking, which lets the engine automatically track the current event time in the data and attempt to clean up old state accordingly. You can define the watermark of a query by specifying the event time column and the threshold on how late the data is expected to be in terms of event time. For a specific window ending at time T, the engine will maintain state and allow late data to update the state until (max event time seen by the engine - late threshold > T). In other words, late data within the threshold will be aggregated, but data later than the threshold will start getting dropped (see later in the section for the exact guarantees). Let’s understand this with an example. We can easily define watermarking on the previous example using withWatermark() as shown below.

但是,要连续几天运行此查询,系统必须限制其累积的中间内存状态量。系统需要知道何时可以从内存中状态删除旧的聚合,因为应用程序将不再接收该聚合的最新数据。为此,在Spark 2.1中,引入了 水印功能,该功能使引擎自动跟踪数据中的当前事件时间,并尝试相应地清除旧状态。可以通过指定事件时间列和有关数据,在事件时间方面的预期延迟时间的阈值,定义查询的水印。对于在时间结束的特定窗口T,引擎将维持状态并允许以后的数据更新状态,直到(max event time seen by the engine - late threshold > T)。换句话说,阈值内的延迟数据将被汇总,但阈值后的数据将开始被丢弃( 有关确切保证,请参阅本节后面的内容)。通过一个例子来理解这一点。可以使用withWatermark()以下示例在上一个示例中轻松定义水印。

import spark.implicits._

 

val words = ... // streaming DataFrame of schema { timestamp: Timestamp, word: String }

 

// Group the data by window and word and compute the count of each group

val windowedCounts = words

    .withWatermark("timestamp", "10 minutes")

    .groupBy(

        window($"timestamp", "10 minutes", "5 minutes"),

        $"word")

    .count()

In this example, we are defining the watermark of the query on the value of the column “timestamp”, and also defining “10 minutes” as the threshold of how late is the data allowed to be. If this query is run in Update output mode (discussed later in Output Modes section), the engine will keep updating counts of a window in the Result Table until the window is older than the watermark, which lags behind the current event time in column “timestamp” by 10 minutes. Here is an illustration.

在此示例中,将在“时间戳”列的值上定义查询的水印,并且还将“ 10分钟”定义为允许数据晚到的阈值。如果此查询在“更新输出”模式下运行(稍后在“输出模式”部分中讨论),则引擎将在“结果表”中保持窗口的更新计数,直到该窗口早于水印为止,该时间滞后于“列”中的当前事件时间。时间戳”的时间减少了10分钟。这是一个例子。

 

 

 As shown in the illustration, the maximum event time tracked by the engine is the blue dashed line, and the watermark set as (max event time - '10 mins') at the beginning of every trigger is the red line. For example, when the engine observes the data (12:14, dog), it sets the watermark for the next trigger as 12:04. This watermark lets the engine maintain intermediate state for additional 10 minutes to allow late data to be counted. For example, the data (12:09, cat) is out of order and late, and it falls in windows 12:00 - 12:10 and 12:05 - 12:15. Since, it is still ahead of the watermark 12:04 in the trigger, the engine still maintains the intermediate counts as state and correctly updates the counts of the related windows. However, when the watermark is updated to 12:11, the intermediate state for window (12:00 - 12:10) is cleared, and all subsequent data (e.g. (12:04, donkey)) is considered “too late” and therefore ignored. Note that after every trigger, the updated counts (i.e. purple rows) are written to sink as the trigger output, as dictated by the Update mode.

Some sinks (e.g. files) may not supported fine-grained updates that Update Mode requires. To work with them, we have also support Append Mode, where only the final counts are written to sink. This is illustrated below.

Note that using withWatermark on a non-streaming Dataset is no-op. As the watermark should not affect any batch query in any way, we will ignore it directly.

如图所示,引擎跟踪的最大事件时间是 蓝色虚线,(max event time - '10 mins') 在每次触发开始时设置的水印是红线。例如,当引擎观察到数据时 (12:14, dog),将下一个触发器的水印设置为12:04。此水印可让引擎再保持10分钟的中间状态,以便对较晚的数据进行计数。例如,数据(12:09, cat)不正确且延迟,并且落在windows12:00 - 12:10和中12:05 - 12:15。仍然12:04在触发器中的水印之前,因此引擎仍将中间计数保持为状态,并正确更新相关窗口的计数。当水印更新为12:11,(12:00 - 12:10),清除了窗口的中间状态,并且所有后续数据(例如(12:04, donkey))都被认为“为时已晚”,因此被忽略。注意,在每次触发之后,更新的计数(即紫色行)将被写入接收器,作为更新输出指示的触发输出。

某些接收器(例如文件)可能不支持更新模式所需的细粒度更新。支持追加模式,其中仅将最终计数写入接收器。如下所示。

withWatermark在非流数据集上使用是no-op。由于水印不应以任何方式影响任何批处理查询,将直接忽略它。

 

 

 Similar to the Update Mode earlier, the engine maintains intermediate counts for each window. However, the partial counts are not updated to the Result Table and not written to sink. The engine waits for “10 mins” for late date to be counted, then drops intermediate state of a window < watermark, and appends the final counts to the Result Table/sink. For example, the final counts of window 12:00 - 12:10 is appended to the Result Table only after the watermark is updated to 12:11.

Conditions for watermarking to clean aggregation state

It is important to note that the following conditions must be satisfied for the watermarking to clean the state in aggregation queries (as of Spark 2.1.1, subject to change in the future).

Semantic Guarantees of Aggregation with Watermarking

Join Operations

Structured Streaming supports joining a streaming Dataset/DataFrame with a static Dataset/DataFrame as well as another streaming Dataset/DataFrame. The result of the streaming join is generated incrementally, similar to the results of streaming aggregations in the previous section. In this section we will explore what type of joins (i.e. inner, outer, semi, etc.) are supported in the above cases. Note that in all the supported join types, the result of the join with a streaming Dataset/DataFrame will be the exactly the same as if it was with a static Dataset/DataFrame containing the same data in the stream.

Stream-static Joins

Since the introduction in Spark 2.0, Structured Streaming has supported joins (inner join and some type of outer joins) between a streaming and a static DataFrame/Dataset. Here is a simple example.

val staticDf = spark.read. ...

val streamingDf = spark.readStream. ...

 

streamingDf.join(staticDf, "type")          // inner equi-join with a static DF

streamingDf.join(staticDf, "type", "left_outer")  // left outer join with a static DF

Note that stream-static joins are not stateful, so no state management is necessary. However, a few types of stream-static outer joins are not yet supported. These are listed at the end of this Join section.

Stream-stream Joins

In Spark 2.3, we have added support for stream-stream joins, that is, you can join two streaming Datasets/DataFrames. The challenge of generating join results between two data streams is that, at any point of time, the view of the dataset is incomplete for both sides of the join making it much harder to find matches between inputs. Any row received from one input stream can match with any future, yet-to-be-received row from the other input stream. Hence, for both the input streams, we buffer past input as streaming state, so that we can match every future input with past input and accordingly generate joined results. Furthermore, similar to streaming aggregations, we automatically handle late, out-of-order data and can limit the state using watermarks. Let’s discuss the different types of supported stream-stream joins and how to use them.

Inner Joins with optional Watermarking

Inner joins on any kind of columns along with any kind of join conditions are supported. However, as the stream runs, the size of streaming state will keep growing indefinitely as all past input must be saved as any new input can match with any input from the past. To avoid unbounded state, you have to define additional join conditions such that indefinitely old inputs cannot match with future inputs and therefore can be cleared from the state. In other words, you will have to do the following additional steps in the join.

  1. Define watermark delays on both inputs such that the engine knows how delayed the input can be (similar to streaming aggregations)
  2. Define a constraint on event-time across the two inputs such that the engine can figure out when old rows of one input is not going to be required (i.e. will not satisfy the time constraint) for matches with the other input. This constraint can be defined in one of the two ways.
    1. Time range join conditions (e.g. ...JOIN ON leftTime BETWEEN rightTime AND rightTime + INTERVAL 1 HOUR),
    2. Join on event-time windows (e.g. ...JOIN ON leftTimeWindow = rightTimeWindow).

Let’s understand this with an example.

Let’s say we want to join a stream of advertisement impressions (when an ad was shown) with another stream of user clicks on advertisements to correlate when impressions led to monetizable clicks. To allow the state cleanup in this stream-stream join, you will have to specify the watermarking delays and the time constraints as follows.

  1. Watermark delays: Say, the impressions and the corresponding clicks can be late/out-of-order in event-time by at most 2 and 3 hours, respectively.
  2. Event-time range condition: Say, a click can occur within a time range of 0 seconds to 1 hour after the corresponding impression.

The code would look like this.

import org.apache.spark.sql.functions.expr

 

val impressions = spark.readStream. ...

val clicks = spark.readStream. ...

 

// Apply watermarks on event-time columns

val impressionsWithWatermark = impressions.withWatermark("impressionTime", "2 hours")

val clicksWithWatermark = clicks.withWatermark("clickTime", "3 hours")

 

// Join with event-time constraints

impressionsWithWatermark.join(

  clicksWithWatermark,

  expr("""

    clickAdId = impressionAdId AND

    clickTime >= impressionTime AND

    clickTime <= impressionTime + interval 1 hour

    """)

)

Semantic Guarantees of Stream-stream Inner Joins with Watermarking

This is similar to the guarantees provided by watermarking on aggregations. A watermark delay of “2 hours” guarantees that the engine will never drop any data that is less than 2 hours delayed. But data delayed by more than 2 hours may or may not get processed.

Outer Joins with Watermarking

While the watermark + event-time constraints is optional for inner joins, for outer joins they must be specified. This is because for generating the NULL results in outer join, the engine must know when an input row is not going to match with anything in future. Hence, the watermark + event-time constraints must be specified for generating correct results. Therefore, a query with outer-join will look quite like the ad-monetization example earlier, except that there will be an additional parameter specifying it to be an outer-join.

impressionsWithWatermark.join(

  clicksWithWatermark,

  expr("""

    clickAdId = impressionAdId AND

    clickTime >= impressionTime AND

    clickTime <= impressionTime + interval 1 hour

    """),

  joinType = "leftOuter"      // can be "inner", "leftOuter", "rightOuter", "fullOuter", "leftSemi"

 )

Semantic Guarantees of Stream-stream Outer Joins with Watermarking

Outer joins have the same guarantees as inner joins regarding watermark delays and whether data will be dropped or not.

Caveats

There are a few important characteristics to note regarding how the outer results are generated.

Semi Joins with Watermarking

A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join. Similar to outer joins, watermark + event-time constraints must be specified for semi join. This is to evict unmatched input rows on left side, the engine must know when an input row on left side is not going to match with anything on right side in future.

Semantic Guarantees of Stream-stream Semi Joins with Watermarking

Semi joins have the same guarantees as inner joins regarding watermark delays and whether data will be dropped or not.

Support matrix for joins in streaming queries

Left Input

Right Input

Join Type

 

Static

Static

All types

Supported, since its not on streaming data even though it can be present in a streaming query

Stream

Static

Inner

Supported, not stateful

Left Outer

Supported, not stateful

Right Outer

Not supported

Full Outer

Not supported

Left Semi

Supported, not stateful

Static

Stream

Inner

Supported, not stateful

Left Outer

Not supported

Right Outer

Supported, not stateful

Full Outer

Not supported

Left Semi

Not supported

Stream

Stream

Inner

Supported, optionally specify watermark on both sides + time constraints for state cleanup

Left Outer

Conditionally supported, must specify watermark on right + time constraints for correct results, optionally specify watermark on left for all state cleanup

Right Outer

Conditionally supported, must specify watermark on left + time constraints for correct results, optionally specify watermark on right for all state cleanup

Full Outer

Conditionally supported, must specify watermark on one side + time constraints for correct results, optionally specify watermark on the other side for all state cleanup

Left Semi

Conditionally supported, must specify watermark on right + time constraints for correct results, optionally specify watermark on left for all state cleanup

       

Additional details on supported joins:

Streaming Deduplication

You can deduplicate records in data streams using a unique identifier in the events. This is exactly same as deduplication on static using a unique identifier column. The query will store the necessary amount of data from previous records such that it can filter duplicate records. Similar to aggregations, you can use deduplication with or without watermarking.

 

val streamingDf = spark.readStream. ...  // columns: guid, eventTime, ...

 

// Without watermark using guid column

streamingDf.dropDuplicates("guid")

 

// With watermark using guid and eventTime columns

streamingDf

  .withWatermark("eventTime", "10 seconds")

  .dropDuplicates("guid", "eventTime")

Policy for handling multiple watermarks

A streaming query can have multiple input streams that are unioned or joined together. Each of the input streams can have a different threshold of late data that needs to be tolerated for stateful operations. You specify these thresholds using withWatermarks("eventTime", delay) on each of the input streams. For example, consider a query with stream-stream joins between inputStream1 and inputStream2.

inputStream1.withWatermark("eventTime1", "1 hour")

  .join(

    inputStream2.withWatermark("eventTime2", "2 hours"),

    joinCondition)

While executing the query, Structured Streaming individually tracks the maximum event time seen in each input stream, calculates watermarks based on the corresponding delay, and chooses a single global watermark with them to be used for stateful operations. By default, the minimum is chosen as the global watermark because it ensures that no data is accidentally dropped as too late if one of the streams falls behind the others (for example, one of the streams stops receiving data due to upstream failures). In other words, the global watermark will safely move at the pace of the slowest stream and the query output will be delayed accordingly.

However, in some cases, you may want to get faster results even if it means dropping data from the slowest stream. Since Spark 2.4, you can set the multiple watermark policy to choose the maximum value as the global watermark by setting the SQL configuration spark.sql.streaming.multipleWatermarkPolicy to max (default is min). This lets the global watermark move at the pace of the fastest stream. However, as a side effect, data from the slower streams will be aggressively dropped. Hence, use this configuration judiciously.

Arbitrary Stateful Operations

Many usecases require more advanced stateful operations than aggregations. For example, in many usecases, you have to track sessions from data streams of events. For doing such sessionization, you will have to save arbitrary types of data as state, and perform arbitrary operations on the state using the data stream events in every trigger. Since Spark 2.2, this can be done using the operation mapGroupsWithState and the more powerful operation flatMapGroupsWithState. Both operations allow you to apply user-defined code on grouped Datasets to update user-defined state. For more concrete details, take a look at the API documentation (Scala/Java) and the examples (Scala/Java).

Though Spark cannot check and force it, the state function should be implemented with respect to the semantics of the output mode. For example, in Update mode Spark doesn’t expect that the state function will emit rows which are older than current watermark plus allowed late record delay, whereas in Append mode the state function can emit these rows.

Unsupported Operations

There are a few DataFrame/Dataset operations that are not supported with streaming DataFrames/Datasets. Some of them are as follows.

In addition, there are some Dataset methods that will not work on streaming Datasets. They are actions that will immediately run queries and return results, which does not make sense on a streaming Dataset. Rather, those functionalities can be done by explicitly starting a streaming query (see the next section regarding that).

If you try any of these operations, you will see an AnalysisException like “operation XYZ is not supported with streaming DataFrames/Datasets”. While some of them may be supported in future releases of Spark, there are others which are fundamentally hard to implement on streaming data efficiently. For example, sorting on the input stream is not supported, as it requires keeping track of all the data received in the stream. This is therefore fundamentally hard to execute efficiently.

Limitation of global watermark

In Append mode, if a stateful operation emits rows older than current watermark plus allowed late record delay, they will be “late rows” in downstream stateful operations (as Spark uses global watermark). Note that these rows may be discarded. This is a limitation of a global watermark, and it could potentially cause a correctness issue.

Spark will check the logical plan of query and log a warning when Spark detects such a pattern.

Any of the stateful operation(s) after any of below stateful operations can have this issue:

As Spark cannot check the state function of mapGroupsWithState/flatMapGroupsWithState, Spark assumes that the state function emits late rows if the operator uses Append mode.

Spark provides two ways to check the number of late rows on stateful operators which would help you identify the issue:

  1. On Spark UI: check the metrics in stateful operator nodes in query execution details page in SQL tab
  2. On Streaming Query Listener: check “numRowsDroppedByWatermark” in “stateOperators” in QueryProcessEvent.

Please note that “numRowsDroppedByWatermark” represents the number of “dropped” rows by watermark, which is not always same as the count of “late input rows” for the operator. It depends on the implementation of the operator - e.g. streaming aggregation does pre-aggregate input rows and checks the late inputs against pre-aggregated inputs, hence the number is not same as the number of original input rows. You’d like to just check the fact whether the value is zero or non-zero.

There’s a known workaround: split your streaming query into multiple queries per stateful operator, and ensure end-to-end exactly once per query. Ensuring end-to-end exactly once for the last query is optional.

Starting Streaming Queries

Once you have defined the final result DataFrame/Dataset, all that is left is for you to start the streaming computation. To do that, you have to use the DataStreamWriter (Scala/Java/Python docs) returned through Dataset.writeStream(). You will have to specify one or more of the following in this interface.

Output Modes

There are a few types of output modes.

Different types of streaming queries support different output modes. Here is the compatibility matrix.

Query Type

 

Supported Output Modes

Notes

Queries with aggregation

Aggregation on event-time with watermark

Append, Update, Complete

Append mode uses watermark to drop old aggregation state. But the output of a windowed aggregation is delayed the late threshold specified in withWatermark() as by the modes semantics, rows can be added to the Result Table only once after they are finalized (i.e. after watermark is crossed). See the Late Data section for more details.

Update mode uses watermark to drop old aggregation state.

Complete mode does not drop old aggregation state since by definition this mode preserves all data in the Result Table.

Other aggregations

Complete, Update

Since no watermark is defined (only defined in other category), old aggregation state is not dropped.

Append mode is not supported as aggregates can update thus violating the semantics of this mode.

Queries with mapGroupsWithState

Update

Aggregations not allowed in a query with mapGroupsWithState.

Queries with flatMapGroupsWithState

Append operation mode

Append

Aggregations are allowed after flatMapGroupsWithState.

Update operation mode

Update

Aggregations not allowed in a query with flatMapGroupsWithState.

Queries with joins

Append

Update and Complete mode not supported yet. See the support matrix in the Join Operations section for more details on what types of joins are supported.

Other queries

Append, Update

Complete mode not supported as it is infeasible to keep all unaggregated data in the Result Table.

       

Output Sinks

There are a few types of built-in output sinks.

writeStream

    .format("parquet")        // can be "orc", "json", "csv", etc.

    .option("path", "path/to/destination/dir")

    .start()

writeStream

    .format("kafka")

    .option("kafka.bootstrap.servers", "host1:port1,host2:port2")

    .option("topic", "updates")

    .start()

writeStream

    .foreach(...)

    .start()

writeStream

    .format("console")

    .start()

writeStream

    .format("memory")

    .queryName("tableName")

    .start()

Some sinks are not fault-tolerant because they do not guarantee persistence of the output and are meant for debugging purposes only. See the earlier section on fault-tolerance semantics. Here are the details of all the sinks in Spark.

Sink

Supported Output Modes

Options

Fault-tolerant

Notes

File Sink

Append

path: path to the output directory, must be specified.
retention: time to live (TTL) for output files. Output files which batches were committed older than TTL will be eventually excluded in metadata log. This means reader queries which read the sink's output directory may not process them. You can provide the value as string format of the time. (like "12h", "7d", etc.) By default it's disabled.

For file-format-specific options, see the related methods in DataFrameWriter (Scala/Java/Python/R). E.g. for "parquet" format options see DataFrameWriter.parquet()

Yes (exactly-once)

Supports writes to partitioned tables. Partitioning by time may be useful.

Kafka Sink

Append, Update, Complete

See the Kafka Integration Guide

Yes (at-least-once)

More details in the Kafka Integration Guide

Foreach Sink

Append, Update, Complete

None

Yes (at-least-once)

More details in the next section

ForeachBatch Sink

Append, Update, Complete

None

Depends on the implementation

More details in the next section

Console Sink

Append, Update, Complete

numRows: Number of rows to print every trigger (default: 20)
truncate: Whether to truncate the output if too long (default: true)

No

 

Memory Sink

Append, Complete

None

No. But in Complete Mode, restarted query will recreate the full table.

Table name is the query name.

         

Note that you have to call start() to actually start the execution of the query. This returns a StreamingQuery object which is a handle to the continuously running execution. You can use this object to manage the query, which we will discuss in the next subsection. For now, let’s understand all this with a few examples.

// ========== DF with no aggregations ==========

val noAggDF = deviceDataDf.select("device").where("signal > 10")  

 

// Print new data to console

noAggDF

  .writeStream

  .format("console")

  .start()

 

// Write new data to Parquet files

noAggDF

  .writeStream

  .format("parquet")

  .option("checkpointLocation", "path/to/checkpoint/dir")

  .option("path", "path/to/destination/dir")

  .start()

 

// ========== DF with aggregation ==========

val aggDF = df.groupBy("device").count()

 

// Print updated aggregations to console

aggDF

  .writeStream

  .outputMode("complete")

  .format("console")

  .start()

 

// Have all the aggregates in an in-memory table

aggDF

  .writeStream

  .queryName("aggregates")    // this query name will be the table name

  .outputMode("complete")

  .format("memory")

  .start()

 

spark.sql("select * from aggregates").show()   // interactively query in-memory table

Using Foreach and ForeachBatch

The foreach and foreachBatch operations allow you to apply arbitrary operations and writing logic on the output of a streaming query. They have slightly different use cases - while foreach allows custom write logic on every row, foreachBatch allows arbitrary operations and custom logic on the output of each micro-batch. Let’s understand their usages in more detail.

ForeachBatch

foreachBatch(...) allows you to specify a function that is executed on the output data of every micro-batch of a streaming query. Since Spark 2.4, this is supported in Scala, Java and Python. It takes two parameters: a DataFrame or Dataset that has the output data of a micro-batch and the unique ID of the micro-batch.

streamingDF.writeStream.foreachBatch { (batchDF: DataFrame, batchId: Long) =>

  // Transform and write batchDF

}.start()

With foreachBatch, you can do the following.

 

streamingDF.writeStream.foreachBatch { (batchDF: DataFrame, batchId: Long) =>

  batchDF.persist()

  batchDF.write.format(...).save(...)  // location 1

  batchDF.write.format(...).save(...)  // location 2

  batchDF.unpersist()

}

Note:

Foreach

If foreachBatch is not an option (for example, corresponding batch data writer does not exist, or continuous processing mode), then you can express your custom writer logic using foreach. Specifically, you can express the data writing logic by dividing it into three methods: open, process, and close. Since Spark 2.4, foreach is available in Scala, Java and Python.

In Scala, you have to extend the class ForeachWriter (docs).

streamingDatasetOfString.writeStream.foreach(

  new ForeachWriter[String] {

 

    def open(partitionId: Long, version: Long): Boolean = {

      // Open connection

    }

 

    def process(record: String): Unit = {

      // Write string to connection

    }

 

    def close(errorOrNull: Throwable): Unit = {

      // Close the connection

    }

  }

).start()

Execution semantics When the streaming query is started, Spark calls the function or the object’s methods in the following way:

Streaming Table APIs

Since Spark 3.1, you can also use DataStreamReader.table() to read tables as streaming DataFrames and use DataStreamWriter.toTable() to write streaming DataFrames as tables:

val spark: SparkSession = ...

 

// Create a streaming DataFrame

val df = spark.readStream

  .format("rate")

  .option("rowsPerSecond", 10)

  .load()

 

// Write the streaming DataFrame to a table

df.writeStream

  .option("checkpointLocation", "path/to/checkpoint/dir")

  .toTable("myTable")

 

// Check the table result

spark.read.table("myTable").show()

 

// Transform the source dataset and write to a new table

spark.readStream

  .table("myTable")

  .select("value")

  .writeStream

  .option("checkpointLocation", "path/to/checkpoint/dir")

  .format("parquet")

  .toTable("newTable")

 

// Check the new table result

spark.read.table("newTable").show()

For more details, please check the docs for DataStreamReader (Scala/Java/Python docs) and DataStreamWriter (Scala/Java/Python docs).

Triggers

The trigger settings of a streaming query define the timing of streaming data processing, whether the query is going to be executed as micro-batch query with a fixed batch interval or as a continuous processing query. Here are the different kinds of triggers that are supported.

Trigger Type

Description

unspecified (default)

If no trigger setting is explicitly specified, then by default, the query will be executed in micro-batch mode, where micro-batches will be generated as soon as the previous micro-batch has completed processing.

Fixed interval micro-batches

The query will be executed with micro-batches mode, where micro-batches will be kicked off at the user-specified intervals.

  • If the previous micro-batch completes within the interval, then the engine will wait until the interval is over before kicking off the next micro-batch.
  • If the previous micro-batch takes longer than the interval to complete (i.e. if an interval boundary is missed), then the next micro-batch will start as soon as the previous one completes (i.e., it will not wait for the next interval boundary).
  • If no new data is available, then no micro-batch will be kicked off.

One-time micro-batch

The query will execute only one micro-batch to process all the available data and then stop on its own. This is useful in scenarios you want to periodically spin up a cluster, process everything that is available since the last period, and then shutdown the cluster. In some case, this may lead to significant cost savings.

Continuous with fixed checkpoint interval
(experimental)

The query will be executed in the new low-latency, continuous processing mode. Read more about this in the Continuous Processing section below.

Here are a few code examples.

import org.apache.spark.sql.streaming.Trigger

 

// Default trigger (runs micro-batch as soon as it can)

df.writeStream

  .format("console")

  .start()

 

// ProcessingTime trigger with two-seconds micro-batch interval

df.writeStream

  .format("console")

  .trigger(Trigger.ProcessingTime("2 seconds"))

  .start()

 

// One-time trigger

df.writeStream

  .format("console")

  .trigger(Trigger.Once())

  .start()

 

// Continuous trigger with one-second checkpointing interval

df.writeStream

  .format("console")

  .trigger(Trigger.Continuous("1 second"))

  .start()

Managing Streaming Queries

The StreamingQuery object created when a query is started can be used to monitor and manage the query.

val query = df.writeStream.format("console").start()   // get the query object

 

query.id          // get the unique identifier of the running query that persists across restarts from checkpoint data

 

query.runId       // get the unique id of this run of the query, which will be generated at every start/restart

 

query.name        // get the name of the auto-generated or user-specified name

 

query.explain()   // print detailed explanations of the query

 

query.stop()      // stop the query

 

query.awaitTermination()   // block until query is terminated, with stop() or with error

 

query.exception       // the exception if the query has been terminated with error

 

query.recentProgress  // an array of the most recent progress updates for this query

 

query.lastProgress    // the most recent progress update of this streaming query

You can start any number of queries in a single SparkSession. They will all be running concurrently sharing the cluster resources. You can use sparkSession.streams() to get the StreamingQueryManager (Scala/Java/Python docs) that can be used to manage the currently active queries.

val spark: SparkSession = ...

 

spark.streams.active    // get the list of currently active streaming queries

 

spark.streams.get(id)   // get a query object by its unique id

 

spark.streams.awaitAnyTermination()   // block until any one of them terminates

Monitoring Streaming Queries

There are multiple ways to monitor active streaming queries. You can either push metrics to external systems using Spark’s Dropwizard Metrics support, or access them programmatically.

Reading Metrics Interactively

You can directly get the current status and metrics of an active query using streamingQuery.lastProgress() and streamingQuery.status(). lastProgress() returns a StreamingQueryProgress object in Scala and Java and a dictionary with the same fields in Python. It has all the information about the progress made in the last trigger of the stream - what data was processed, what were the processing rates, latencies, etc. There is also streamingQuery.recentProgress which returns an array of last few progresses.

In addition, streamingQuery.status() returns a StreamingQueryStatus object in Scala and Java and a dictionary with the same fields in Python. It gives information about what the query is immediately doing - is a trigger active, is data being processed, etc.

Here are a few examples.

val query: StreamingQuery = ...

 

println(query.lastProgress)

 

/* Will print something like the following.

 

{

  "id" : "ce011fdc-8762-4dcb-84eb-a77333e28109",

  "runId" : "88e2ff94-ede0-45a8-b687-6316fbef529a",

  "name" : "MyQuery",

  "timestamp" : "2016-12-14T18:45:24.873Z",

  "numInputRows" : 10,

  "inputRowsPerSecond" : 120.0,

  "processedRowsPerSecond" : 200.0,

  "durationMs" : {

    "triggerExecution" : 3,

    "getOffset" : 2

  },

  "eventTime" : {

    "watermark" : "2016-12-14T18:45:24.873Z"

  },

  "stateOperators" : [ ],

  "sources" : [ {

    "description" : "KafkaSource[Subscribe[topic-0]]",

    "startOffset" : {

      "topic-0" : {

        "2" : 0,

        "4" : 1,

        "1" : 1,

        "3" : 1,

        "0" : 1

      }

    },

    "endOffset" : {

      "topic-0" : {

        "2" : 0,

        "4" : 115,

        "1" : 134,

        "3" : 21,

        "0" : 534

      }

    },

    "numInputRows" : 10,

    "inputRowsPerSecond" : 120.0,

    "processedRowsPerSecond" : 200.0

  } ],

  "sink" : {

    "description" : "MemorySink"

  }

}

*/

 

 

println(query.status)

 

/*  Will print something like the following.

{

  "message" : "Waiting for data to arrive",

  "isDataAvailable" : false,

  "isTriggerActive" : false

}

*/

Reporting Metrics programmatically using Asynchronous APIs

You can also asynchronously monitor all queries associated with a SparkSession by attaching a StreamingQueryListener (Scala/Java docs). Once you attach your custom StreamingQueryListener object with sparkSession.streams.attachListener(), you will get callbacks when a query is started and stopped and when there is progress made in an active query. Here is an example,

val spark: SparkSession = ...

 

spark.streams.addListener(new StreamingQueryListener() {

    override def onQueryStarted(queryStarted: QueryStartedEvent): Unit = {

        println("Query started: " + queryStarted.id)

    }

    override def onQueryTerminated(queryTerminated: QueryTerminatedEvent): Unit = {

        println("Query terminated: " + queryTerminated.id)

    }

    override def onQueryProgress(queryProgress: QueryProgressEvent): Unit = {

        println("Query made progress: " + queryProgress.progress)

    }

})

Reporting Metrics using Dropwizard

Spark supports reporting metrics using the Dropwizard Library. To enable metrics of Structured Streaming queries to be reported as well, you have to explicitly enable the configuration spark.sql.streaming.metricsEnabled in the SparkSession.

spark.conf.set("spark.sql.streaming.metricsEnabled", "true")

// or

spark.sql("SET spark.sql.streaming.metricsEnabled=true")

All queries started in the SparkSession after this configuration has been enabled will report metrics through Dropwizard to whatever sinks have been configured (e.g. Ganglia, Graphite, JMX, etc.).

Recovering from Failures with Checkpointing

In case of a failure or intentional shutdown, you can recover the previous progress and state of a previous query, and continue where it left off. This is done using checkpointing and write-ahead logs. You can configure a query with a checkpoint location, and the query will save all the progress information (i.e. range of offsets processed in each trigger) and the running aggregates (e.g. word counts in the quick example) to the checkpoint location. This checkpoint location has to be a path in an HDFS compatible file system, and can be set as an option in the DataStreamWriter when starting a query.

aggDF

  .writeStream

  .outputMode("complete")

  .option("checkpointLocation", "path/to/HDFS/dir")

  .format("memory")

  .start()

Recovery Semantics after Changes in a Streaming Query

There are limitations on what changes in a streaming query are allowed between restarts from the same checkpoint location. Here are a few kinds of changes that are either not allowed, or the effect of the change is not well-defined. For all of them:

Types of changes

Continuous Processing

[Experimental]

Continuous processing is a new, experimental streaming execution mode introduced in Spark 2.3 that enables low (~1 ms) end-to-end latency with at-least-once fault-tolerance guarantees. Compare this with the default micro-batch processing engine which can achieve exactly-once guarantees but achieve latencies of ~100ms at best. For some types of queries (discussed below), you can choose which mode to execute them in without modifying the application logic (i.e. without changing the DataFrame/Dataset operations).

To run a supported query in continuous processing mode, all you need to do is specify a continuous trigger with the desired checkpoint interval as a parameter. For example,

import org.apache.spark.sql.streaming.Trigger

 

spark

  .readStream

  .format("kafka")

  .option("kafka.bootstrap.servers", "host1:port1,host2:port2")

  .option("subscribe", "topic1")

  .load()

  .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")

  .writeStream

  .format("kafka")

  .option("kafka.bootstrap.servers", "host1:port1,host2:port2")

  .option("topic", "topic1")

  .trigger(Trigger.Continuous("1 second"))  // only change in query

  .start()

A checkpoint interval of 1 second means that the continuous processing engine will record the progress of the query every second. The resulting checkpoints are in a format compatible with the micro-batch engine, hence any query can be restarted with any trigger. For example, a supported query started with the micro-batch mode can be restarted in continuous mode, and vice versa. Note that any time you switch to continuous mode, you will get at-least-once fault-tolerance guarantees.

Supported Queries

As of Spark 2.4, only the following type of queries are supported in the continuous processing mode.

See Input Sources and Output Sinks sections for more details on them. While the console sink is good for testing, the end-to-end low-latency processing can be best observed with Kafka as the source and sink, as this allows the engine to process the data and make the results available in the output topic within milliseconds of the input data being available in the input topic.

Caveats

Additional Information

Notes

Further Reading

Talks

 

标签:Streaming,Structured,Programming,will,streaming,time,query,Spark,data
来源: https://www.cnblogs.com/wujianming-110117/p/14609000.html