Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Licensed to the Apache Software Foundation (ASF) under one or more
0003  * contributor license agreements.  See the NOTICE file distributed with
0004  * this work for additional information regarding copyright ownership.
0005  * The ASF licenses this file to You under the Apache License, Version 2.0
0006  * (the "License"); you may not use this file except in compliance with
0007  * the License.  You may obtain a copy of the License at
0008  *
0009  *    http://www.apache.org/licenses/LICENSE-2.0
0010  *
0011  * Unless required by applicable law or agreed to in writing, software
0012  * distributed under the License is distributed on an "AS IS" BASIS,
0013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014  * See the License for the specific language governing permissions and
0015  * limitations under the License.
0016  */
0017 package org.apache.spark.examples.sql.streaming;
0018 
0019 import org.apache.spark.api.java.function.FlatMapFunction;
0020 import org.apache.spark.sql.*;
0021 import org.apache.spark.sql.streaming.StreamingQuery;
0022 import scala.Tuple2;
0023 
0024 import java.sql.Timestamp;
0025 import java.util.ArrayList;
0026 import java.util.List;
0027 
0028 /**
0029  * Counts words in UTF8 encoded, '\n' delimited text received from the network over a
0030  * sliding window of configurable duration. Each line from the network is tagged
0031  * with a timestamp that is used to determine the windows into which it falls.
0032  *
0033  * Usage: JavaStructuredNetworkWordCountWindowed <hostname> <port> <window duration>
0034  *   [<slide duration>]
0035  * <hostname> and <port> describe the TCP server that Structured Streaming
0036  * would connect to receive data.
0037  * <window duration> gives the size of window, specified as integer number of seconds
0038  * <slide duration> gives the amount of time successive windows are offset from one another,
0039  * given in the same units as above. <slide duration> should be less than or equal to
0040  * <window duration>. If the two are equal, successive windows have no overlap. If
0041  * <slide duration> is not provided, it defaults to <window duration>.
0042  *
0043  * To run this on your local machine, you need to first run a Netcat server
0044  *    `$ nc -lk 9999`
0045  * and then run the example
0046  *    `$ bin/run-example sql.streaming.JavaStructuredNetworkWordCountWindowed
0047  *    localhost 9999 <window duration in seconds> [<slide duration in seconds>]`
0048  *
0049  * One recommended <window duration>, <slide duration> pair is 10, 5
0050  */
0051 public final class JavaStructuredNetworkWordCountWindowed {
0052 
0053   public static void main(String[] args) throws Exception {
0054     if (args.length < 3) {
0055       System.err.println("Usage: JavaStructuredNetworkWordCountWindowed <hostname> <port>" +
0056         " <window duration in seconds> [<slide duration in seconds>]");
0057       System.exit(1);
0058     }
0059 
0060     String host = args[0];
0061     int port = Integer.parseInt(args[1]);
0062     int windowSize = Integer.parseInt(args[2]);
0063     int slideSize = (args.length == 3) ? windowSize : Integer.parseInt(args[3]);
0064     if (slideSize > windowSize) {
0065       System.err.println("<slide duration> must be less than or equal to <window duration>");
0066     }
0067     String windowDuration = windowSize + " seconds";
0068     String slideDuration = slideSize + " seconds";
0069 
0070     SparkSession spark = SparkSession
0071       .builder()
0072       .appName("JavaStructuredNetworkWordCountWindowed")
0073       .getOrCreate();
0074 
0075     // Create DataFrame representing the stream of input lines from connection to host:port
0076     Dataset<Row> lines = spark
0077       .readStream()
0078       .format("socket")
0079       .option("host", host)
0080       .option("port", port)
0081       .option("includeTimestamp", true)
0082       .load();
0083 
0084     // Split the lines into words, retaining timestamps
0085     Dataset<Row> words = lines
0086       .as(Encoders.tuple(Encoders.STRING(), Encoders.TIMESTAMP()))
0087       .flatMap((FlatMapFunction<Tuple2<String, Timestamp>, Tuple2<String, Timestamp>>) t -> {
0088           List<Tuple2<String, Timestamp>> result = new ArrayList<>();
0089           for (String word : t._1.split(" ")) {
0090             result.add(new Tuple2<>(word, t._2));
0091           }
0092           return result.iterator();
0093         },
0094         Encoders.tuple(Encoders.STRING(), Encoders.TIMESTAMP())
0095       ).toDF("word", "timestamp");
0096 
0097     // Group the data by window and word and compute the count of each group
0098     Dataset<Row> windowedCounts = words.groupBy(
0099       functions.window(words.col("timestamp"), windowDuration, slideDuration),
0100       words.col("word")
0101     ).count().orderBy("window");
0102 
0103     // Start running the query that prints the windowed word counts to the console
0104     StreamingQuery query = windowedCounts.writeStream()
0105       .outputMode("complete")
0106       .format("console")
0107       .option("truncate", "false")
0108       .start();
0109 
0110     query.awaitTermination();
0111   }
0112 }