[
  {
    "path": ".gitignore",
    "content": ".idea/*\ntarget/*\nspark-warehouse/*\ncheckpoint/*\nproject/*\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2018 Paul Leclercq\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Kafka / Cassandra / Elastic with Spark Structured Streaming\n\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/214d5a4420ef471cba15ca3c59c15de0)](https://app.codacy.com/app/paleclercq/Spark-Structured-Streaming-Examples?utm_source=github.com&utm_medium=referral&utm_content=polomarcus/Spark-Structured-Streaming-Examples&utm_campaign=Badge_Grade_Dashboard)\n\nStream the number of time **Drake is broadcasted** on each radio.\nAnd also, see how easy is Spark Structured Streaming to use using Spark SQL's Dataframe API\n\n## Run the Project\n### Step 1 - Start containers\nStart the ZooKeeper, Kafka, Cassandra containers in detached mode (-d)\n```\n./start-docker-compose.sh\n```\nIt will run these 2 commands together so you don't have to\n```\ndocker-compose up -d\n```\n\n```\n# create Cassandra schema\ndocker-compose exec cassandra cqlsh -f /schema.cql;\n\n# confirm schema\ndocker-compose exec cassandra cqlsh -e \"DESCRIBE SCHEMA;\"\n```\n\n### Step 2 - start spark structured streaming\n```\nsbt run\n```\n\n### Run the project after another time\nAs checkpointing enables us to process our data exactly once, we need to delete the checkpointing folders to re run our examples.\n```\nrm -rf checkpoint/\nsbt run\n```\n\n## Monitor\n* Spark : http://localhost:4040/SQL/\n* Kibana (index \"test\") : http://localhost:5601/app/kibana#/discover\n* Kafka : Read all messages sent\n```\ndocker-compose exec kafka  \\\n kafka-console-consumer --bootstrap-server localhost:9092 --topic test --from-beginning\n```\n\nExamples:\n```\n{\"radio\":\"nova\",\"artist\":\"Drake\",\"title\":\"From Time\",\"count\":18}\n{\"radio\":\"nova\",\"artist\":\"Drake\",\"title\":\"4pm In Calabasas\",\"count\":1}\n```\n## Requirements\n* SBT\n* [docker compose](https://github.com/docker/compose/releases/tag/1.17.1)\n\n### Linux\n```\ncurl -L https://github.com/docker/compose/releases/download/1.17.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose\nchmod +x /usr/local/bin/docker-compose\n```\n### MacOS\n```\nbrew install docker-compose\n```\n\n## Input data\nComing from radio stations stored inside a parquet file, the stream is emulated with ` .option(\"maxFilesPerTrigger\", 1)` option.\n\nThe stream is after read to be sink into Kafka.\nThen, Kafka to Cassandra\n\n## Output data \nStored inside Kafka and Cassandra for example only.\nCassandra's Sinks uses the [ForeachWriter](https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.ForeachWriter) and also the [StreamSinkProvider](https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.sources.StreamSinkProvider) to compare both sinks.\n\nOne is using the **Datastax's Cassandra saveToCassandra** method. The other another method, messier (untyped), that uses CQL on a custom foreach loop.\n\nFrom Spark's doc about batch duration:\n> Trigger interval: Optionally, specify the trigger interval. If it is not specified, the system will check for availability of new data as soon as the previous processing has completed. If a trigger time is missed because the previous processing has not completed, then the system will attempt to trigger at the next trigger point, not immediately after the processing has completed.\n\n### Kafka topic\nOne topic `test` with only one partition\n\n#### List all topics\n```\ndocker-compose exec kafka  \\\n  kafka-topics --list --zookeeper zookeeper:32181\n```\n\n\n#### Send a message to be processed\n```\ndocker-compose exec kafka  \\\n kafka-console-producer --broker-list localhost:9092 --topic test\n\n> {\"radio\":\"skyrock\",\"artist\":\"Drake\",\"title\":\"Hold On We’Re Going Home\",\"count\":38}\n```\n\n### Cassandra Table\nThere are 3 tables. 2 used as sinks, and another to save kafka metadata.\nHave a look to [schema.cql](https://github.com/polomarcus/Spark-Structured-Streaming-Examples/blob/e9afaf6691c860ffb4da64e311c6cec4cdee8968/src/conf/cassandra/schema.cql) for all the details.\n\n```\n docker-compose exec cassandra cqlsh -e \"SELECT * FROM structuredstreaming.radioOtherSink;\"\n\n radio   | title                    | artist | count\n---------+--------------------------+--------+-------\n skyrock |                Controlla |  Drake |     1\n skyrock |                Fake Love |  Drake |     9\n skyrock | Hold On We’Re Going Home |  Drake |    35\n skyrock |            Hotline Bling |  Drake |  1052\n skyrock |  Started From The Bottom |  Drake |    39\n    nova |         4pm In Calabasas |  Drake |     1\n    nova |             Feel No Ways |  Drake |     2\n    nova |                From Time |  Drake |    34\n    nova |                     Hype |  Drake |     2\n\n```\n\n### Kafka Metadata\n@TODO Verify this below information. Cf this [SO comment](https://stackoverflow.com/questions/46153105/how-to-get-kafka-offsets-for-structured-query-for-manual-and-reliable-offset-man/46174353?noredirect=1#comment79536515_46174353)\n\nWhen doing an application upgrade, we cannot use [checkpointing](https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#recovering-from-failures-with-checkpointing), so we need to store our offset into a external datasource, here Cassandra is chosen.\nThen, when starting our kafka source we need to use the option \"StartingOffsets\" with a json string like \n```\n\"\"\" {\"topicA\":{\"0\":23,\"1\":-1},\"topicB\":{\"0\":-2}} \"\"\"\n```\nLearn more [in the official Spark's doc for Kafka](https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html#creating-a-kafka-source-for-batch-queries).\n\nIn the case, there is not Kafka's metadata stored inside Cassandra, **earliest** is used.\n\n```\ndocker-compose exec cassandra cqlsh -e \"SELECT * FROM structuredstreaming.kafkametadata;\"\n partition | offset\n-----------+--------\n         0 |    171\n```\n\n## Useful links\n* [Kafka tutorial #8 - Spark Structured Streaming](http://aseigneurin.github.io/2018/08/14/kafka-tutorial-8-spark-structured-streaming.html)\n* [Processing Data in Apache Kafka with Structured Streaming in Apache Spark 2.2](https://databricks.com/blog/2017/04/26/processing-data-in-apache-kafka-with-structured-streaming-in-apache-spark-2-2.html)\n* https://databricks.com/blog/2017/04/04/real-time-end-to-end-integration-with-apache-kafka-in-apache-sparks-structured-streaming.html\n* https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#using-foreach\n* https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#output-modes\n* [Elastic Structured Streamin doc](https://www.elastic.co/blog/structured-streaming-elasticsearch-for-hadoop-6-0)\n* [Structured Streaming - “Failed to find data source: es” ](https://discuss.elastic.co/t/structured-streaming-failed-to-find-data-source-es)\n* [Arbitrary Stateful Processing in Apache Spark’s Structured Streaming][1]\n* [Deep dive stateful stream processing][2] \n* [Official documentation][3]\n\n\n  [1]: https://databricks.com/blog/2017/10/17/arbitrary-stateful-processing-in-apache-sparks-structured-streaming.html\n  [2]: https://databricks.com/session/deep-dive-stateful-stream-processing\n  [3]: https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#arbitrary-stateful-operations\n\n### Docker-compose\n* [The last pickle's docker example](https://github.com/thelastpickle/docker-cassandra-bootstrap/blob/master/docker-compose.yml)\n* [Confluence's Kafka docker compose](https://docs.confluent.io/current/installation/docker/docs/quickstart.html#getting-started-with-docker-compose)\n\n## Inspired by\n* https://github.com/ansrivas/spark-structured-streaming\n* [Holden Karau's High Performance Spark](https://github.com/holdenk/spark-structured-streaming-ml/blob/master/src/main/scala/com/high-performance-spark-examples/structuredstreaming/CustomSink.scala#L66)\n* [Jay Kreps blog articles](https://medium.com/@jaykreps/exactly-once-support-in-apache-kafka-55e1fdd0a35f)\n"
  },
  {
    "path": "build.sbt",
    "content": "resolvers += \"Spark Packages Repo\" at \"https://dl.bintray.com/spark-packages/maven\"\n\nname := \"Spark-Structured-Streaming-Examples\"\n\nversion := \"1.0\"\nscalaVersion := \"2.11.12\"\nval sparkVersion = \"2.2.0\"\n\nlibraryDependencies += \"log4j\" % \"log4j\" % \"1.2.14\"\n\nlibraryDependencies += \"org.apache.spark\" %% \"spark-core\" % sparkVersion\nlibraryDependencies += \"org.apache.spark\" %% \"spark-sql\" % sparkVersion\nlibraryDependencies += \"org.apache.spark\" % \"spark-sql-kafka-0-10_2.11\" % sparkVersion\nlibraryDependencies += \"com.datastax.spark\" %% \"spark-cassandra-connector\" % \"2.0.2\"\n\nfork in run := true\n\nlibraryDependencies += \"org.elasticsearch\" % \"elasticsearch-hadoop\" % \"6.3.0\"\n\n"
  },
  {
    "path": "data/allRadioPartitionByRadioAndDate.parquet/_SUCCESS",
    "content": ""
  },
  {
    "path": "data/broadcast.parquet/_SUCCESS",
    "content": ""
  },
  {
    "path": "docker-compose.yml",
    "content": "version: '2'\nservices:\n  zookeeper: # thanks to https://github.com/confluentinc/cp-docker-images/issues/265#issuecomment-314442790\n    image: confluentinc/cp-zookeeper:latest\n    environment:\n      ZOOKEEPER_CLIENT_PORT: 32181\n      ZOOKEEPER_TICK_TIME: 2000\n    ports:\n        - \"32181:32181\"\n    extra_hosts:\n      - \"localhost: 127.0.0.1\"\n  kafka:\n    image: confluentinc/cp-kafka:latest\n    depends_on:\n      - zookeeper\n    environment:\n      KAFKA_BROKER_ID: 1\n      KAFKA_ZOOKEEPER_CONNECT: zookeeper:32181\n      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092\n      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1\n      KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'true'\n    ports:\n        - \"9092:9092\"\n    extra_hosts:\n      - \"localhost: 127.0.0.1\"\n\n  cassandra:\n    image: cassandra:3.11\n    ports:\n      - \"9042:9042\"\n      - \"7199:7199\"\n    volumes:\n      - ./src/conf/cassandra/schema.cql:/schema.cql\n    extra_hosts:\n      - \"localhost: 127.0.0.1\"\n\n  elasticsearch:\n    image: docker.elastic.co/elasticsearch/elasticsearch:6.3.0\n    container_name: elasticsearch\n#   environment: ['http.host=0.0.0.0', 'transport.host=127.0.0.1']\n    ports:\n      - \"9200:9200\"\n    extra_hosts:\n      - \"localhost: 127.0.0.1\"\n\n  kibana:\n    image: docker.elastic.co/kibana/kibana:6.3.0\n    container_name: kibana\n\n    ports:\n      - \"5601:5601\"\n    depends_on: ['elasticsearch']\n    extra_hosts:\n      - \"localhost: 127.0.0.1\""
  },
  {
    "path": "src/conf/cassandra/create-schema.sh",
    "content": "#!/bin/bash\n\n# create Cassandra schema\ndocker-compose exec cassandra cqlsh -f /schema.cql;\n\n# confirm schema\ndocker-compose exec cassandra cqlsh -e \"DESCRIBE SCHEMA;\""
  },
  {
    "path": "src/conf/cassandra/schema.cql",
    "content": "CREATE KEYSPACE IF NOT EXISTS structuredstreaming\n  WITH REPLICATION = {\n   'class' : 'SimpleStrategy',\n   'replication_factor' : 1\n  };\n\n\nCREATE TABLE IF NOT EXISTS structuredstreaming.radio (\nradio varchar,\ntitle varchar,\nartist varchar,\ncount bigint,\nPRIMARY KEY (radio, title, artist)\n) WITH comment = 'First sink to test the other \"unsafe\" Cassandra Foreach Sink.';\n\n\nCREATE TABLE IF NOT EXISTS structuredstreaming.radioOtherSink (\nradio varchar,\ntitle varchar,\nartist varchar,\ncount bigint,\nPRIMARY KEY (radio, title, artist)\n) WITH comment = 'Second sink to test Datastax connector.';\n\nCREATE TABLE IF NOT EXISTS structuredstreaming.kafkaMetadata (\npartition int,\noffset bigint,\nPRIMARY KEY (partition)\n) WITH comment = 'Save kafka metadata : topic and partitions offsets.';"
  },
  {
    "path": "src/conf/log4j.properties",
    "content": "log4j.logger.org.apache.spark.storage.BlockManager=OFF"
  },
  {
    "path": "src/main/scala/Main.scala",
    "content": "package main\n\nimport cassandra.CassandraDriver\nimport elastic.ElasticSink\nimport kafka.{KafkaSink, KafkaSource}\nimport mapGroupsWithState.MapGroupsWithState\nimport parquetHelper.ParquetService\nimport spark.SparkHelper\n\nobject Main {\n\n  def main(args: Array[String]) {\n    val spark = SparkHelper.getAndConfigureSparkSession()\n\n    //Classic Batch\n    //ParquetService.batchWay()\n\n    //Streaming way\n    //Generate a \"fake\" stream from a parquet file\n    val streamDS = ParquetService.streamingWay()\n\n    val songEvent = ParquetService.streamEachEvent\n\n    ElasticSink.writeStream(songEvent)\n\n    //Send it to Kafka for our example\n    KafkaSink.writeStream(streamDS)\n\n    //Finally read it from kafka, in case checkpointing is not available we read last offsets saved from Cassandra\n    val (startingOption, partitionsAndOffsets) = CassandraDriver.getKafaMetadata()\n    val kafkaInputDS = KafkaSource.read(startingOption, partitionsAndOffsets)\n\n    //Just debugging Kafka source into our console\n    KafkaSink.debugStream(kafkaInputDS)\n\n    //Saving using Datastax connector's saveToCassandra method\n    CassandraDriver.saveStreamSinkProvider(kafkaInputDS)\n\n    //Saving using the foreach method\n    //CassandraDriver.saveForeach(kafkaInputDS) //Untype/unsafe method using CQL  --> just here for example\n\n    //Another fun example managing an arbitrary state\n    MapGroupsWithState.write(kafkaInputDS)\n\n    //Wait for all streams to finish\n    spark.streams.awaitAnyTermination()\n  }\n}\n"
  },
  {
    "path": "src/main/scala/cassandra/CassandraDriver.scala",
    "content": "package cassandra\n\nimport org.apache.spark.sql._\nimport com.datastax.spark.connector._\nimport com.datastax.spark.connector.cql.CassandraConnector\nimport kafka.KafkaService\nimport radio.{SimpleSongAggregation, SimpleSongAggregationKafka}\nimport spark.SparkHelper\nimport foreachSink._\nimport log.LazyLogger\n\nobject CassandraDriver extends LazyLogger {\n  private val spark = SparkHelper.getSparkSession()\n  import spark.implicits._\n\n  val connector = CassandraConnector(SparkHelper.getSparkSession().sparkContext.getConf)\n\n  val namespace = \"structuredstreaming\"\n  val foreachTableSink = \"radio\"\n  val StreamProviderTableSink = \"radioothersink\"\n  val kafkaMetadata = \"kafkametadata\"\n  def getTestInfo() = {\n    val rdd = spark.sparkContext.cassandraTable(namespace, kafkaMetadata)\n\n    if( !rdd.isEmpty ) {\n      log.warn(rdd.count)\n      log.warn(rdd.first)\n    } else {\n      log.warn(s\"$namespace, $kafkaMetadata is empty in cassandra\")\n    }\n  }\n\n\n  /**\n    * remove kafka metadata and only focus on business structure\n    */\n  def getDatasetForCassandra(df: DataFrame) = {\n    df.select(KafkaService.radioStructureName + \".*\")\n      .as[SimpleSongAggregation]\n  }\n\n  //https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#using-foreach\n  //https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#output-modes\n  def saveForeach(df: DataFrame ) = {\n    val ds = CassandraDriver.getDatasetForCassandra(df)\n\n    ds\n      .writeStream\n      .queryName(\"KafkaToCassandraForeach\")\n      .outputMode(\"update\")\n      .foreach(new CassandraSinkForeach())\n      .start()\n  }\n\n  def saveStreamSinkProvider(ds: Dataset[SimpleSongAggregationKafka]) = {\n    ds\n      .toDF() //@TODO see if we can use directly the Dataset object\n      .writeStream\n      .format(\"cassandra.StreamSinkProvider.CassandraSinkProvider\")\n      .outputMode(\"update\")\n      .queryName(\"KafkaToCassandraStreamSinkProvider\")\n      .start()\n  }\n\n  /**\n    * @TODO handle more topic name, for our example we only use the topic \"test\"\n    *\n    *  we can use collect here as kafkameta data is not big at all\n    *\n    * if no metadata are found, we would use the earliest offsets.\n    *\n    * @see https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html#creating-a-kafka-source-batch\n    *  assign\tjson string {\"topicA\":[0,1],\"topicB\":[2,4]}\n    *  Specific TopicPartitions to consume. Only one of \"assign\", \"subscribe\" or \"subscribePattern\" options can be specified for Kafka source.\n    */\n  def getKafaMetadata() = {\n    try {\n      val kafkaMetadataRDD = spark.sparkContext.cassandraTable(namespace, kafkaMetadata)\n\n      val output = if (kafkaMetadataRDD.isEmpty) {\n        (\"startingOffsets\", \"earliest\")\n      } else {\n        (\"startingOffsets\", transformKafkaMetadataArrayToJson(kafkaMetadataRDD.collect()))\n      }\n      log.warn(\"getKafkaMetadata \" + output.toString)\n\n      output\n    }\n    catch {\n      case e: Exception =>\n        (\"startingOffsets\", \"earliest\")\n    }\n  }\n\n  /**\n    * @param array\n    * @return {\"topicA\":{\"0\":23,\"1\":-1},\"topicB\":{\"0\":-2}}\n    */\n  def transformKafkaMetadataArrayToJson(array: Array[CassandraRow]) : String = {\n      s\"\"\"{\"${KafkaService.topicName}\":\n          {\n           \"${array(0).getLong(\"partition\")}\": ${array(0).getLong(\"offset\")}\n          }\n         }\n      \"\"\".replaceAll(\"\\n\", \"\").replaceAll(\" \", \"\")\n  }\n\n  def debug() = {\n   val output = spark.sparkContext.cassandraTable(namespace, foreachTableSink)\n\n    log.warn(output.count)\n  }\n}\n"
  },
  {
    "path": "src/main/scala/cassandra/CassandraKafkaMetadata.scala",
    "content": "package cassandra\n\nimport kafka.KafkaMetadata\n\nobject CassandraKafkaMetadata {\n  private def cql(metadata: KafkaMetadata): String = s\"\"\"\n       INSERT INTO ${CassandraDriver.namespace}.${CassandraDriver.kafkaMetadata} (partition, offset)\n       VALUES(${metadata.partition}, ${metadata.offset})\n    \"\"\"\n\n  //https://github.com/datastax/spark-cassandra-connector/blob/master/doc/1_connecting.md#connection-pooling\n  def save(metadata: KafkaMetadata) = {\n    CassandraDriver.connector.withSessionDo(session =>\n      session.execute(cql(metadata))\n    )\n  }\n}\n"
  },
  {
    "path": "src/main/scala/cassandra/StreamSinkProvider/CassandraSink.scala",
    "content": "package cassandra.StreamSinkProvider\n\nimport cassandra.{CassandraDriver, CassandraKafkaMetadata}\nimport org.apache.spark.sql.{DataFrame, Dataset}\nimport org.apache.spark.sql.execution.streaming.Sink\nimport org.apache.spark.sql.functions.max\nimport spark.SparkHelper\nimport cassandra.CassandraDriver\nimport com.datastax.spark.connector._\nimport kafka.KafkaMetadata\nimport log.LazyLogger\nimport org.apache.spark.sql.execution.streaming.Sink\nimport org.apache.spark.sql.types.LongType\nimport radio.SimpleSongAggregation\n\n/**\n* must be idempotent and synchronous (@TODO check asynchronous/synchronous from Datastax's Spark connector) sink\n*/\nclass CassandraSink() extends Sink with LazyLogger {\n  private val spark = SparkHelper.getSparkSession()\n  import spark.implicits._\n  import org.apache.spark.sql.functions._\n\n  private def saveToCassandra(df: DataFrame) = {\n    val ds = CassandraDriver.getDatasetForCassandra(df)\n    ds.show() //Debug only\n\n    ds.rdd.saveToCassandra(CassandraDriver.namespace,\n      CassandraDriver.StreamProviderTableSink,\n      SomeColumns(\"title\", \"artist\", \"radio\", \"count\")\n    )\n\n    saveKafkaMetaData(df)\n  }\n\n  /*\n   * As per SPARK-16020 arbitrary transformations are not supported, but\n   * converting to an RDD allows us to do magic.\n   */\n  override def addBatch(batchId: Long, df: DataFrame) = {\n    log.warn(s\"CassandraSink - Datastax's saveToCassandra method -  batchId : ${batchId}\")\n    saveToCassandra(df)\n  }\n\n  /**\n    * saving the highest value of offset per partition when checkpointing is not available (application upgrade for example)\n    * http://docs.datastax.com/en/cassandra/3.0/cassandra/dml/dmlTransactionsDiffer.html\n    * should be done in the same transaction as the data linked to the offsets\n    */\n  private def saveKafkaMetaData(df: DataFrame) = {\n    val kafkaMetadata = df\n      .groupBy($\"partition\")\n      .agg(max($\"offset\").cast(LongType).as(\"offset\"))\n      .as[KafkaMetadata]\n\n    log.warn(\"Saving Kafka Metadata (partition and offset per topic (only one in our example)\")\n    kafkaMetadata.show()\n\n    kafkaMetadata.rdd.saveToCassandra(CassandraDriver.namespace,\n      CassandraDriver.kafkaMetadata,\n      SomeColumns(\"partition\", \"offset\")\n    )\n\n    //Otherway to save offset inside Cassandra\n    //kafkaMetadata.collect().foreach(CassandraKafkaMetadata.save)\n  }\n}\n\n"
  },
  {
    "path": "src/main/scala/cassandra/StreamSinkProvider/CassandraSinkProvider.scala",
    "content": "package cassandra.StreamSinkProvider\n\nimport org.apache.spark.sql.sources.StreamSinkProvider\nimport org.apache.spark.sql.streaming.OutputMode\nimport org.apache.spark.sql.{DataFrame, SQLContext}\n\n/**\n  From Holden Karau's High Performance Spark\n  https://github.com/holdenk/spark-structured-streaming-ml/blob/master/src/main/scala/com/high-performance-spark-examples/structuredstreaming/CustomSink.scala#L66\n  *\n  */\nclass CassandraSinkProvider extends StreamSinkProvider {\n  override def createSink(sqlContext: SQLContext,\n                          parameters: Map[String, String],\n                          partitionColumns: Seq[String],\n                          outputMode: OutputMode): CassandraSink = {\n    new CassandraSink()\n  }\n}"
  },
  {
    "path": "src/main/scala/cassandra/foreachSink/CassandraSinkForeach.scala",
    "content": "package cassandra.foreachSink\n\nimport cassandra.CassandraDriver\nimport log.LazyLogger\nimport org.apache.spark.sql.ForeachWriter\nimport radio.SimpleSongAggregation\n\n/**\n  * Inspired by\n  * https://github.com/ansrivas/spark-structured-streaming/\n  * https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#using-foreach\n  */\nclass CassandraSinkForeach() extends ForeachWriter[SimpleSongAggregation] with LazyLogger {\n  private def cqlRadio(record: SimpleSongAggregation): String = s\"\"\"\n       insert into ${CassandraDriver.namespace}.${CassandraDriver.foreachTableSink} (title, artist, radio, count)\n       values('${record.title}', '${record.artist}', '${record.radio}', ${record.count})\"\"\"\n\n  def open(partitionId: Long, version: Long): Boolean = {\n    // open connection\n    //@TODO command to check if cassandra cluster is up\n    true\n  }\n\n  //https://github.com/datastax/spark-cassandra-connector/blob/master/doc/1_connecting.md#connection-pooling\n  def process(record: SimpleSongAggregation) = {\n    log.warn(s\"Saving record: $record\")\n    CassandraDriver.connector.withSessionDo(session =>\n      session.execute(cqlRadio(record))\n    )\n  }\n\n  //https://github.com/datastax/spark-cassandra-connector/blob/master/doc/reference.md#cassandra-connection-parameters\n\n  def close(errorOrNull: Throwable): Unit = {\n    // close the connection\n    //connection.keep_alive_ms\t--> 5000ms :\tPeriod of time to keep unused connections open\n  }\n}"
  },
  {
    "path": "src/main/scala/elastic/ElasticSink.scala",
    "content": "package elastic\n\nimport org.apache.spark.sql.{DataFrame, Dataset, SparkSession}\nimport org.apache.spark.sql.streaming.{OutputMode, StreamingQuery}\nimport radio.{SimpleSongAggregation, Song}\nimport org.elasticsearch.spark.sql.streaming._\nimport org.elasticsearch.spark.sql._\nimport org.elasticsearch.spark.sql.streaming.EsSparkSqlStreamingSink\n\nobject ElasticSink {\n  def writeStream(ds: Dataset[Song] ) : StreamingQuery = {\n    ds   //Append output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark\n      .writeStream\n      .outputMode(OutputMode.Append) //Only mode for ES\n      .format(\"org.elasticsearch.spark.sql\") //es\n      .queryName(\"ElasticSink\")\n      .start(\"test/broadcast\") //ES index\n  }\n\n}"
  },
  {
    "path": "src/main/scala/kafka/KafkaMetadata.scala",
    "content": "package kafka\n\ncase class KafkaMetadata(partition: Long, offset: Long)\n"
  },
  {
    "path": "src/main/scala/kafka/KafkaService.scala",
    "content": "package kafka\n\nimport org.apache.spark.sql.types.StringType\nimport org.apache.spark.sql.types._\nimport spark.SparkHelper\n\nobject KafkaService {\n  private val spark = SparkHelper.getSparkSession()\n\n  val radioStructureName = \"radioCount\"\n\n  val topicName = \"test\"\n\n  val bootstrapServers = \"localhost:9092\"\n\n  val schemaOutput = new StructType()\n    .add(\"title\", StringType)\n    .add(\"artist\", StringType)\n    .add(\"radio\", StringType)\n    .add(\"count\", LongType)\n}\n"
  },
  {
    "path": "src/main/scala/kafka/KafkaSink.scala",
    "content": "package kafka\n\nimport org.apache.spark.sql.{DataFrame, Dataset}\nimport org.apache.spark.sql.functions.{struct, to_json, _}\nimport _root_.log.LazyLogger\nimport org.apache.spark.sql.streaming.StreamingQuery\nimport org.apache.spark.sql.types.{StringType, _}\nimport radio.{SimpleSongAggregation, SimpleSongAggregationKafka}\nimport spark.SparkHelper\n\nobject KafkaSink extends LazyLogger {\n  private val spark = SparkHelper.getSparkSession()\n\n  import spark.implicits._\n\n  def writeStream(staticInputDS: Dataset[SimpleSongAggregation]) : StreamingQuery = {\n    log.warn(\"Writing to Kafka\")\n    staticInputDS\n      .select(to_json(struct($\"*\")).cast(StringType).alias(\"value\"))\n      .writeStream\n      .outputMode(\"update\")\n      .format(\"kafka\")\n      .option(\"kafka.bootstrap.servers\", KafkaService.bootstrapServers)\n      .queryName(\"Kafka - Count number of broadcasts for a title/artist by radio\")\n      .option(\"topic\", \"test\")\n      .start()\n  }\n\n  /**\n      Console sink from Kafka's stream\n      +----+--------------------+-----+---------+------+--------------------+-------------+--------------------+\n      | key|               value|topic|partition|offset|           timestamp|timestampType|          radioCount|\n      +----+--------------------+-----+---------+------+--------------------+-------------+--------------------+\n      |null|[7B 22 72 61 64 6...| test|        0|    60|2017-11-21 22:56:...|            0|[Feel No Ways,Dra...|\n    *\n    */\n  def debugStream(staticKafkaInputDS: Dataset[SimpleSongAggregationKafka]) = {\n    staticKafkaInputDS\n      .writeStream\n      .queryName(\"Debug Stream Kafka\")\n      .format(\"console\")\n      .start()\n  }\n}\n"
  },
  {
    "path": "src/main/scala/kafka/KafkaSource.scala",
    "content": "package kafka\n\nimport org.apache.spark.sql.{DataFrame, Dataset}\nimport org.apache.spark.sql.functions.{struct, to_json, _}\nimport _root_.log.LazyLogger\nimport org.apache.spark.sql.types.{StringType, _}\nimport radio.{SimpleSongAggregation, SimpleSongAggregationKafka}\nimport spark.SparkHelper\n\n/**\n @see https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html\n */\nobject KafkaSource extends LazyLogger {\n  private val spark = SparkHelper.getSparkSession()\n\n  import spark.implicits._\n\n  /**\n    * will return, we keep some kafka metadata for our example, otherwise we would only focus on \"radioCount\" structure\n     |-- key: binary (nullable = true)\n     |-- value: binary (nullable = true)\n     |-- topic: string (nullable = true) : KEPT\n     |-- partition: integer (nullable = true) : KEPT\n     |-- offset: long (nullable = true) : KEPT\n     |-- timestamp: timestamp (nullable = true) : KEPT\n     |-- timestampType: integer (nullable = true)\n     |-- radioCount: struct (nullable = true)\n     |    |-- title: string (nullable = true)\n     |    |-- artist: string (nullable = true)\n     |    |-- radio: string (nullable = true)\n     |    |-- count: long (nullable = true)\n\n    * @return\n    *\n    *\n    * startingOffsets should use a JSON coming from the lastest offsets saved in our DB (Cassandra here)\n    */\n    def read(startingOption: String = \"startingOffsets\", partitionsAndOffsets: String = \"earliest\") : Dataset[SimpleSongAggregationKafka] = {\n      log.warn(\"Reading from Kafka\")\n\n      spark\n      .readStream\n      .format(\"kafka\")\n      .option(\"kafka.bootstrap.servers\", \"localhost:9092\")\n      .option(\"subscribe\", KafkaService.topicName)\n      .option(\"enable.auto.commit\", false) // Cannot be set to true in Spark Strucutured Streaming https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html#kafka-specific-configurations\n      .option(\"group.id\", \"Structured-Streaming-Examples\")\n      .option(\"failOnDataLoss\", false) // when starting a fresh kafka (default location is temporary (/tmp) and cassandra is not (var/lib)), we have saved different offsets in Cassandra than real offsets in kafka (that contains nothing)\n      .option(startingOption, partitionsAndOffsets) //this only applies when a new query is started and that resuming will always pick up from where the query left off\n      .load()\n      .withColumn(KafkaService.radioStructureName, // nested structure with our json\n        from_json($\"value\".cast(StringType), KafkaService.schemaOutput) //From binary to JSON object\n      ).as[SimpleSongAggregationKafka]\n      .filter(_.radioCount != null) //TODO find a better way to filter bad json\n  }\n}\n"
  },
  {
    "path": "src/main/scala/log/LazyLogger.scala",
    "content": "package log\n\nimport org.apache.log4j.LogManager\n\ntrait LazyLogger {\n  @transient lazy val log = LogManager.getLogger(getClass)\n}\n"
  },
  {
    "path": "src/main/scala/mapGroupsWithState/MapGroupsWithState.scala",
    "content": "package mapGroupsWithState\n\nimport org.apache.spark.sql.{DataFrame, Dataset}\nimport org.apache.spark.sql.functions.{struct, to_json, _}\nimport _root_.log.LazyLogger\nimport org.apache.spark.sql.types.StringType\nimport spark.SparkHelper\nimport org.apache.spark.sql.streaming.{GroupState, GroupStateTimeout, OutputMode}\nimport radio.{ArtistAggregationState, SimpleSongAggregation, SimpleSongAggregationKafka}\n\nobject MapGroupsWithState extends LazyLogger {\n  private val spark = SparkHelper.getSparkSession()\n\n  import spark.implicits._\n\n\n  def updateArtistStateWithEvent(state: ArtistAggregationState, artistCount : SimpleSongAggregation) = {\n    log.warn(\"MapGroupsWithState - updateArtistStateWithEvent\")\n    if(state.artist == artistCount.artist) {\n      ArtistAggregationState(state.artist, state.count + artistCount.count)\n    } else {\n      state\n    }\n  }\n\n  def updateAcrossEvents(artist:String,\n                         inputs: Iterator[SimpleSongAggregation],\n                         oldState: GroupState[ArtistAggregationState]): ArtistAggregationState = {\n\n    var state: ArtistAggregationState = if (oldState.exists)\n      oldState.get\n    else\n      ArtistAggregationState(artist, 1L)\n\n    // for every rows, let's count by artist the number of broadcast, instead of counting by artist, title and radio\n    for (input <- inputs) {\n      state = updateArtistStateWithEvent(state, input)\n      oldState.update(state)\n    }\n\n    state\n  }\n\n\n  /**\n    *\n    * @return\n    *\n    * Batch: 4\n      -------------------------------------------\n      +------+-----+\n      |artist|count|\n      +------+-----+\n      | Drake| 4635|\n      +------+-----+\n\n      Batch: 5\n      -------------------------------------------\n      +------+-----+\n      |artist|count|\n      +------+-----+\n      | Drake| 4710|\n      +------+-----+\n    */\n  def write(ds: Dataset[SimpleSongAggregationKafka] ) = {\n    ds.select($\"radioCount.title\", $\"radioCount.artist\", $\"radioCount.radio\", $\"radioCount.count\")\n      .as[SimpleSongAggregation]\n      .groupByKey(_.artist)\n      .mapGroupsWithState(GroupStateTimeout.NoTimeout)(updateAcrossEvents) //we can control what should be done with the state when no update is received after a timeout.\n      .writeStream\n      .outputMode(OutputMode.Update())\n      .format(\"console\")\n      .queryName(\"mapGroupsWithState - counting artist broadcast\")\n      .start()\n  }\n}\n"
  },
  {
    "path": "src/main/scala/parquetHelper/ParquetService.scala",
    "content": "package parquetHelper\n\nimport log.LazyLogger\nimport org.apache.spark.sql.{DataFrame, Dataset}\nimport org.apache.spark.sql.types._\nimport radio.{SimpleSongAggregation, Song}\nimport spark.SparkHelper\n\nobject ParquetService extends LazyLogger {\n  val pathRadioStationSongs = \"data/allRadioPartitionByRadioAndDate.parquet\"\n  val pathRadioES = \"data/broadcast.parquet\"\n\n  private val spark = SparkHelper.getSparkSession()\n  import spark.implicits._\n\n  val schema = new StructType()\n    .add(\"timestamp\", TimestampType)\n    .add(\"title\", StringType)\n    .add(\"artist\", StringType)\n    .add(\"radio\", StringType)\n    .add(\"humanDate\", LongType)\n    .add(\"hour\", IntegerType)\n    .add(\"minute\", IntegerType)\n    .add(\"allArtists\", StringType)\n    .add(\"year\", IntegerType)\n    .add(\"month\", IntegerType)\n    .add(\"day\", IntegerType)\n\n  def batchWay() = {\n    //Classic  Batch way\n    val batchWay =\n      spark\n        .read\n        .schema(ParquetService.schema)\n        .parquet(pathRadioStationSongs)\n        .where($\"artist\" === \"Drake\")\n        .groupBy($\"radio\", $\"artist\",  $\"title\")\n        .count()\n        .orderBy(\"count\")\n        .as[Song]\n\n    batchWay.show()\n\n    batchWay\n  }\n\n  def streamingWay() : Dataset[SimpleSongAggregation] = {\n    log.warn(\"Starting to stream events from Parquet files....\")\n\n    spark\n      .readStream\n      .schema(ParquetService.schema)\n      .option(\"maxFilesPerTrigger\", 1000)  // Treat a sequence of files as a stream by picking one file at a time\n      .parquet(pathRadioStationSongs)\n      .as[Song]\n      .where($\"artist\" === \"Drake\")\n      .groupBy($\"radio\", $\"artist\",  $\"title\")\n      .count()\n      .as[SimpleSongAggregation]\n  }\n\n  def streamEachEvent : Dataset[Song]  = {\n    spark\n      .readStream\n      .schema(ParquetService.schema)\n      .option(\"maxFilesPerTrigger\", 1000)  // Treat a sequence of files as a stream by picking one file at a time\n      .parquet(pathRadioES)\n      .as[Song]\n      .where($\"artist\" === \"Drake\")\n      .withWatermark(\"timestamp\", \"10 minutes\")\n      .as[Song]\n  }\n\n  //Process stream on console to debug only\n  def debugStream(staticInputDF: DataFrame) = {\n    staticInputDF.writeStream\n      .format(\"console\")\n      .outputMode(\"complete\")\n      .queryName(\"Console - Count number of broadcasts for a title/artist by radio\")\n      .start()\n  }\n}\n"
  },
  {
    "path": "src/main/scala/radio/Song.scala",
    "content": "package radio\n\nimport java.sql.Timestamp\n\ncase class Song(timestamp: Long, humanDate:Long, year:Int, month:Int, day:Int, hour:Int, minute: Int, artist:String, allArtists: String, title:String, radio:String)\n\ncase class SimpleSong(title: String, artist: String, radio: String)\n\ncase class SimpleSongAggregation(title: String, artist: String, radio: String, count: Long)\n\ncase class SimpleSongAggregationKafka(topic: String, partition: Int, offset: Long, timestamp: Timestamp, radioCount: SimpleSongAggregation)\n\ncase class ArtistAggregationState(artist: String, count: Long)"
  },
  {
    "path": "src/main/scala/spark/SparkHelper.scala",
    "content": "package spark\n\nimport org.apache.spark.{SparkConf, SparkContext}\nimport org.apache.spark.sql.SparkSession\n\nobject SparkHelper {\n  def getAndConfigureSparkSession() = {\n    val conf = new SparkConf()\n      .setAppName(\"Structured Streaming from Parquet to Cassandra\")\n      .setMaster(\"local[2]\")\n      .set(\"spark.cassandra.connection.host\", \"127.0.0.1\")\n      .set(\"spark.sql.streaming.checkpointLocation\", \"checkpoint\")\n      .set(\"es.nodes\", \"localhost\") // full config : https://www.elastic.co/guide/en/elasticsearch/hadoop/current/configuration.html\n      .set(\"es.index.auto.create\", \"true\") //https://www.elastic.co/guide/en/elasticsearch/hadoop/current/spark.html\n      .set(\"es.nodes.wan.only\", \"true\")\n\n    val sc = new SparkContext(conf)\n    sc.setLogLevel(\"WARN\")\n\n    SparkSession\n      .builder()\n      .getOrCreate()\n  }\n\n  def getSparkSession() = {\n    SparkSession\n      .builder()\n      .getOrCreate()\n  }\n}\n"
  },
  {
    "path": "start-docker-compose.sh",
    "content": "#!/bin/bash\n\ndocker-compose up -d --no-recreate;\n\n# create Cassandra schema\nsleep 5\necho \"Creating Cassandra's Schema... if error run ./src/conf/cassandra/create-schema.sh\"\n./src/conf/cassandra/create-schema.sh\n"
  }
]