spark-connect 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +82 -0
  3. data/LICENSE +202 -0
  4. data/NOTICE +16 -0
  5. data/README.md +166 -0
  6. data/lib/spark-connect.rb +5 -0
  7. data/lib/spark_connect/arrow.rb +115 -0
  8. data/lib/spark_connect/catalog.rb +190 -0
  9. data/lib/spark_connect/channel_builder.rb +134 -0
  10. data/lib/spark_connect/client.rb +264 -0
  11. data/lib/spark_connect/column.rb +379 -0
  12. data/lib/spark_connect/conf.rb +79 -0
  13. data/lib/spark_connect/data_frame.rb +828 -0
  14. data/lib/spark_connect/errors.rb +58 -0
  15. data/lib/spark_connect/functions.rb +903 -0
  16. data/lib/spark_connect/grouped_data.rb +101 -0
  17. data/lib/spark_connect/na_functions.rb +98 -0
  18. data/lib/spark_connect/observation.rb +61 -0
  19. data/lib/spark_connect/pipelines.rb +221 -0
  20. data/lib/spark_connect/plan.rb +39 -0
  21. data/lib/spark_connect/proto/spark/connect/base_pb.rb +118 -0
  22. data/lib/spark_connect/proto/spark/connect/base_services_pb.rb +82 -0
  23. data/lib/spark_connect/proto/spark/connect/catalog_pb.rb +46 -0
  24. data/lib/spark_connect/proto/spark/connect/commands_pb.rb +67 -0
  25. data/lib/spark_connect/proto/spark/connect/common_pb.rb +32 -0
  26. data/lib/spark_connect/proto/spark/connect/expressions_pb.rb +63 -0
  27. data/lib/spark_connect/proto/spark/connect/ml_common_pb.rb +22 -0
  28. data/lib/spark_connect/proto/spark/connect/ml_pb.rb +32 -0
  29. data/lib/spark_connect/proto/spark/connect/pipelines_pb.rb +45 -0
  30. data/lib/spark_connect/proto/spark/connect/relations_pb.rb +102 -0
  31. data/lib/spark_connect/proto/spark/connect/types_pb.rb +46 -0
  32. data/lib/spark_connect/proto.rb +32 -0
  33. data/lib/spark_connect/reader.rb +98 -0
  34. data/lib/spark_connect/row.rb +105 -0
  35. data/lib/spark_connect/session.rb +317 -0
  36. data/lib/spark_connect/stat_functions.rb +109 -0
  37. data/lib/spark_connect/streaming.rb +351 -0
  38. data/lib/spark_connect/types.rb +490 -0
  39. data/lib/spark_connect/version.rb +11 -0
  40. data/lib/spark_connect/window.rb +119 -0
  41. data/lib/spark_connect/writer.rb +208 -0
  42. data/lib/spark_connect.rb +58 -0
  43. data/proto/spark/connect/base.proto +1275 -0
  44. data/proto/spark/connect/catalog.proto +243 -0
  45. data/proto/spark/connect/commands.proto +553 -0
  46. data/proto/spark/connect/common.proto +179 -0
  47. data/proto/spark/connect/expressions.proto +557 -0
  48. data/proto/spark/connect/ml.proto +147 -0
  49. data/proto/spark/connect/ml_common.proto +64 -0
  50. data/proto/spark/connect/pipelines.proto +307 -0
  51. data/proto/spark/connect/relations.proto +1252 -0
  52. data/proto/spark/connect/types.proto +227 -0
  53. metadata +149 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ad83f60b70501f49722aa4ae51d768d27accbeb056c7f6fe1be695e010116c52
