This is an automated email from the ASF dual-hosted git repository. jmalkin pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/datasketches-spark.git
commit 1cebabcd617e4c78daaa7a60a457db71a8a2a175 Author: Jon Malkin <[email protected]> AuthorDate: Fri Dec 20 12:45:05 2024 -0800 Initial commit --- .asf.yaml | 8 + .gitignore | 73 +++++++ LICENSE | 210 +++++++++++++++++++ NOTICE | 7 + README.md | 24 +++ build.sbt | 57 ++++++ .../apache/spark/sql/aggregate/KllAggregate.scala | 147 ++++++++++++++ .../org/apache/spark/sql/aggregate/KllMerge.scala | 154 ++++++++++++++ .../spark/sql/expressions/KllExpressions.scala | 224 +++++++++++++++++++++ .../scala/org/apache/spark/sql/functions_ds.scala | 155 ++++++++++++++ .../registrar/DatasketchesFunctionRegistry.scala | 85 ++++++++ .../spark/sql/types/KllDoublesSketchType.scala | 37 ++++ .../spark/sql/types/KllDoublesSketchWrapper.scala | 47 +++++ src/test/scala/org/apache/spark/sql/KllTest.scala | 210 +++++++++++++++++++ .../org/apache/spark/sql/SparkSessionManager.scala | 41 ++++ 15 files changed, 1479 insertions(+) diff --git a/.asf.yaml b/.asf.yaml new file mode 100644 index 0000000..daa5a02 --- /dev/null +++ b/.asf.yaml @@ -0,0 +1,8 @@ +github: + homepage: https://datasketches.apache.org + ghp_branch: gh-pages + ghp_path: /docs + + features: + # Enable issue management + issues: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fe02d20 --- /dev/null +++ b/.gitignore @@ -0,0 +1,73 @@ +# VSCode +.vscode/ + +# Eclipse project files +.classpath +.project +.settings/ +.checkstyle + +# IntelliJ project files +*.idea +**/*.iml +*.ipr +*.iws + +# Scala project files and related plugins +target/ +project/ +.bsp/ +.bloop/ +.metals/ +.scala-build/ + +# OSX files +**/.DS_Store + +# Compiler output, class files +*.class +bin/ + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +#Test config and output +test-output/ +local/ +reports/ +.pmd +tmp/ + +# Build artifacts +target/ +serialization_test_data/ +out/ +build/ +jarsIn/ +build.xml +*.properties +*.releaseBackup +*.next +*.tag +doc/ + + +# Sketch binary test files +*.sk \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..51e907d --- /dev/null +++ b/LICENSE @@ -0,0 +1,210 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + + +APPENDIX A: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + ------------------------------------------------------------- + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ------------------------------------------------------------- + + +APPENDIX B: Additional licenses relevant to this product: + + (None) \ No newline at end of file diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..6532873 --- /dev/null +++ b/NOTICE @@ -0,0 +1,7 @@ +Apache DataSketches BigQuery +Copyright 2024 The Apache Software Foundation + +Copyright 2024- Yahoo Inc. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/README.md b/README.md new file mode 100644 index 0000000..6131f41 --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +# Apache<sup>®</sup> DataSketches™ Spark Library + +This repo is still an early-stage work in progress. + +There have been multiple attempts to help integrate Apache DataSketches into Apache Spark, including one built into Spark itself as of v3.5. All are useful work, but in comparing them, there are various limitations to each library. Whether limitng the type of sketches available (e.g. native Spark provides only HLL) or limiting flexibility and functionality (e.g. forcing HLL and Theta to use a common interface which precludes set operations HLL cannot support, or using global parameters t [...] diff --git a/build.sbt b/build.sbt new file mode 100644 index 0000000..daa4c63 --- /dev/null +++ b/build.sbt @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +name := "datasketches-spark" +version := "1.0-SNAPSHOT" +scalaVersion := "2.12.20" + +organization := "org.apache.datasketches" +description := "The Apache DataSketches package for Spark" + +licenses += ("Apache-2.0", url("http://www.apache.org/licenses/LICENSE-2.0")) + +// these do not impact code generation in spark +javacOptions ++= Seq("-source", "17", "-target", "17") +scalacOptions ++= Seq("-encoding", "UTF-8", "-release", "11") +Test / javacOptions ++= Seq("-source", "17", "-target", "17") +Test / scalacOptions ++= Seq("-encoding", "UTF-8", "-release", "11") + +libraryDependencies ++= Seq( + "org.scala-lang" % "scala-library" % "2.12.6", + "org.apache.spark" %% "spark-sql" % "3.4.4" % "provided", + "org.apache.datasketches" % "datasketches-java" % "6.1.1" % "compile", + "org.scalatest" %% "scalatest" % "3.2.19" % "test", + "org.scalatestplus" %% "junit-4-13" % "3.2.19.0" % "test" +) + +Test / testOptions += Tests.Argument(TestFrameworks.ScalaTest, "-oD") + +scalacOptions ++= Seq( + "-deprecation", + "-feature", + "-unchecked", + "-Xlint" +) + +Test / logBuffered := false + +// Only show warnings and errors on the screen for compilations. +// This applies to both test:compile and compile and is Info by default +Compile / logLevel := Level.Warn + +// Level.INFO is needed to see detailed output when running tests +Test / logLevel := Level.Info diff --git a/src/main/scala/org/apache/spark/sql/aggregate/KllAggregate.scala b/src/main/scala/org/apache/spark/sql/aggregate/KllAggregate.scala new file mode 100644 index 0000000..1cea930 --- /dev/null +++ b/src/main/scala/org/apache/spark/sql/aggregate/KllAggregate.scala @@ -0,0 +1,147 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.aggregate + +import org.apache.datasketches.kll.{KllSketch, KllDoublesSketch} +import org.apache.spark.SparkUnsupportedOperationException +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{ExpectsInputTypes, Expression, ExpressionDescription, Literal} +import org.apache.spark.sql.catalyst.expressions.aggregate.TypedImperativeAggregate +import org.apache.spark.sql.catalyst.trees.BinaryLike +import org.apache.spark.sql.types.{AbstractDataType, DataType, IntegerType, LongType, NumericType, FloatType, DoubleType, KllDoublesSketchWrapper, KllDoublesSketchType} + +/** + * The KllDoublesSketchAgg function utilizes a Datasketches KllDoublesSketch instance + * to create a sketch from a column of values which can be used to estimate quantiles + * and histograms. + * + * @param child child expression against which unique counting will occur + * @param k the size-accraucy trade-off parameter for the sketch + */ +// scalastyle:off line.size.limit +@ExpressionDescription( + usage = """ + _FUNC_(expr, k) - Creates a KllDoublesSketch and returns the binary representation. + `k` (optional, default: 200) the size-accuracy trade-off parameter.""", + examples = """ + Examples: + > SELECT kll_get_quantile(_FUNC_(col, 200), 0.5) FROM VALUES (1.0), (1.0), (2.0), (2.0), (3.0) tab(col); + 2.0 + """, +) +// scalastyle:on line.size.limit +case class KllDoublesSketchAgg( + left: Expression, + right: Expression, + mutableAggBufferOffset: Int = 0, + inputAggBufferOffset: Int = 0) + extends TypedImperativeAggregate[KllDoublesSketchWrapper] + with BinaryLike[Expression] + with ExpectsInputTypes { + + lazy val k: Int = { + right.eval() match { + case null => KllSketch.DEFAULT_K + case k: Int => k + case _ => throw new SparkUnsupportedOperationException( + s"Unsupported input type ${right.dataType.catalogString}", + Map("dataType" -> dataType.toString)) + } + } + + // Constructors + + def this(child: Expression) = { + this(child, Literal(KllSketch.DEFAULT_K), 0, 0) + } + + def this(child: Expression, k: Expression) = { + this(child, k, 0, 0) + } + + def this(child: Expression, k: Int) = { + this(child, Literal(k), 0, 0) + } + + // Copy constructors + + override def withNewMutableAggBufferOffset(newMutableAggBufferOffset: Int): KllDoublesSketchAgg = + copy(mutableAggBufferOffset = newMutableAggBufferOffset) + + override def withNewInputAggBufferOffset(newInputAggBufferOffset: Int): KllDoublesSketchAgg = + copy(inputAggBufferOffset = newInputAggBufferOffset) + + override protected def withNewChildrenInternal(newLeft: Expression, + newRight: Expression): KllDoublesSketchAgg = { + copy(left = newLeft, right = newRight) + } + + // overrides for TypedImperativeAggregate + override def prettyName: String = "kll_sketch_agg" + + override def dataType: DataType = KllDoublesSketchType + + override def nullable: Boolean = false + + override def inputTypes: Seq[AbstractDataType] = Seq(NumericType, IntegerType, LongType, FloatType, DoubleType) + + // create buffer + override def createAggregationBuffer(): KllDoublesSketchWrapper = new KllDoublesSketchWrapper(KllDoublesSketch.newHeapInstance(k)) + + // update + override def update(wrapper: KllDoublesSketchWrapper, input: InternalRow): KllDoublesSketchWrapper = { + val value = left.eval(input) + if (value != null) { + left.dataType match { + case DoubleType => wrapper.sketch.update(value.asInstanceOf[Double]) + case FloatType => wrapper.sketch.update(value.asInstanceOf[Float].toDouble) + case IntegerType => wrapper.sketch.update(value.asInstanceOf[Int].toDouble) + case LongType => wrapper.sketch.update(value.asInstanceOf[Long].toDouble) + case _ => throw new SparkUnsupportedOperationException( + s"Unsupported input type ${left.dataType.catalogString}", + Map("dataType" -> dataType.toString)) + } + } + wrapper + } + + // union (merge) + override def merge(wrapper: KllDoublesSketchWrapper, other: KllDoublesSketchWrapper): KllDoublesSketchWrapper = { + if (other != null && !other.sketch.isEmpty) { + wrapper.sketch.merge(other.sketch) + } + wrapper + } + + // eval + override def eval(wrapper: KllDoublesSketchWrapper): Any = { + if (wrapper == null || wrapper.sketch.isEmpty) { + null + } else { + wrapper.toByteArray + } + } + + override def serialize(wrapper: KllDoublesSketchWrapper): Array[Byte] = { + KllDoublesSketchType.serialize(wrapper) + } + + override def deserialize(bytes: Array[Byte]): KllDoublesSketchWrapper = { + KllDoublesSketchType.deserialize(bytes) + } +} diff --git a/src/main/scala/org/apache/spark/sql/aggregate/KllMerge.scala b/src/main/scala/org/apache/spark/sql/aggregate/KllMerge.scala new file mode 100644 index 0000000..67db2cc --- /dev/null +++ b/src/main/scala/org/apache/spark/sql/aggregate/KllMerge.scala @@ -0,0 +1,154 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.aggregate + +import org.apache.datasketches.kll.{KllSketch, KllDoublesSketch} + +import org.apache.spark.SparkUnsupportedOperationException +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{ExpectsInputTypes, Expression, ExpressionDescription} +import org.apache.spark.sql.catalyst.expressions.aggregate.TypedImperativeAggregate +import org.apache.spark.sql.catalyst.trees.UnaryLike +import org.apache.spark.sql.types.{AbstractDataType, DataType, KllDoublesSketchWrapper, KllDoublesSketchType} +import org.apache.datasketches.memory.Memory + +/** + * The KllDoublesMergeAgg function utilizes a Datasketches KllDoublesSketch instance to + * combine multiple sketches into a single sketch. + * + * See [[https://datasketches.apache.org/docs/HLL/HLL.html]] for more information. + * + * @param child child expression against which unique counting will occur + */ +// scalastyle:off line.size.limit +@ExpressionDescription( + usage = """ + _FUNC_(expr, k) - Merges multiple KllDoublesSketch images and returns the binary representation + """, + examples = """ + Examples: + > SELECT kll_get_quantile(_FUNC_(sketch), 0.5) FROM (SELECT kll_sketch_agg(col) as sketch FROM VALUES (1.0), (2.0) tab(col) UNION ALL SELECT kll_sketch_agg(col) as sketch FROM VALUES (2.0), (3.0) tab(col)); + 2.0 + """, + //group = "agg_funcs", +) +// scalastyle:on line.size.limit +case class KllDoublesMergeAgg( + child: Expression, + mutableAggBufferOffset: Int = 0, + inputAggBufferOffset: Int = 0) + extends TypedImperativeAggregate[Option[KllDoublesSketchWrapper]] + with UnaryLike[Expression] + with ExpectsInputTypes { + + // Constructors + + // this seems redundant given the constructor? + def this(child: Expression) = this(child, 0, 0) + + // Copy constructors + + override def withNewMutableAggBufferOffset(newMutableAggBufferOffset: Int): KllDoublesMergeAgg = + copy(mutableAggBufferOffset = newMutableAggBufferOffset) + + override def withNewInputAggBufferOffset(newInputAggBufferOffset: Int): KllDoublesMergeAgg = + copy(inputAggBufferOffset = newInputAggBufferOffset) + + override protected def withNewChildInternal(newChild: Expression): KllDoublesMergeAgg = + copy(child = newChild) + + + // overrides for TypedImperativeAggregate + override def prettyName: String = "kll_merge_agg" + + override def dataType: DataType = KllDoublesSketchType + + override def nullable: Boolean = false + + // TODO: refine this? + override def inputTypes: Seq[AbstractDataType] = Seq(KllDoublesSketchType) + + // create buffer + override def createAggregationBuffer(): Option[KllDoublesSketchWrapper] = { + None + } + + // update + override def update(unionOption: Option[KllDoublesSketchWrapper], input: InternalRow): Option[KllDoublesSketchWrapper] = { + val value = child.eval(input) + if (value != null && value != None) { + child.dataType match { + case KllDoublesSketchType => + if (unionOption == None || unionOption.get.sketch.isEmpty) { + // if union is empty, just return a copy of the input sketch + // TODO: is this serialized or already as a sketch object? + //Some(KllDoublesSketch.heapify(Memory.wrap(value.asInstanceOf[Array[Byte]]))) + Some(KllDoublesSketchWrapper.deserialize(value.asInstanceOf[Array[Byte]])) + } else { + unionOption.get.sketch.merge(KllDoublesSketch.wrap(Memory.wrap(value.asInstanceOf[Array[Byte]]))) + unionOption + } + case _ => throw new SparkUnsupportedOperationException( + s"Unsupported input type ${child.dataType.catalogString}", + Map("dataType" -> dataType.toString)) + } + } else { + unionOption + } + } + + // union (merge) + override def merge(unionOption: Option[KllDoublesSketchWrapper], otherOption: Option[KllDoublesSketchWrapper]): Option[KllDoublesSketchWrapper] = { + (unionOption, otherOption) match { + case (Some(union), Some(other)) => + union.sketch.merge(other.sketch) + Some(union) + + // for these others, we'll return the input even if degenerate + case (Some(union), None) => + unionOption + case (None, Some(other)) => + otherOption + case (None, None) => + unionOption + } + } + + // eval + override def eval(unionOption: Option[KllDoublesSketchWrapper]): Any = { + unionOption match { + case Some(wrapper) => wrapper.sketch.toByteArray + case None => None // can this happen in practice? If so, what should we return? + } + } + + override def serialize(sketchOption: Option[KllDoublesSketchWrapper]): Array[Byte] = { + sketchOption match { + case Some(wrapper) => wrapper.sketch.toByteArray + case None => KllDoublesSketch.newHeapInstance(KllSketch.DEFAULT_K).toByteArray + } + } + + override def deserialize(bytes: Array[Byte]): Option[KllDoublesSketchWrapper] = { + if (bytes.length > 0) { + Some(KllDoublesSketchType.deserialize(bytes)) + } else { + None + } + } +} diff --git a/src/main/scala/org/apache/spark/sql/expressions/KllExpressions.scala b/src/main/scala/org/apache/spark/sql/expressions/KllExpressions.scala new file mode 100644 index 0000000..df2aa2f --- /dev/null +++ b/src/main/scala/org/apache/spark/sql/expressions/KllExpressions.scala @@ -0,0 +1,224 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.expressions + +import org.apache.datasketches.memory.Memory +import org.apache.datasketches.kll.KllDoublesSketch +import org.apache.spark.sql.catalyst.expressions.{Expression, ExpectsInputTypes, UnaryExpression, BinaryExpression} +import org.apache.spark.sql.types.{AbstractDataType, DataType, ArrayType, DoubleType, KllDoublesSketchType} +import org.apache.spark.sql.catalyst.expressions.NullIntolerant +import org.apache.spark.sql.catalyst.expressions.codegen.{CodeBlock, CodegenContext, ExprCode} +import org.apache.datasketches.quantilescommon.QuantileSearchCriteria +import org.apache.spark.sql.catalyst.util.GenericArrayData +import org.apache.spark.sql.catalyst.expressions.ExpressionDescription +import org.apache.spark.sql.catalyst.expressions.ImplicitCastInputTypes + +@ExpressionDescription( + usage = """ + _FUNC_(expr) - Returns the minimum value seem by the sketch given the binary representation + of a Datasketches KllDoublesSketch. """, + examples = """ + Examples: + > SELECT _FUNC_(kll_sketch_agg(col)) FROM VALUES (1.0), (2.0), (3.0) tab(col); + 1.0 + """ + //group = "misc_funcs", +) +case class KllGetMin(child: Expression) + extends UnaryExpression + with ExpectsInputTypes + with NullIntolerant { + + override protected def withNewChildInternal(newChild: Expression): KllGetMin = { + copy(child = newChild) + } + + override def prettyName: String = "kll_get_min" + + override def inputTypes: Seq[AbstractDataType] = Seq(KllDoublesSketchType) + + override def dataType: DataType = DoubleType + + override def nullSafeEval(input: Any): Any = { + val bytes = input.asInstanceOf[Array[Byte]] + val sketch = KllDoublesSketch.wrap(Memory.wrap(bytes)) + sketch.getMinItem + } + + override protected def nullSafeCodeGen(ctx: CodegenContext, ev: ExprCode, f: String => String): ExprCode = { + val childEval = child.genCode(ctx) + val sketch = ctx.freshName("sketch") + + val code = + s""" + |${childEval.code} + |final org.apache.datasketches.kll.KllDoublesSketch $sketch = org.apache.spark.sql.types.KllDoublesSketchWrapper.wrapAsReadOnlySketch(${childEval.value}); + |final double ${ev.value} = $sketch.getMinItem(); + """.stripMargin + ev.copy(code = CodeBlock(Seq(code), Seq.empty), isNull = childEval.isNull) + } + + override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { + nullSafeCodeGen(ctx, ev, c => s"($c)") + } +} + +@ExpressionDescription( + usage = """ + _FUNC_(expr) - Returns the maximum value seem by the sketch given the binary representation + of a Datasketches KllDoublesSketch. """, + examples = """ + Examples: + > SELECT _FUNC_(kll_sketch_agg(col)) FROM VALUES (1.0), (2.0), (3.0) tab(col); + 3.0 + """ + //group = "misc_funcs", +) +case class KllGetMax(child: Expression) + extends UnaryExpression + with ExpectsInputTypes + with NullIntolerant { + + override protected def withNewChildInternal(newChild: Expression): KllGetMax = { + copy(child = newChild) + } + + override def prettyName: String = "kll_get_max" + + override def inputTypes: Seq[AbstractDataType] = Seq(KllDoublesSketchType) + + override def dataType: DataType = DoubleType + + override def nullSafeEval(input: Any): Any = { + val bytes = input.asInstanceOf[Array[Byte]] + val sketch = KllDoublesSketch.wrap(Memory.wrap(bytes)) + sketch.getMaxItem + } + + override protected def nullSafeCodeGen(ctx: CodegenContext, ev: ExprCode, f: String => String): ExprCode = { + val childEval = child.genCode(ctx) + val sketch = ctx.freshName("sketch") + + val code = + s""" + |${childEval.code} + |final org.apache.datasketches.kll.KllDoublesSketch $sketch = org.apache.spark.sql.types.KllDoublesSketchWrapper.wrapAsReadOnlySketch(${childEval.value}); + |final double ${ev.value} = $sketch.getMaxItem(); + """.stripMargin + ev.copy(code = CodeBlock(Seq(code), Seq.empty), isNull = childEval.isNull) + } + + override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { + nullSafeCodeGen(ctx, ev, c => s"($c)") + } +} + + +/** + * Returns the PMF and CDF of the given quantile search criteria. + * + * @param left A KllDoublesSketch sketch, in serialized form + * @param right An array of split points, as doubles + * @param isInclusive If true, use INCLUSIVE else EXCLUSIVE + * @param isPmf Whether to return the PMF (true) or CDF (false) + */ +@ExpressionDescription( + usage = """ + _FUNC_(expr, expr, isInclusive, isPmf) - Returns an approximation to the PMF or CDF (default: isPmf = false) + of the given KllDoublesSketch using the specified search criteria (default: inclusive, isInclusive = true) + or exclusive using the given split points. + """, + examples = """ + Examples: + > SELECT _FUNC_(kll_sketch_agg(col), array(1.5, 3.5), true, true) FROM VALUES (1.0), (2.0), (3.0) tab(col); + [0.3333333333333333, 0.6666666666666666, 0.0] + """ +) +case class KllGetPmfCdf(left: Expression, + right: Expression, + isInclusive: Boolean = true, + isPmf: Boolean = false) + extends BinaryExpression + with ExpectsInputTypes + with NullIntolerant + with ImplicitCastInputTypes { + + override protected def withNewChildrenInternal(newLeft: Expression, + newRight: Expression) = { + copy(left = newLeft, right = newRight, isInclusive = isInclusive, isPmf = isPmf) + } + + override def prettyName: String = "kll_get_pmf_cdf" + + override def inputTypes: Seq[AbstractDataType] = Seq(KllDoublesSketchType, ArrayType(DoubleType)) + + override def dataType: DataType = ArrayType(DoubleType, containsNull = false) + + override def nullSafeEval(leftInput: Any, rightInput: Any): Any = { + val sketchBytes = leftInput.asInstanceOf[Array[Byte]] + val splitPoints = rightInput.asInstanceOf[GenericArrayData].toDoubleArray + val sketch = KllDoublesSketch.wrap(Memory.wrap(sketchBytes)) + + val result: Array[Double] = + if (isPmf) { + sketch.getPMF(splitPoints, if (isInclusive) QuantileSearchCriteria.INCLUSIVE else QuantileSearchCriteria.EXCLUSIVE) + } else { + sketch.getCDF(splitPoints, if (isInclusive) QuantileSearchCriteria.INCLUSIVE else QuantileSearchCriteria.EXCLUSIVE) + } + new GenericArrayData(result) + } + + override protected def nullSafeCodeGen(ctx: CodegenContext, ev: ExprCode, f: (String, String) => String): ExprCode = { + val sketchEval = left.genCode(ctx) + val sketch = ctx.freshName("sketch") + val splitPointsEval = right.genCode(ctx) + val code = + s""" + |${sketchEval.code} + |${splitPointsEval.code} + |if (${sketchEval.isNull} || ${splitPointsEval.isNull}) { + | ${ev.isNull} = true; + |} else { + | QuantileSearchCriteria searchCriteria = ${if (isInclusive) "QuantileSearchCriteria.INCLUSIVE" else "QuantileSearchCriteria.EXCLUSIVE"}; + | final org.apache.datasketches.kll.KllDoublesSketch $sketch = org.apache.spark.sql.types.KllDoublesSketchWrapper.wrapAsReadOnlySketch(${sketchEval.value}); + | final double[] splitPoints = ((org.apache.spark.sql.catalyst.util.GenericArrayData)${splitPointsEval.value}).toDoubleArray(); + | final double[] result = ${if (isPmf) s"$sketch.getPMF(splitPoints, searchCriteria)" else s"$sketch.getCDF(splitPoints, searchCriteria)"}; + | GenericArrayData ${ev.value} = new GenericArrayData(result); + | ${ev.isNull} = false; + |} + """.stripMargin + ev.copy(code = CodeBlock(Seq(code), Seq.empty)) + } + + override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { + nullSafeCodeGen(ctx, ev, (arg1, arg2) => s"($arg1, $arg2)") + } +} + +// default search criteria = inclusive +// getQuantile(rank, QuantileSearchCriteria) +// getQuantileLowerBound(rank) +// getQuantileUpperBound(rank) +// getQuantiles(double ranks[], QuantileSearchCriteria) +// getRank(quantile, QuantileSearchCriteria) +// getRanks(quantile[]), QuantileSearchCriteria) +// getNormalizedRankError(bool isPmf) +// isEstimationMode() +// toString(bool, bool) -- already part of the wrapper +// getK() ? +// getNumRetained() ? diff --git a/src/main/scala/org/apache/spark/sql/functions_ds.scala b/src/main/scala/org/apache/spark/sql/functions_ds.scala new file mode 100644 index 0000000..7c2a96e --- /dev/null +++ b/src/main/scala/org/apache/spark/sql/functions_ds.scala @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql + +import org.apache.spark.sql.functions.lit +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateFunction + +import org.apache.spark.sql.catalyst.expressions.Expression +import org.apache.spark.sql.aggregate.{KllDoublesSketchAgg, KllDoublesMergeAgg} +import org.apache.spark.sql.expressions._ +import org.apache.spark.sql.catalyst.expressions.Literal +import org.apache.spark.sql.types.ArrayType +import org.apache.spark.sql.types.DoubleType + +// this class defines and maps all the variants of each function invocation, analagous +// to the functions object in org.apache.spark.sql.functions +object functions_ds { + + private def withExpr(expr: => Expression): Column = Column(expr) + + private def withAggregateFunction(func: AggregateFunction): Column = { + Column(func.toAggregateExpression()) + } + + // get min + def kll_get_min(expr: Column): Column = withExpr { + new KllGetMin(expr.expr) + } + + def kll_get_min(columnName: String): Column = { + kll_get_min(Column(columnName)) + } + + // get max + def kll_get_max(expr: Column): Column = withExpr { + new KllGetMax(expr.expr) + } + + def kll_get_max(columnName: String): Column = { + kll_get_max(Column(columnName)) + } + + // build sketch + def kll_sketch_agg(expr: Column, k: Column): Column = withAggregateFunction { + new KllDoublesSketchAgg(expr.expr, k.expr) + } + + def kll_sketch_agg(expr: Column, k: Int): Column = { + kll_sketch_agg(expr, lit(k)) + } + + def kll_sketch_agg(columnName: String, k: Int): Column = { + kll_sketch_agg(Column(columnName), k) + } + + def kll_sketch_agg(expr: Column): Column = withAggregateFunction { + new KllDoublesSketchAgg(expr.expr) + } + + def kll_sketch_agg(columnName: String): Column = { + kll_sketch_agg(Column(columnName)) + } + + // merge sketches + def kll_merge_agg(expr: Column): Column = withAggregateFunction { + new KllDoublesMergeAgg(expr.expr) + } + + def kll_merge_agg(columnName: String): Column = { + kll_merge_agg(Column(columnName)) + } + + // get PMF + def kll_get_pmf(sketch: Column, splitPoints: Column, isInclusive: Boolean): Column = withExpr { + new KllGetPmfCdf(sketch.expr, splitPoints.expr, isInclusive, true) + } + + def kll_get_pmf(sketch: Column, splitPoints: Column): Column = withExpr { + new KllGetPmfCdf(sketch.expr, splitPoints.expr, true, true) + } + + def kll_get_pmf(columnName: String, splitPoints: Column, isInclusive: Boolean): Column = { + kll_get_pmf(Column(columnName), splitPoints, isInclusive) + } + + def kll_get_pmf(columnName: String, splitPoints: Column): Column = { + kll_get_pmf(Column(columnName), splitPoints) + } + + def kll_get_pmf(sketch: Column, splitPoints: Array[Double], isInclusive: Boolean): Column = { + kll_get_pmf(sketch, Column(Literal.create(splitPoints, ArrayType(DoubleType))), isInclusive) + } + + def kll_get_pmf(sketch: Column, splitPoints: Array[Double]): Column = { + kll_get_pmf(sketch, Column(Literal.create(splitPoints, ArrayType(DoubleType)))) + } + + def kll_get_pmf(columnName: String, splitPoints: Array[Double], isInclusive: Boolean): Column = { + kll_get_pmf(Column(columnName), splitPoints, isInclusive) + } + + def kll_get_pmf(columnName: String, splitPoints: Array[Double]): Column = { + kll_get_pmf(Column(columnName), splitPoints) + } + + + // get CDF + def kll_get_cdf(sketch: Column, splitPoints: Column, isInclusive: Boolean): Column = withExpr { + new KllGetPmfCdf(sketch.expr, splitPoints.expr, isInclusive, false) + } + + def kll_get_cdf(sketch: Column, splitPoints: Column): Column = withExpr { + new KllGetPmfCdf(sketch.expr, splitPoints.expr, true, false) + } + + def kll_get_cdf(columnName: String, splitPoints: Column, isInclusive: Boolean): Column = { + kll_get_cdf(Column(columnName), splitPoints, isInclusive) + } + + def kll_get_cdf(columnName: String, splitPoints: Column): Column = { + kll_get_cdf(Column(columnName), splitPoints) + } + + def kll_get_cdf(sketch: Column, splitPoints: Array[Double], isInclusive: Boolean): Column = { + kll_get_cdf(sketch, Column(Literal.create(splitPoints, ArrayType(DoubleType))), isInclusive) + } + + def kll_get_cdf(sketch: Column, splitPoints: Array[Double]): Column = { + kll_get_cdf(sketch, Column(Literal.create(splitPoints, ArrayType(DoubleType)))) + } + + def kll_get_cdf(columnName: String, splitPoints: Array[Double], isInclusive: Boolean): Column = { + kll_get_cdf(Column(columnName), splitPoints, isInclusive) + } + + def kll_get_cdf(columnName: String, splitPoints: Array[Double]): Column = { + kll_get_cdf(Column(columnName), splitPoints) + } + +} diff --git a/src/main/scala/org/apache/spark/sql/registrar/DatasketchesFunctionRegistry.scala b/src/main/scala/org/apache/spark/sql/registrar/DatasketchesFunctionRegistry.scala new file mode 100644 index 0000000..5ab1738 --- /dev/null +++ b/src/main/scala/org/apache/spark/sql/registrar/DatasketchesFunctionRegistry.scala @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.registrar + +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.catalyst.FunctionIdentifier +import org.apache.spark.sql.catalyst.analysis.FunctionRegistryBase +import org.apache.spark.sql.catalyst.analysis.FunctionRegistry.FunctionBuilder +import org.apache.spark.sql.catalyst.expressions.{Expression, ExpressionInfo} + +import scala.reflect.ClassTag + +// DataSketches imports +import org.apache.spark.sql.aggregate.{KllDoublesSketchAgg, KllDoublesMergeAgg} +import org.apache.spark.sql.expressions.{KllGetMin, KllGetMax} +import org.apache.spark.sql.expressions.KllGetPmfCdf + +// based on org.apache.spark.sql.catalyst.FunctionRegistry +trait DatasketchesFunctionRegistry { + // override this to define the actual functions + val expressions: Map[String, (ExpressionInfo, FunctionBuilder)] + + // registers all the functions in the expressions Map + def registerFunctions(spark: SparkSession): Unit = { + expressions.foreach { case (name, (info, builder)) => + spark.sessionState.functionRegistry.registerFunction(FunctionIdentifier(name), info, builder) + } + } + + // simplifies defining the expression (ignoring "since" as a stand-alone library) + protected def expression[T <: Expression : ClassTag](name: String): (String, (ExpressionInfo, FunctionBuilder)) = { + val (expressionInfo, builder) = FunctionRegistryBase.build[T](name, None) + (name, (expressionInfo, builder)) + } + + // some functions throw a query compile-time exception around the wrong + // number of parameters when using expression(). This function allows + // explicit argument handling by providing a lambda to use for the bulder. + protected def complexExpression[T <: Expression : ClassTag](name: String)(f: (Seq[Expression]) => T): (String, (ExpressionInfo, FunctionBuilder)) = { + val expressionInfo = FunctionRegistryBase.expressionInfo[T](name, None) + val builder: FunctionBuilder = (args: Seq[Expression]) => f(args) + (name, (expressionInfo, builder)) + } +} + +// defines the Map for the Datasketches functions +object DatasketchesFunctionRegistry extends DatasketchesFunctionRegistry { + override val expressions: Map[String, (ExpressionInfo, FunctionBuilder)] = Map( + expression[KllDoublesSketchAgg]("kll_sketch_agg"), + expression[KllDoublesMergeAgg]("kll_merge_agg"), + expression[KllGetMin]("kll_get_min"), + expression[KllGetMax]("kll_get_max"), + + // TODO: it seems like there's got to be a way to simplify this, but + // perhaps not with the optional isInclusive parameter? + // Spark uses ExprssionBuilder, extending that class via a builder class + // and overriding build() to handle the lambda. + // It allows for a cleaner registry here, so we can look at where to put + // the builder classes in the future. + // See org.apache.spark.sql.catalyst.expressions.variant.variantExpressions.scala + complexExpression[KllGetPmfCdf]("kll_get_pmf") { args: Seq[Expression] => + val isInclusive = if (args.length > 2) args(2).eval().asInstanceOf[Boolean] else true + new KllGetPmfCdf(args(0), args(1), isInclusive = isInclusive, isPmf = true) + }, + complexExpression[KllGetPmfCdf]("kll_get_cdf") { args: Seq[Expression] => + val isInclusive = if (args.length > 2) args(2).eval().asInstanceOf[Boolean] else true + new KllGetPmfCdf(args(0), args(1), isInclusive = isInclusive, isPmf = false) + } + ) +} diff --git a/src/main/scala/org/apache/spark/sql/types/KllDoublesSketchType.scala b/src/main/scala/org/apache/spark/sql/types/KllDoublesSketchType.scala new file mode 100644 index 0000000..65a3635 --- /dev/null +++ b/src/main/scala/org/apache/spark/sql/types/KllDoublesSketchType.scala @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.types + +class KllDoublesSketchType extends UserDefinedType[KllDoublesSketchWrapper] { + override def sqlType: DataType = DataTypes.BinaryType + + override def serialize(wrapper: KllDoublesSketchWrapper): Array[Byte] = { + wrapper.toByteArray + } + + override def deserialize(data: Any): KllDoublesSketchWrapper = { + val bytes = data.asInstanceOf[Array[Byte]] + KllDoublesSketchWrapper.deserialize(bytes) + } + + override def userClass: Class[KllDoublesSketchWrapper] = classOf[KllDoublesSketchWrapper] + + override def catalogString: String = "KllDoublesSketch" +} + +case object KllDoublesSketchType extends KllDoublesSketchType diff --git a/src/main/scala/org/apache/spark/sql/types/KllDoublesSketchWrapper.scala b/src/main/scala/org/apache/spark/sql/types/KllDoublesSketchWrapper.scala new file mode 100644 index 0000000..774d4c8 --- /dev/null +++ b/src/main/scala/org/apache/spark/sql/types/KllDoublesSketchWrapper.scala @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.types + +import org.apache.datasketches.kll.KllDoublesSketch +import org.apache.datasketches.memory.Memory + +@SQLUserDefinedType(udt = classOf[KllDoublesSketchType]) +case class KllDoublesSketchWrapper(sketch: KllDoublesSketch) { + + def toByteArray: Array[Byte] = sketch.toByteArray + + def serialize: Array[Byte] = sketch.toByteArray + + def toString(withLevels: Boolean = false, withData: Boolean = false ): String = { + sketch.toString(withLevels, withData) + } +} + +object KllDoublesSketchWrapper { + // TODO: determine if wrap or writableWrap is a better option + def deserialize(bytes: Array[Byte]): KllDoublesSketchWrapper = { + val sketch = KllDoublesSketch.heapify(Memory.wrap(bytes)) + KllDoublesSketchWrapper(sketch) + } + + // this can go away in favor of directly calling the KllDoublesSketch.wrap + // from codegen once janino can generate java 8+ code + def wrapAsReadOnlySketch(bytes: Array[Byte]): KllDoublesSketch = { + KllDoublesSketch.wrap(Memory.wrap(bytes)) + } +} diff --git a/src/test/scala/org/apache/spark/sql/KllTest.scala b/src/test/scala/org/apache/spark/sql/KllTest.scala new file mode 100644 index 0000000..49e0a18 --- /dev/null +++ b/src/test/scala/org/apache/spark/sql/KllTest.scala @@ -0,0 +1,210 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql + +import scala.util.Random +import org.apache.spark.sql.functions._ +import org.apache.spark.sql.functions_ds._ +import org.apache.spark.registrar.DatasketchesFunctionRegistry +import scala.collection.mutable.WrappedArray + +class KllTest extends SparkSessionManager { + import spark.implicits._ + + // helper method to check if two arrays are equal + private def compareArrays(ref: Array[Double], tst: WrappedArray[Double]) { + val tstArr = tst.toArray + if (ref.length != tstArr.length) + throw new AssertionError("Array lengths do not match: " + ref.length + " != " + tstArr.length) + (ref zip tstArr).foreach { case (v1, v2) => if (v1 != v2) throw new AssertionError("Values do not match: " + v1 + " != " + v2) } + } + + test("KLL Doubles Sketch via scala") { + val n = 100 + val data = (for (i <- 1 to n) yield i.toDouble).toDF("value") + + val sketchDf = data.agg(kll_sketch_agg("value").as("sketch")) + val result: Row = sketchDf.select(kll_get_min($"sketch").as("min"), + kll_get_max($"sketch").as("max") + ).head + + val minValue = result.getAs[Double]("min") + val maxValue = result.getAs[Double]("max") + assert(minValue == 1.0) + assert(maxValue == n.toDouble) + + val splitPoints = Array[Double](20.5, 50, 102) + val pmfCdfResult = sketchDf.select( + kll_get_pmf($"sketch", splitPoints).as("pmf_inclusive"), + kll_get_pmf($"sketch", splitPoints, false).as("pmf_exclusive"), + kll_get_cdf($"sketch", splitPoints).as("cdf_inclusive"), + kll_get_cdf($"sketch", splitPoints, false).as("cdf_exclusive") + ).head + + val pmf_incl = Array[Double](0.2, 0.3, 0.5, 0.0) + compareArrays(pmf_incl, pmfCdfResult.getAs[WrappedArray[Double]]("pmf_inclusive")) + + val pmf_excl = Array[Double](0.2, 0.29, 0.51, 0.0) + compareArrays(pmf_excl, pmfCdfResult.getAs[WrappedArray[Double]]("pmf_exclusive")) + + val cdf_incl = Array[Double](0.2, 0.5, 1.0, 1.0) + compareArrays(cdf_incl, pmfCdfResult.getAs[WrappedArray[Double]]("cdf_inclusive")) + + val cdf_excl = Array[Double](0.2, 0.49, 1.0, 1.0) + compareArrays(cdf_excl, pmfCdfResult.getAs[WrappedArray[Double]]("cdf_exclusive")) + } + + test("Kll Doubles Sketch via SQL") { + // register Datasketches functions + DatasketchesFunctionRegistry.registerFunctions(spark) + + val n = 100 + val data = (for (i <- 1 to n) yield i.toDouble).toDF("value") + data.createOrReplaceTempView("data_table") + + val kllDf = spark.sql( + s""" + |SELECT + | kll_get_min(kll_sketch_agg(value, 200)) AS min, + | kll_get_max(kll_sketch_agg(value, 200)) AS max + |FROM + | data_table + """.stripMargin + ) + val minValue = kllDf.head.getAs[Double]("min") + val maxValue = kllDf.head.getAs[Double]("max") + assert(minValue == 1.0) + assert(maxValue == n.toDouble) + + val splitPoints = "array(20.5, 50, 102)" + val pmfCdfResult = spark.sql( + s""" + |SELECT + | kll_get_pmf(t.sketch, ${splitPoints}) AS pmf_inclusive, + | kll_get_pmf(t.sketch, ${splitPoints}, false) AS pmf_exclusive, + | kll_get_cdf(t.sketch, ${splitPoints}) AS cdf_inclusive, + | kll_get_cdf(t.sketch, ${splitPoints}, false) AS cdf_exclusive + |FROM + | (SELECT + | kll_sketch_agg(value, 200) sketch + | FROM + | data_table) t + """.stripMargin + ).head + + val pmf_incl = Array[Double](0.2, 0.3, 0.5, 0.0) + compareArrays(pmf_incl, pmfCdfResult.getAs[WrappedArray[Double]]("pmf_inclusive")) + + val pmf_excl = Array[Double](0.2, 0.29, 0.51, 0.0) + compareArrays(pmf_excl, pmfCdfResult.getAs[WrappedArray[Double]]("pmf_exclusive")) + + val cdf_incl = Array[Double](0.2, 0.5, 1.0, 1.0) + compareArrays(cdf_incl, pmfCdfResult.getAs[WrappedArray[Double]]("cdf_inclusive")) + + val cdf_excl = Array[Double](0.2, 0.49, 1.0, 1.0) + compareArrays(cdf_excl, pmfCdfResult.getAs[WrappedArray[Double]]("cdf_exclusive")) + } + + test("KLL Doubles Merge via Scala") { + val data = generateData().toDF("id", "value") + + // compute global min and max + val minMax: Row = data.agg(min("value").as("min"), max("value").as("max")).collect.head + val globalMin = minMax.getAs[Double]("min") + val globalMax = minMax.getAs[Double]("max") + + // create a sketch for each id value + val idSketchDf = data.groupBy($"id").agg(kll_sketch_agg($"value").as("sketch")) + + // merge into an aggregate sketch + val mergedSketchDf = idSketchDf.agg(kll_merge_agg($"sketch").as("sketch")) + + // check min and max + val result: Row = mergedSketchDf.select(kll_get_min($"sketch").as("min"), + kll_get_max($"sketch").as("max")) + .head + + val sketchMin = result.getAs[Double]("min") + val sketchMax = result.getAs[Double]("max") + + assert(globalMin == sketchMin) + assert(globalMax == sketchMax) + } + + test("KLL Doubles Merge via SQL") { + // register Datasketches functions + DatasketchesFunctionRegistry.registerFunctions(spark) + + val data = generateData().toDF() + data.createOrReplaceTempView("data_table") + + // compute global min and max from dataframe + val minMax: Row = data.agg(min("value").as("min"), max("value").as("max")).head + val globalMin = minMax.getAs[Double]("min") + val globalMax = minMax.getAs[Double]("max") + + // cannot do nested aggregations so need + // need a first pass to generate sketches + val idSketchDf = spark.sql( + s""" + |SELECT + | id, + | kll_sketch_agg(value, 200) AS sketch + |FROM + | data_table + |GROUP BY + | id + """.stripMargin + ) + idSketchDf.createOrReplaceTempView("sketch_table") + + // now merge the sketches + val mergedSketchDf = spark.sql( + s""" + |SELECT + | kll_get_min(sub.sketch) AS min, + | kll_get_max(sub.sketch) AS max + |FROM + | (SELECT + | kll_merge_agg(sketch) AS sketch + | FROM + | sketch_table + | ) sub + """.stripMargin + ) + + // check min and max + val result: Row = mergedSketchDf.head + val sketchMin = result.getAs[Double]("min") + val sketchMax = result.getAs[Double]("max") + + assert(globalMin == sketchMin) + assert(globalMax == sketchMax) + } + + // a simple data generator + private def generateData(numRecords: Int = 25000, numClasses: Int = 20): Seq[DataRow] = { + val maxId = numClasses + for (i <- 0 until numRecords) yield { + val id = i % maxId + DataRow(id, id + Random.nextDouble()) + } + } +} + +case class DataRow(id: Integer, value: Double) diff --git a/src/test/scala/org/apache/spark/sql/SparkSessionManager.scala b/src/test/scala/org/apache/spark/sql/SparkSessionManager.scala new file mode 100644 index 0000000..3675620 --- /dev/null +++ b/src/test/scala/org/apache/spark/sql/SparkSessionManager.scala @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql + +import org.apache.log4j.{Level, Logger} +import org.scalatest.BeforeAndAfterAll +import org.scalatest.funsuite.AnyFunSuite + +/** + * This class provides a common base for tests. It can perhaps + * be simplified or eliminated but was useful for very early-stage + * testing. + */ +trait SparkSessionManager extends AnyFunSuite with BeforeAndAfterAll { + Logger.getRootLogger().setLevel(Level.OFF) + + lazy val spark: SparkSession = SparkSession + .builder() + .appName("datasketches-spark-tests") + .master("local[3]") + .getOrCreate() + + override def beforeAll(): Unit = { + spark.sparkContext.setLogLevel("OFF") + } +} --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
