• Stars
    star
    459
  • Rank 95,377 (Top 2 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This projects gives Kotlin bindings and several extensions for Apache Spark. We are looking to have this as a part of Apache Spark 3.x

Kotlin for Apache® Spark™

Kotlin Stable JetBrains official project Maven Central Join the chat at https://gitter.im/JetBrains/kotlin-spark-api

Your next API to work with Apache Spark.

This project adds a missing layer of compatibility between Kotlin and Apache Spark. It allows Kotlin developers to use familiar language features such as data classes, and lambda expressions as simple expressions in curly braces or method references.

We have opened a Spark Project Improvement Proposal: Kotlin support for Apache Spark to work with the community towards getting Kotlin support as a first-class citizen in Apache Spark. We encourage you to voice your opinions and participate in the discussion.

Table of Contents

Supported versions of Apache Spark

Apache Spark Scala Kotlin for Apache Spark
3.3.1 2.13 kotlin-spark-api_3.3.1_2.13:VERSION
2.12 kotlin-spark-api_3.3.1_2.12:VERSION
3.3.0 2.13 kotlin-spark-api_3.3.0_2.13:VERSION
2.12 kotlin-spark-api_3.3.0_2.12:VERSION
3.2.3 2.13 kotlin-spark-api_3.2.3_2.13:VERSION
2.12 kotlin-spark-api_3.2.3_2.12:VERSION
3.2.2 2.13 kotlin-spark-api_3.2.2_2.13:VERSION
2.12 kotlin-spark-api_3.2.2_2.12:VERSION
3.2.1 2.13 kotlin-spark-api_3.2.1_2.13:VERSION
2.12 kotlin-spark-api_3.2.1_2.12:VERSION
3.2.0 2.13 kotlin-spark-api_3.2.0_2.13:VERSION
2.12 kotlin-spark-api_3.2.0_2.12:VERSION
3.1.3 2.12 kotlin-spark-api_3.1.3_2.12:VERSION
3.1.2 2.12 kotlin-spark-api_3.1.2_2.12:VERSION
3.1.1 2.12 kotlin-spark-api_3.1.1_2.12:VERSION
3.1.0 2.12 kotlin-spark-api_3.1.0_2.12:VERSION
3.0.3 2.12 kotlin-spark-api_3.0.3_2.12:VERSION
3.0.2 2.12 kotlin-spark-api_3.0.2_2.12:VERSION
3.0.1 2.12 kotlin-spark-api_3.0.1_2.12:VERSION
3.0.0 2.12 kotlin-spark-api_3.0.0_2.12:VERSION

Deprecated versions

Apache Spark Scala Kotlin for Apache Spark
2.4.1+ 2.12 kotlin-spark-api-2.4_2.12:1.0.2
2.4.1+ 2.11 kotlin-spark-api-2.4_2.11:1.0.2

Releases

The list of Kotlin for Apache Spark releases is available here. The Kotlin for Spark artifacts adhere to the following convention: [name]_[Apache Spark version]_[Scala core version]:[Kotlin for Apache Spark API version]

The only exception to this is scala-tuples-in-kotlin_[Scala core version]:[Kotlin for Apache Spark API version], which is independent of Spark.

Maven Central

How to configure Kotlin for Apache Spark in your project

You can add Kotlin for Apache Spark as a dependency to your project: Maven, Gradle, SBT, and leinengen are supported.

Here's an example pom.xml:

<dependency>
  <groupId>org.jetbrains.kotlinx.spark</groupId>
  <artifactId>kotlin-spark-api_3.3.1_2.13</artifactId>
  <version>${kotlin-spark-api.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.13</artifactId>
    <version>${spark.version}</version>
</dependency>

Note that you must match the version of the Kotlin for Apache Spark API to the Spark- and Scala version of your project. You can find a complete example with pom.xml and build.gradle in the Quick Start Guide.

If you want to try a development version. You can use the versions published to GH Packages. They typically have the same version as the release version, but with a -SNAPSHOT suffix. See the GitHub Docs for more information.

Once you have configured the dependency, you only need to add the following import to your Kotlin file:

import org.jetbrains.kotlinx.spark.api.*

Jupyter

The Kotlin Spark API also supports Kotlin Jupyter notebooks. To it, simply add

%use spark

to the top of your notebook. This will get the latest version of the API, together with the latest version of Spark. To define a certain version of Spark or the API itself, simply add it like this:

%use spark(spark=3.3.1, scala=2.13, v=1.2.2)

Inside the notebook a Spark session will be initiated automatically. This can be accessed via the spark value. sc: JavaSparkContext can also be accessed directly. The API operates pretty similarly.

There is also support for HTML rendering of Datasets and simple (Java)RDDs. Check out the example as well.

To use Spark Streaming abilities, instead use

%use spark-streaming

This does not start a Spark session right away, meaning you can call withSparkStreaming(batchDuration) {} in whichever cell you want. Check out the example.

NOTE: You need kotlin-jupyter-kernel to be at least version 0.11.0.83 for the Kotlin Spark API to work. Also, if the %use spark magic does not output "Spark session has been started...", and %use spark-streaming doesn't work at all, add %useLatestDescriptors above it.

For more information, check the wiki.

Kotlin for Apache Spark features

Creating a SparkSession in Kotlin

val spark = SparkSession
        .builder()
        .master("local[2]")
        .appName("Simple Application").orCreate

This is not needed when running the Kotlin Spark API from a Jupyter notebook.

Creating a Dataset in Kotlin

spark.dsOf("a" to 1, "b" to 2)

The example above produces Dataset<Pair<String, Int>>. While Kotlin Pairs and Triples are supported, Scala Tuples are recommended for better support.

Null safety

There are several aliases in API, like leftJoin, rightJoin etc. These are null-safe by design. For example, leftJoin is aware of nullability and returns Dataset<Pair<LEFT, RIGHT?>>. Note that we are forcing RIGHT to be nullable for you as a developer to be able to handle this situation. NullPointerExceptions are hard to debug in Spark, and we're doing our best to make them as rare as possible.

In Spark, you might also come across Scala-native Option<*> or Java-compatible Optional<*> classes. We provide getOrNull() and getOrElse() functions for these to use Kotlin's null safety for good.

Similarly, you can also create Option<*>s and Optional<*>s like T?.toOptional() if a Spark function requires it.

withSpark function

We provide you with useful function withSpark, which accepts everything that may be needed to run Spark — properties, name, master location and so on. It also accepts a block of code to execute inside Spark context.

After work block ends, spark.stop() is called automatically.

Do not use this when running the Kotlin Spark API from a Jupyter notebook.

withSpark {
    dsOf(1, 2)
        .map { it X it } // creates Tuple2<Int, Int>
        .show()
}

dsOf is just one more way to create Dataset (Dataset<Int>) from varargs.

withCached function

It can easily happen that we need to fork our computation to several paths. To compute things only once we should call cache method. However, it becomes difficult to control when we're using cached Dataset and when not. It is also easy to forget to unpersist cached data, which can break things unexpectedly or take up more memory than intended.

To solve these problems we've added withCached function

withSpark {
    dsOf(1, 2, 3, 4, 5)
        .map { tupleOf(it, it + 2) }
        .withCached {
            showDS()
  
            filter { it._1 % 2 == 0 }.showDS()
        }
        .map { tupleOf(it._1, it._2, (it._1 + it._2) * 2) }
        .show()
}

Here we're showing cached Dataset for debugging purposes then filtering it. The filter method returns filtered Dataset and then the cached Dataset is being unpersisted, so we have more memory t o call the map method and collect the resulting Dataset.

toList and toArray methods

For more idiomatic Kotlin code we've added toList and toArray methods in this API. You can still use the collect method as in Scala API, however the result should be casted to Array. This is because collect returns a Scala array, which is not the same as Java/Kotlin one.

Column infix/operator functions

Similar to the Scala API for Columns, many of the operator functions could be ported over. For example:

dataset.select( col("colA") + 5 )
dataset.select( col("colA") / col("colB") )

dataset.where( col("colA") `===` 6 )
// or alternatively
dataset.where( col("colA") eq 6)

To read more, check the wiki.

Overload resolution ambiguity

We had to implement the functions reduceGroups and reduce for Kotlin separately as reduceGroupsK and reduceK respectively, because otherwise it caused resolution ambiguity between Kotlin, Scala and Java APIs, which was quite hard to solve.

We have a special example of work with this function in the Groups example.

Tuples

Inspired by ScalaTuplesInKotlin, the API introduces a lot of helper- extension functions to make working with Scala Tuples a breeze in your Kotlin Spark projects. While working with data classes is encouraged, for pair-like Datasets / RDDs / DStreams Scala Tuples are recommended, both for the useful helper functions, as well as Spark performance. To enable these features simply add

import org.jetbrains.kotlinx.spark.api.tuples.*

to the start of your file.

Tuple creation can be done in the following manners:

val a: Tuple2<Int, Long> = tupleOf(1, 2L)
val b: Tuple3<String, Double, Int> = t("test", 1.0, 2)
val c: Tuple3<Float, String, Int> = 5f X "aaa" X 1

To read more about tuples and all the added functions, refer to the wiki.

Streaming

A popular Spark extension is Spark Streaming. Of course the Kotlin Spark API also introduces a more Kotlin-esque approach to write your streaming programs. There are examples for use with a checkpoint, Kafka and SQL in the examples module.

We shall also provide a quick example below:

// Automatically provides ssc: JavaStreamingContext which starts and awaits termination or timeout
withSparkStreaming(batchDuration = Durations.seconds(1), timeout = 10_000) { // this: KSparkStreamingSession

    // create input stream for, for instance, Netcat: `$ nc -lk 9999`
    val lines: JavaReceiverInputDStream<String> = ssc.socketTextStream("localhost", 9999)
  
    // split input stream on space
    val words: JavaDStream<String> = lines.flatMap { it.split(" ").iterator() }

    // perform action on each formed RDD in the stream
    words.foreachRDD { rdd: JavaRDD<String>, _: Time ->
      
          // to convert the JavaRDD to a Dataset, we need a spark session using the RDD context
          withSpark(rdd) { // this: KSparkSession
            val dataframe: Dataset<TestRow> = rdd.map { TestRow(word = it) }.toDS()
            dataframe
                .groupByKey { it.word }
                .count()
                .show()
            // +-----+--------+
            // |  key|count(1)|
            // +-----+--------+
            // |hello|       1|
            // |   is|       1|
            // |    a|       1|
            // | this|       1|
            // | test|       3|
            // +-----+--------+
        }
    }
}

For more information, check the wiki.

User Defined Functions

Spark has a way to call functions from SQL using so-called UDFs. Using the Scala/Java API from Kotlin is not that obvious, so we decided to add special UDF support for Kotlin. This support grew into a typesafe, name-safe, and feature-rich solution for which we will give an example:

// example of creation/naming, and registering of a simple UDF
val plusOne by udf { x: Int -> x + 1 }
plusOne.register()
spark.sql("SELECT plusOne(5)").show()
// +----------+
// |plusOne(5)|
// +----------+
// |         6|
// +----------+

// directly registering
udf.register("plusTwo") { x: Double -> x + 2.0 }
spark.sql("SELECT plusTwo(2.0d)").show()
// +------------+
// |plusTwo(2.0)|
// +------------+
// |         4.0|
// +------------+

// dataset select
val result: Dataset<Int> = myDs.select(
  plusOne(col(MyType::age))
)

We support:

  • a notation close to Spark's
  • smart naming (with reflection)
  • creation from function references
  • typed column operations
  • UDAF support and functional creation
  • (Unique!) simple vararg UDF support

For more, check the extensive examples. Also, check out the wiki.

Examples

For more, check out examples module. To get up and running quickly, check out this tutorial.

Reporting issues / support

Please use GitHub issues for filing feature requests and bug reports. You are also welcome to join kotlin-spark channel in the Kotlin Slack.

Contribution guide

Contributions are more than welcome! Pull requests can be created for the main branch and will be considered as soon as possible. Be sure to add the necessary tests for any new feature you add. The main branch always aims to target the latest available Apache Spark version. Note that we use Java Comment Preprocessor to build the library for all different supported versions of Apache Spark and Scala. The current values of these versions can be edited in gradle.properties and should always be the latest versions for commits. For testing, all versions need a pass for the request to be accepted. We use GitHub Actions to test and deploy the library for all versions, but locally you can also use the gradlew_all_versions file.

Of the main branch, development versions of the library are published to GitHub Packages. This way, new features can be tested quickly without having to wait for a full release.

For full releases, the release branch is updated.

Code of Conduct

This project and the corresponding community is governed by the JetBrains Open Source and Community Code of Conduct. Please make sure you read it.

License

Kotlin for Apache Spark is licensed under the Apache 2.0 License.

More Repositories

1

anko

Pleasant Android application development
Kotlin
15,927
star
2

kotlinx.coroutines

Library support for Kotlin coroutines
Kotlin
12,203
star
3

kotlinx.serialization

Kotlin multiplatform / multi-format serialization
Kotlin
5,375
star
4

dokka

API documentation engine for Kotlin
Kotlin
3,311
star
5

kotlin-examples

Various examples for Kotlin
3,177
star
6

KEEP

Kotlin Evolution and Enhancement Process
Markdown
3,109
star
7

kotlin-koans

Kotlin workshop
Kotlin
2,602
star
8

kotlinx-datetime

KotlinX multiplatform date/time library
Kotlin
2,379
star
9

kmp-production-sample

This is an open-source, mobile, cross-platform application built with Kotlin Multiplatform Mobile. It's a simple RSS reader, and you can download it from the App Store and Google Play. It's been designed to demonstrate how KMM can be used in real production projects.
Kotlin
1,984
star
10

kotlindl

High-level Deep Learning Framework written in Kotlin and inspired by Keras
Kotlin
1,467
star
11

coroutines-examples

Examples for coroutines design in Kotlin
1,465
star
12

kotlinx-kover

Kotlin
1,324
star
13

kotlin-fullstack-sample

Kotlin Full-stack Application Example
Kotlin
1,218
star
14

kotlinx.collections.immutable

Immutable persistent collections for Kotlin
Kotlin
1,153
star
15

kotlin-jupyter

Kotlin kernel for Jupyter/IPython
Kotlin
1,094
star
16

kotlinx-cli

Pure Kotlin implementation of a generic CLI parser.
Kotlin
906
star
17

kmm-basic-sample

Example of Kotlin multiplatform project
Kotlin
887
star
18

dataframe

Structured data processing in Kotlin
Kotlin
831
star
19

kotlinx-io

Kotlin multiplatform I/O library
Kotlin
817
star
20

binary-compatibility-validator

Public API management tool
Kotlin
795
star
21

kotlinx-rpc

Add asynchronous RPC services to your multiplatform applications.
Kotlin
730
star
22

kotlinx-atomicfu

The idiomatic way to use atomic operations in Kotlin
Kotlin
716
star
23

kotlinconf-spinner

Kotlin
603
star
24

workshop

JetBrains Kotlin Workshop Material
Kotlin
594
star
25

kotlin-interactive-shell

Kotlin Language Interactive Shell
Java
591
star
26

kdoctor

Environment analysis tool
Kotlin
580
star
27

kandy

Kotlin plotting library.
Kotlin
579
star
28

kotlin-frontend-plugin

Gradle Kotlin (http://kotlinlang.org) plugin for frontend development
Kotlin
570
star
29

dukat

Converter of <any kind of declarations> to Kotlin external declarations
Kotlin
552
star
30

multik

Kotlin
550
star
31

kotlin-wasm-examples

Examples with Kotlin/Wasm
519
star
32

kotlinx-benchmark

Kotlin multiplatform benchmarking toolkit
Kotlin
504
star
33

kotlin-by-example

The sources of Kotlin by Example.
396
star
34

kotlin-spec

Kotlin Language Specification:
Kotlin
358
star
35

kotlin-in-action

Code samples from the "Kotlin in Action" book
Kotlin
343
star
36

ts2kt

ts2kt is officially deprecated, please use https://github.com/Kotlin/dukat instead. // Converter of TypeScript definition files to Kotlin external declarations
Kotlin
320
star
37

kotlin-numpy

Kotlin bindings for NumPy
Kotlin
312
star
38

kotlin-style-guide

Work-in-progress notes for the Kotlin style guide
289
star
39

kotlinx-knit

Kotlin source code documentation management tool
Kotlin
287
star
40

anko-example

A small application built with Anko DSL
Kotlin
285
star
41

full-stack-web-jetbrains-night-sample

Full-stack demo application written with Kotlin MPP
Kotlin
271
star
42

KMP-App-Template

Kotlin Multiplatform app template with shared UI
Kotlin
269
star
43

kotlin-script-examples

Examples of Kotlin Scripts and usages of the Kotlin Scripting API
Kotlin
262
star
44

kotlinx-nodejs

Kotlin external declarations for using the Node.js API from Kotlin code targeting JavaScript
Kotlin
212
star
45

kotlin-eclipse

Kotlin Plugin for Eclipse
Kotlin
186
star
46

Storytale

Kotlin
165
star
47

kotlinx.reflect.lite

Lightweight library allowing to introspect basic stuff about Kotlin symbols
Kotlin
150
star
48

api-guidelines

Best practices to consider when writing an API for your library
144
star
49

kotlin-benchmarks

This is the project to verify and investigate performance issues in Kotlin and standard library.
Kotlin
136
star
50

kotlin-libs-publisher

Gradle plugin for publishing of Kotlin libs
Kotlin
119
star
51

kotlinx-browser

Kotlin browser API
Kotlin
110
star
52

kotlindl-app-sample

This repo demonstrates how to use KotlinDL for neural network inference on Android devices.
Kotlin
96
star
53

kotlin-koans-edu

Kotlin Koans for Educational Plugin and play.kotl.in
Kotlin
93
star
54

KMP-App-Template-Native

Kotlin Multiplatform app template with native UI
Kotlin
85
star
55

grammar-tools

Tokenization and parsing Kotlin code using the ANTLR Kotlin grammar
Kotlin
83
star
56

kmm-integration-sample

Kotlin
76
star
57

kmm-with-cocoapods-sample

This project represents the case when Cocoapods dependencies are added in Kotlin and there is no existing Xcode project
Kotlin
57
star
58

kotlin-koans-edu-obsolete

Obsolete: check https://github.com/Kotlin/kotlin-koans-edu for the latest version.
Kotlin
55
star
59

kotlin-native-calculator-sample

55
star
60

kotlinx.support

Extension and top-level functions to use JDK7/JDK8 features in Kotlin 1.0
Kotlin
54
star
61

js-externals

External declarations for Kotlin/JS
53
star
62

k2-performance-metrics

Measure Kotlin K2 compiler performance in your repository
Jupyter Notebook
45
star
63

kmp-native-wizard

A mostly-empty template to get started creating a Kotlin/Native project.
Kotlin
43
star
64

coroutines-workshop

Materials for a full-day workshop on Kotlin Coroutines
Kotlin
42
star
65

swift-export-sample

Kotlin to Swift technology preview
Swift
39
star
66

kotlin-playground-wp-plugin

WordPress plugin which allows to embed interactive Kotlin playground to any post via [kotlin] shortcode
PHP
35
star
67

io2019-serverside-demo

E2E Sample
Kotlin
31
star
68

kotlin-jupyter-libraries

Library descriptors for Kotlin kernel for Jupyter
29
star
69

kmm-with-cocoapods-multitarget-xcode-sample

This project is intended to demonstrate how to connect Kotlin library to Xcode project with several targets: iOS, macOS, tvOS, watchOS
Swift
23
star
70

xcode-compat

AppCode helper for Kotlin/Native and Xcode
Kotlin
21
star
71

kotlin-in-action-2e

Code samples for the second edition of "Kotlin in Action".
Kotlin
20
star
72

kotlin-wasm-compose-template

A template repository for Compose Multiplatform with Kotlin/Wasm target
Kotlin
20
star
73

kotlinx.dom

Kotlin
17
star
74

kotlin-wasm-benchmarks

Kotlin Multiplatform Collection of Benchmarks focused on Kotlin/Wasm performance
Kotlin
13
star
75

dokka-plugin-template

Dokka plugin quickstart template with pre-configured dependencies and publishing
Kotlin
12
star
76

kotlinx.team.infra

Kotlin
10
star
77

multiplatform-library-template

Kotlin
10
star
78

kotlin-js-inspection-pack-plugin

Adds useful inspections, intentions, and quick-fixes for working with Kotlin/JS projects.
Kotlin
10
star
79

obsolete-kotlin-swing

Experimental library providing some helper functions and extensions for creating Swing user interfaces.
Kotlin
8
star
80

kotlin-in-action-2e-jkid

Sample project accompanying the second edition of "Kotlin in Action". JSON serialization/deserialization library for Kotlin data classes
Kotlin
8
star
81

kotlin-wasm-browser-template

A template repository for Kotlin/Wasm on browser
HTML
8
star
82

kotlin-spark-shell

Kotlin Language support for Apache Spark
Kotlin
7
star
83

obsolete-kotlin-jdbc

Experimental library providing some helper functions and extensions for working with JDBC in Kotlin.
Kotlin
7
star
84

community-project-gradle-plugin

Kotlin
6
star
85

website-grammar-generator

Kotlin ANTLR grammar converter to XML for the Kotlin website or text file
Kotlin
6
star
86

kotlin-grammar-gpl2

Kotlin grammar ANTLR sources (under GPLv2)
ANTLR
6
star
87

web-site-samples

Examples repository for kotlinlang.org
4
star
88

kotlin-build-report-sample

Kotlin
4
star
89

kotlin-wasm-wasi-template

A template repository for Kotlin/Wasm with WASI
Kotlin
4
star
90

kotlin-jupyter-http-util

Ktor client and serialization for Kotlin Jupyter Notebooks
Kotlin
3
star
91

kotlin-cocoapods-spec

Ruby
3
star
92

analysis-api

Kotlin Analysis API Documentation
3
star
93

kotlin.github.io

Redirect to kotlinlang.org and favicon/title provider for kotlin.github.io/* websites.
HTML
2
star
94

kotlin-wasm-nodejs-template

A template repository for Kotlin/Wasm on Node.js
Kotlin
1
star
95

kmm-with-cocoapods-xcode-two-kotlin-libraries-sample

This project is intended to demonstrate the connection of two Kotlin libraries to existing Xcode project through Cocoapods
Kotlin
1
star