4
+ data.tar.gz: 528b67cacc0ba1b516aa93228c242d07efcaa86ae297d75c9c11c9d36905a00f
5
+ SHA512:
6
+ metadata.gz: ceb4e18bcc75a30a38fe4c2446ae192f07a24446f86b5a76b9992b4f6a70e59bfb3d4709f633988eacd00fa85d174b8904b80eb291855dc943a7c8e10f9c7f4d
7
+ data.tar.gz: e06a6c98eee8042f56aabc5689655ad8bb7b04c843d90d2093d24fc6c82247993c0e47b002125ab774b1ce87c0e3b4203a88de6864a0c3dde1b45e7236db29f0
data/CHANGELOG.md ADDED
@@ -0,0 +1,82 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.2.0] - 2026-06-10
11
+
12
+ ### Added
13
+
14
+ - **Declarative Pipelines** (Spark 4.1+): `SparkSession#pipeline` returns a
15
+ `Pipeline` (dataflow graph). Define outputs (`create_table`,
16
+ `create_materialized_view`, `create_temporary_view`, `create_sink`) and flows
17
+ (`define_flow`, `define_sql`), then `start_run` (with `full_refresh`/`refresh`/
18
+ `dry`/`storage`) which streams `PipelineEvent`s; plus `read` and `drop`.
19
+ - **Structured Streaming**: `SparkSession#read_stream` (`DataStreamReader`),
20
+ `DataFrame#write_stream` (`DataStreamWriter`), `StreamingQuery` (status,
21
+ recent/last progress, await_termination, process_all_available, stop,
22
+ exception, explain), and `SparkSession#streams` (`StreamingQueryManager`:
23
+ active, get, await_any_termination, reset_terminated). Supports triggers
24
+ (processing-time, once, available-now, continuous), output modes, and
25
+ file/console/memory/Kafka sinks. (`foreach`/`foreachBatch` and UDFs remain
26
+ unsupported pending finalized protobuf definitions.)
27
+ - Temporary views: `DataFrame#create_temp_view` /
28
+ `create_or_replace_temp_view` / `create_global_temp_view` /
29
+ `create_or_replace_global_temp_view`.
30
+ - `DataFrame#with_watermark`, `repartition_by_range`, `checkpoint` /
31
+ `local_checkpoint`, `transform`, `col_regex`, `to_json`, and
32
+ `each` / `to_local_iterator`.
33
+ - `Catalog#create_table` and `Catalog#create_external_table`.
34
+ - `SparkSession#new_session`, `interrupt_all` / `interrupt_tag` /
35
+ `interrupt_operation`, and operation tags (`add_tag` / `remove_tag` /
36
+ `get_tags` / `clear_tags`) propagated on every execution.
37
+ - Regenerated the vendored protobuf/gRPC stubs against Spark Connect **4.1.0**
38
+ (adds `pipelines.proto`).
39
+ - `bin/console` (an IRB session with `spark`/`F`/`T`) and `bin/setup`.
40
+
41
+ ## [0.1.0] - 2026-06-10
42
+
43
+ Initial release.
44
+
45
+ ### Added
46
+
47
+ - `SparkConnect::SparkSession` and its fluent `Builder` (`remote`, `app_name`,
48
+ `config`, `get_or_create`/`create`), plus `range`, `sql`, `table`, `read`,
49
+ `create_data_frame`, `conf`, `catalog`, `version`, and `stop`.
50
+ - `SparkConnect::DataFrame` with the core transformation and action surface:
51
+ `select`/`select_expr`, `filter`/`where`, `with_column(s)`,
52
+ `with_column(s)_renamed`, `drop`, `distinct`/`drop_duplicates`,
53
+ `order_by`/`sort`/`sort_within_partitions`, `limit`/`offset`,
54
+ `group_by`/`rollup`/`cube`/`agg`, `join`/`cross_join`,
55
+ `union`/`union_by_name`/`intersect`/`except`/`subtract`,
56
+ `repartition`/`coalesce`, `sample`, `alias`, `hint`, `unpivot`, `to`/`to_df`,
57
+ `collect`/`take`/`head`/`first`/`count`/`show`/`to_arrow`, and plan
58
+ introspection (`schema`, `columns`, `dtypes`, `print_schema`, `explain`).
59
+ - `SparkConnect::Column` with Ruby operator overloads, aliasing, casting,
60
+ sort ordering, predicates, `when`/`otherwise`, complex-type access, and `over`.
61
+ - `SparkConnect::Functions` (`F`): a broad PySpark-compatible function library
62
+ including aggregate, math, string, date/time, collection, JSON, conditional,
63
+ hashing, and higher-order (lambda) functions.
64
+ - `SparkConnect::Window`/`WindowSpec` for analytic window definitions.
65
+ - `SparkConnect::GroupedData`, `DataFrameNaFunctions` (`na`),
66
+ `DataFrameStatFunctions` (`stat`), and `Observation`.
67
+ - `SparkConnect::DataFrameReader`, `DataFrameWriter`, and `DataFrameWriterV2`.
68
+ - `SparkConnect::Catalog` and `SparkConnect::RuntimeConfig`.
69
+ - `SparkConnect::Types`: a full Spark SQL type system with proto conversion,
70
+ `simpleString`/DDL/JSON rendering, and schema trees.
71
+ - `SparkConnect::Row` with positional, by-name, and method-style access.
72
+ - Apache Arrow IPC result decoding and local-relation encoding via `red-arrow`.
73
+ - gRPC client (`SparkConnectClient`, `ChannelBuilder`) with `sc://` connection
74
+ string parsing, TLS/bearer-token auth, and retry-with-backoff.
75
+ - A structured error hierarchy (`Error`, `ConnectionError`, `SparkConnectError`,
76
+ `AnalysisError`, `ParseError`, ...).
77
+ - Vendored Spark Connect 4.1 protobuf/gRPC definitions and a regeneration script
78
+ (`bin/generate-protos`).
79
+
80
+ [Unreleased]: https://github.com/HyukjinKwon/spark-connect-ruby/compare/v0.2.0...HEAD
81
+ [0.2.0]: https://github.com/HyukjinKwon/spark-connect-ruby/compare/v0.1.0...v0.2.0
82
+ [0.1.0]: https://github.com/HyukjinKwon/spark-connect-ruby/releases/tag/v0.1.0
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/NOTICE ADDED
@@ -0,0 +1,16 @@
1
+ spark-connect (Ruby client for Apache Spark Connect)
2
+ Copyright 2026 The spark-connect-ruby authors
3
+
4
+ This product includes software developed as part of the
5
+ Apache Spark project (https://spark.apache.org/).
6
+
7
+ The Protocol Buffers definitions under proto/spark/connect/ are vendored from
8
+ Apache Spark (https://github.com/apache/spark), which is licensed under the
9
+ Apache License, Version 2.0:
10
+
11
+ Apache Spark
12
+ Copyright 2014 and onwards The Apache Software Foundation.
13
+
14
+ This product is not affiliated with, endorsed by, or sponsored by the Apache
15
+ Software Foundation. "Apache", "Apache Spark", and "Spark" are trademarks of the
16
+ Apache Software Foundation.
data/README.md ADDED
@@ -0,0 +1,166 @@
1
+ # spark-connect (Ruby)
2
+
3
+ [![CI](https://github.com/HyukjinKwon/spark-connect-ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/HyukjinKwon/spark-connect-ruby/actions/workflows/ci.yml)
4
+ [![Gem Version](https://badge.fury.io/rb/spark-connect.svg)](https://rubygems.org/gems/spark-connect)
5
+ [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://hyukjinkwon.github.io/spark-connect-ruby/)
6
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
7
+
8
+ A pure-Ruby client for **[Apache Spark Connect](https://spark.apache.org/docs/latest/spark-connect-overview.html)** - the gRPC-based, decoupled client/server protocol for Apache Spark.
9
+
10
+ `spark-connect` lets you build and run Spark DataFrame queries from Ruby against a remote Spark cluster, with an API that closely mirrors PySpark. No JVM, no local Spark installation, no `spark-submit` - just a gRPC connection to a Spark Connect server.
11
+
12
+ ```ruby
13
+ require "spark-connect"
14
+
15
+ spark = SparkConnect::SparkSession.builder
16
+ .remote("sc://localhost:15002")
17
+ .get_or_create
18
+
19
+ F = SparkConnect::F
20
+
21
+ spark.range(1, 1_000)
22
+ .select(F.col("id"), (F.col("id") % 3).alias("bucket"))
23
+ .group_by("bucket")
24
+ .agg(F.count("*").alias("n"), F.sum("id").alias("total"))
25
+ .order_by("bucket")
26
+ .show
27
+
28
+ spark.stop
29
+ ```
30
+
31
+ ```
32
+ +------+---+------+
33
+ |bucket| n| total|
34
+ +------+---+------+
35
+ | 0|333|166833|
36
+ | 1|333|166167|
37
+ | 2|333|166500|
38
+ +------+---+------+
39
+ ```
40
+
41
+ ## What it supports
42
+
43
+ `spark-connect` implements the Spark Connect **DataFrame**, **SQL**,
44
+ **Structured Streaming**, and **Declarative Pipelines** API -- everything
45
+ **except** user-defined functions (UDFs) and the `foreach`/`foreachBatch`
46
+ streaming sinks, whose Spark Connect protobuf definitions are not yet finalized.
47
+ (The separate, experimental MLlib-over-Connect surface is also out of scope.)
48
+
49
+ Results decode through Apache Arrow into ordered, name-addressable `Row`s.
50
+ Method names are snake_case (idiomatic Ruby) with camelCase aliases for the
51
+ common PySpark names (`groupBy`, `withColumn`, `orderBy`, `createDataFrame`,
52
+ ...), so PySpark code ports almost verbatim.
53
+
54
+ ## Requirements
55
+
56
+ - **Ruby >= 3.1**
57
+ - **Apache Arrow C++/GLib system libraries** (required by the `red-arrow` dependency):
58
+ - macOS: `brew install apache-arrow apache-arrow-glib`
59
+ - Ubuntu/Debian: install `libarrow-glib-dev` from the [Apache Arrow APT repository](https://arrow.apache.org/install/)
60
+ - A reachable **Spark Connect server**. This client is generated against the Spark Connect 4.1 protocol and supports **Apache Spark 3.5 and above**.
61
+
62
+ See the [installation guide](https://hyukjinkwon.github.io/spark-connect-ruby/installation.html) for details.
63
+
64
+ ## Installation
65
+
66
+ ```bash
67
+ gem install spark-connect
68
+ ```
69
+
70
+ Or in a `Gemfile`:
71
+
72
+ ```ruby
73
+ gem "spark-connect"
74
+ ```
75
+
76
+ ## Running a local Spark Connect server
77
+
78
+ ```bash
79
+ # Download a Spark distribution (4.1.0 shown here; 3.5+ also works)
80
+ curl -fsSL https://archive.apache.org/dist/spark/spark-4.1.0/spark-4.1.0-bin-hadoop3.tgz | tar xz
81
+ cd spark-4.1.0-bin-hadoop3
82
+
83
+ # Start the Connect server (requires Java 17+)
84
+ ./sbin/start-connect-server.sh --jars "$(pwd)/jars/spark-connect_2.13-4.1.0.jar"
85
+ ```
86
+
87
+ The server listens on `sc://localhost:15002` by default.
88
+
89
+ ## Connecting
90
+
91
+ Connection strings follow the standard Spark Connect grammar:
92
+
93
+ ```ruby
94
+ # Plaintext, local
95
+ SparkConnect::SparkSession.builder.remote("sc://localhost:15002").get_or_create
96
+
97
+ # TLS + bearer token (token implies SSL)
98
+ SparkConnect::SparkSession.builder
99
+ .remote("sc://spark.example.com:443/;token=#{ENV['SPARK_TOKEN']};user_id=alice")
100
+ .get_or_create
101
+ ```
102
+
103
+ Supported parameters: `token`, `user_id`, `user_agent`, `use_ssl`, `session_id`, and any `x-*` custom gRPC headers.
104
+
105
+ ## A quick tour
106
+
107
+ ```ruby
108
+ F = SparkConnect::F
109
+ T = SparkConnect::Types
110
+
111
+ # Build a DataFrame from local Ruby data
112
+ df = spark.create_data_frame([
113
+ { "name" => "alice", "dept" => "eng", "salary" => 120 },
114
+ { "name" => "bob", "dept" => "eng", "salary" => 100 },
115
+ { "name" => "carol", "dept" => "ops", "salary" => 110 },
116
+ ])
117
+
118
+ # Transform and aggregate
119
+ df.where(F.col("salary") >= 105)
120
+ .group_by("dept")
121
+ .agg(F.avg("salary").alias("avg_salary"), F.count("*").alias("headcount"))
122
+ .order_by(F.col("avg_salary").desc)
123
+ .show
124
+
125
+ # Window functions
126
+ w = SparkConnect::Window.partition_by("dept").order_by(F.col("salary").desc)
127
+ df.with_column("rank", F.rank.over(w)).show
128
+
129
+ # Schemas
130
+ df.print_schema
131
+ df.schema.simple_string #=> "struct<name:string,dept:string,salary:bigint>"
132
+
133
+ # SQL with parameters
134
+ spark.sql("SELECT * FROM VALUES (1), (2), (3) AS t(x) WHERE x > :min", { min: 1 }).show
135
+ ```
136
+
137
+ ## Documentation
138
+
139
+ Full documentation, including guides for every part of the API, lives at
140
+ **<https://hyukjinkwon.github.io/spark-connect-ruby/>**.
141
+
142
+ Runnable [`examples/`](examples/) cover quickstart, transformations, aggregations, joins, window functions, SQL, reading/writing, local data, and NA/stat helpers.
143
+
144
+ ## Compatibility
145
+
146
+ The client is generated against the **Spark Connect 4.1** protocol and supports **Apache Spark 3.5 and above** (the Spark Connect wire protocol is backward compatible across these releases).
147
+
148
+ ## Development
149
+
150
+ ```bash
151
+ git clone https://github.com/HyukjinKwon/spark-connect-ruby
152
+ cd spark-connect-ruby
153
+ bundle install
154
+
155
+ bundle exec rake spec # unit specs (no server required)
156
+ bundle exec rake rubocop # lint
157
+ bundle exec rake yard # API docs
158
+
159
+ # Integration specs against a live server
160
+ SPARK_REMOTE=sc://localhost:15002 bundle exec rspec spec/integration
161
+
162
+ # Regenerate the protobuf/gRPC stubs from the vendored .proto files
163
+ bin/generate-protos
164
+ ```
165
+
166
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Convenience entry point matching the gem name (`require "spark-connect"`).
4
+ # Delegates to the canonical namespace file.
5
+ require_relative "spark_connect"
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "arrow"
4
+
5
+ module SparkConnect
6
+ # Decodes the Apache Arrow IPC stream payloads returned by the server into
7
+ # Ruby {Row}s. Each `ExecutePlanResponse.arrow_batch.data` chunk is a complete,
8
+ # self-contained Arrow IPC stream (schema + record batches); this converter
9
+ # reads each chunk and flattens all record batches into rows.
10
+ #
11
+ # Named `ArrowConverter` (not `Arrow`) so that references to the `red-arrow`
12
+ # top-level {Arrow} constant inside the gem are unambiguous.
13
+ module ArrowConverter
14
+ module_function
15
+
16
+ # Decode IPC stream chunks into rows.
17
+ #
18
+ # @param batches [Array<String>] Arrow IPC stream byte chunks.
19
+ # @return [Array<Row>]
20
+ def to_rows(batches)
21
+ rows = []
22
+ field_names = nil
23
+ batches.each do |data|
24
+ next if data.nil? || data.empty?
25
+
26
+ reader = ::Arrow::RecordBatchStreamReader.new(::Arrow::BufferInputStream.new(::Arrow::Buffer.new(data)))
27
+ reader.each do |record_batch|
28
+ field_names ||= record_batch.schema.fields.map(&:name)
29
+ record_batch.raw_records.each do |values|
30
+ rows << Row.new(values, fields: field_names)
31
+ end
32
+ end
33
+ end
34
+ rows
35
+ end
36
+
37
+ # Decode IPC stream chunks into a single Arrow Table (for advanced/columnar
38
+ # consumers who want zero-copy access to the underlying data).
39
+ #
40
+ # @param batches [Array<String>]
41
+ # @return [Arrow::Table, nil]
42
+ def to_table(batches)
43
+ tables = batches.reject { |b| b.nil? || b.empty? }.map do |data|
44
+ ::Arrow::RecordBatchStreamReader.new(::Arrow::BufferInputStream.new(::Arrow::Buffer.new(data))).read_all
45
+ end
46
+ return nil if tables.empty?
47
+
48
+ tables.reduce { |acc, t| acc.concatenate([t]) }
49
+ end
50
+
51
+ # Serialize an array of Ruby hashes into a single Arrow IPC stream given a
52
+ # Spark {Types::StructType}. Used by {SparkSession#create_data_frame} to ship
53
+ # local data to the server as a `LocalRelation`.
54
+ #
55
+ # @param rows [Array<Hash, Array, Row>]
56
+ # @param schema [Types::StructType]
57
+ # @return [String] Arrow IPC stream bytes.
58
+ def from_rows(rows, schema)
59
+ arrow_schema = build_arrow_schema(schema)
60
+ raw_rows = rows.map do |row|
61
+ schema.fields.each_with_index.map { |field, idx| extract_value(row, field.name, idx) }
62
+ end
63
+ record_batch = ::Arrow::RecordBatch.new(arrow_schema, raw_rows)
64
+ buffer = ::Arrow::ResizableBuffer.new(1024)
65
+ ::Arrow::BufferOutputStream.open(buffer) do |output|
66
+ ::Arrow::RecordBatchStreamWriter.open(output, arrow_schema) do |writer|
67
+ writer.write_record_batch(record_batch)
68
+ end
69
+ end
70
+ buffer.data.to_s
71
+ end
72
+
73
+ def build_arrow_schema(schema)
74
+ fields = schema.fields.map do |f|
75
+ ::Arrow::Field.new(f.name, arrow_field_type(f.data_type))
76
+ end
77
+ ::Arrow::Schema.new(fields)
78
+ end
79
+
80
+ def extract_value(row, name, idx)
81
+ case row
82
+ when Row then row[name]
83
+ when Hash
84
+ if row.key?(name) then row[name]
85
+ elsif row.key?(name.to_sym) then row[name.to_sym]
86
+ end
87
+ when Array then row[idx]
88
+ else row
89
+ end
90
+ end
91
+
92
+ # Map a Spark type to the corresponding `red-arrow` data type used when
93
+ # building local relations.
94
+ def arrow_field_type(data_type)
95
+ case data_type
96
+ when Types::BooleanType then :boolean
97
+ when Types::ByteType then :int8
98
+ when Types::ShortType then :int16
99
+ when Types::IntegerType then :int32
100
+ when Types::LongType then :int64
101
+ when Types::FloatType then :float
102
+ when Types::DoubleType then :double
103
+ when Types::StringType, Types::CharType, Types::VarcharType then :string
104
+ when Types::BinaryType then :binary
105
+ when Types::DateType then :date32
106
+ when Types::TimestampType, Types::TimestampNTZType then { type: :timestamp, unit: :micro }
107
+ when Types::ArrayType
108
+ { type: :list, field: { name: "element", type: arrow_field_type(data_type.element_type) } }
109
+ when Types::StructType
110
+ { type: :struct, fields: data_type.fields.map { |f| { name: f.name, type: arrow_field_type(f.data_type) } } }
111
+ else :string # rubocop:disable Lint/DuplicateBranch -- string default for unsupported-locally types
112
+ end
113
+ end
114
+ end
115
+ end