Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
7bf45dd
Adds zip function to sparksql
DylanGuedes Apr 11, 2018
99848fe
Changes zip construction
DylanGuedes Apr 13, 2018
27b0bc2
Changes tests and uses builtin namespace in pyspark
DylanGuedes Apr 13, 2018
93826b6
fixes examples string and uses struct instead of arrays
DylanGuedes Apr 26, 2018
a7e29f6
working pyspark zip_lists
DylanGuedes May 11, 2018
7130fec
Fixes java version when arrays have different lengths
DylanGuedes May 11, 2018
d552216
remove unused variables
DylanGuedes May 11, 2018
1fecef4
rename zip_lists to zip
DylanGuedes May 11, 2018
f71151a
adds expression tests and uses strip margin syntax
DylanGuedes May 12, 2018
6b4bc94
Adds variable number of inputs to zip function
DylanGuedes May 15, 2018
1549928
uses foldleft instead of while for iterating
DylanGuedes May 15, 2018
9f7bba1
rewritten some notation
DylanGuedes May 16, 2018
3ba2b4f
fix dogencode generation
DylanGuedes May 17, 2018
3a59201
Adds new tests, uses lazy val and split calls
DylanGuedes May 17, 2018
6462fa8
uses splitFunction
DylanGuedes May 17, 2018
8b1eb7c
move arraytypes to private member
DylanGuedes May 18, 2018
2bfba80
adds binary and array of array tests
DylanGuedes May 18, 2018
c3b062c
uses stored array types names
DylanGuedes May 18, 2018
d9b95c4
split input function using ctxsplitexpression
DylanGuedes May 18, 2018
26bbf66
uses splitexpression for inputs
DylanGuedes May 19, 2018
d9ad04d
Refactor cases, add new tests with empty seq, check size of array
DylanGuedes May 22, 2018
f29ee1c
Check empty seq as input
DylanGuedes May 22, 2018
c58d09c
Uses switch instead of if
DylanGuedes May 23, 2018
38fa996
refactor switch and else methods
DylanGuedes May 23, 2018
5b3066b
uses if instead of switch
DylanGuedes May 30, 2018
759a4d4
Not using storedarrtype anymore
DylanGuedes Jun 4, 2018
68e69db
split between empty and nonempty codegen
DylanGuedes Jun 4, 2018
12b3835
remove ternary if
DylanGuedes Jun 4, 2018
643cb9b
Fixes null values evaluation and adds back tests
DylanGuedes Jun 4, 2018
5876082
move to else
DylanGuedes Jun 4, 2018
0223960
remove unused lines
DylanGuedes Jun 4, 2018
2b88387
use zip alias
DylanGuedes Jun 5, 2018
bbc20ee
using same docs for all apis
DylanGuedes Jun 8, 2018
8d3a838
adds transient to method
DylanGuedes Jun 8, 2018
d8f3dea
rename zip function to arrays_zip
DylanGuedes Jun 10, 2018
3d68ea9
adds pretty_name for arrays_zip
DylanGuedes Jun 11, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Adds variable number of inputs to zip function
Signed-off-by: DylanGuedes <[email protected]>
  • Loading branch information
DylanGuedes committed Jun 4, 2018
commit 6b4bc94051a3f86150a6be15b44bbb6b25e5fc67
7 changes: 3 additions & 4 deletions python/pyspark/sql/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2395,21 +2395,20 @@ def array_repeat(col, count):


@since(2.4)
def zip(col1, col2):
def zip(*cols):
"""
Merge two columns into one, such that the M-th element of the N-th argument will be
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add Collection function: like other collection functions?

the N-th field of the M-th output element.

:param col1: name of the first column
:param col2: name of the second column
:param cols: columns in input
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: columns of arrays to be merged.


>>> from pyspark.sql.functions import zip
>>> df = spark.createDataFrame([(([1, 2, 3], [2, 3, 4]))], ['vals1', 'vals2'])
>>> df.select(zip(df.vals1, df.vals2).alias('zipped')).collect()
[Row(zipped=[1, 2]), Row(zipped=[2, 3]), Row(zipped=[3, 4])]
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.zip(_to_java_column(col1), _to_java_column(col2)))
return Column(sc._jvm.functions.zip(_to_seq(sc, cols, _to_java_column)))


# ---------------------------- User Defined Function ----------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,106 +129,84 @@ case class MapKeys(child: Expression)
}

@ExpressionDescription(
usage = """_FUNC_(a1, a2) - Returns a merged array matching N-th element of first
array with the N-th element of second.""",
usage = """_FUNC_(a1, a2, ...) - Returns a merged array containing in the N-th position the
N-th value of each array given.""",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would do this:

usage = """
  _FUNC_(a1, a2, ...) - Returns a merged array containing in the N-th position the
    N-th value of each array given.
"""

examples = """
Examples:
> SELECT _FUNC_(array(1, 2, 3), array(2, 3, 4));
[[1, 2], [2, 3], [3, 4]]
> SELECT _FUNC_(array(1, 2), array(2, 3), array(3, 4));
[[1, 2, 3], [2, 3, 4]]
""",
since = "2.4.0")
case class Zip(left: Expression, right: Expression)
extends BinaryExpression with ExpectsInputTypes {
case class Zip(children: Seq[Expression]) extends Expression with ExpectsInputTypes {
private[this] val childrenArray = children.toArray

override def inputTypes: Seq[AbstractDataType] = Seq.fill(childrenArray.length)(ArrayType)

def mountSchema(): StructType = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the whole method may be done more easily using foldLeft/foldRight

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

val arrayAT = childrenArray.map(_.dataType.asInstanceOf[ArrayType])
val n = childrenArray.length
var i = n - 1
var myList = List[StructField]()
while (i >= 0) {
myList = StructField(s"_$i", arrayAT(i).elementType, arrayAT(i).containsNull) :: myList
i -= 1
}

override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType, ArrayType)
StructType(myList)
}

override def dataType: DataType = ArrayType(StructType(
StructField("_1", left.dataType.asInstanceOf[ArrayType].elementType, true) ::
StructField("_2", right.dataType.asInstanceOf[ArrayType].elementType, true) ::
Nil))
override def dataType: DataType = ArrayType(mountSchema())

override def prettyName: String = "zip"

override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (arr1, arr2) => {
val genericArrayData = classOf[GenericArrayData].getName
val genericInternalRow = classOf[GenericInternalRow].getName

val i = ctx.freshName("i")
val values = ctx.freshName("values")
val len1 = ctx.freshName("len1")
val len2 = ctx.freshName("len2")
val pair = ctx.freshName("pair")
val getValue1 = CodeGenerator.getValue(
arr1, left.dataType.asInstanceOf[ArrayType].elementType, i)
val getValue2 = CodeGenerator.getValue(
arr2, right.dataType.asInstanceOf[ArrayType].elementType, i)

s"""
|int $len1 = $arr1.numElements();
|int $len2 = $arr2.numElements();
|Object[] $values;
|Object[] $pair;
|if ($len1 > $len2) {
| $values = new Object[$len1];
| for (int $i = 0; $i < $len1; $i ++) {
| $pair = new Object[2];
| $pair[0] = $getValue1;
| if ($i >= $len2) {
| $pair[1] = null;
| } else {
| $pair[1] = $getValue2;
| }
| $values[$i] = new $genericInternalRow($pair);
| }
|} else {
| $values = new Object[$len2];
| for (int $i = 0; $i < $len2; $i ++) {
| $pair = new Object[2];
| $pair[1] = $getValue2;
| if ($i >= $len1) {
| $pair[0] = null;
| } else {
| $pair[0] = $getValue1;
| }
| $values[$i] = new $genericInternalRow($pair);
| }
|}
|${ev.value} = new $genericArrayData($values);
""".stripMargin
})
}
val genericArrayData = classOf[GenericArrayData].getName
val genericInternalRow = classOf[GenericInternalRow].getName

def extendWithNull(a1: Array[AnyRef], a2: Array[AnyRef]):
(Array[AnyRef], Array[AnyRef]) = {
val lens = (a1.length, a2.length)
val evals = children.map(_.genCode(ctx))
val numArrs = evals.length

var arr1 = a1
var arr2 = a2
val values = children.zip(evals).map { case(child, eval) =>

val diff = lens._1 - lens._2
if (lens._1 > lens._2) {
arr2 = a2 ++ Array.fill(diff)(null)
}
if (lens._1 < lens._2) {
arr1 = a1 ++ Array.fill(-diff)(null)
}

(arr1, arr2)
ev.copy(code =
s"""
""".stripMargin)
}

override def nullSafeEval(a1: Any, a2: Any): Any = {
val type1 = left.dataType.asInstanceOf[ArrayType].elementType
val type2 = right.dataType.asInstanceOf[ArrayType].elementType
override def nullable: Boolean = children.forall(_.nullable)

val arrays = (
a1.asInstanceOf[ArrayData].toArray[AnyRef](type1),
a2.asInstanceOf[ArrayData].toArray[AnyRef](type2)
)
override def eval(input: InternalRow): Any = {
val inputArrays = childrenArray.map(_.eval(input).asInstanceOf[ArrayData])
val arrayTypes = childrenArray.map(_.dataType.asInstanceOf[ArrayType].elementType)
val numberOfArrays = childrenArray.length

val extendedArrays = extendWithNull(arrays._1, arrays._2)
var biggestCardinality = 0
for (e <- inputArrays) {
biggestCardinality = biggestCardinality max e.numElements()
}

new GenericArrayData(extendedArrays.zipped.map((a, b) => InternalRow.apply(a, b)))
var i = 0
var j = 0
var result = Seq[InternalRow]()
while (i < biggestCardinality) {
var myList = List[Any]()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Number of children is fixed. What about using Array?

j = numberOfArrays - 1
while (j >= 0) {
if (inputArrays(j).numElements() > i) {
myList = inputArrays(j).get(i, arrayTypes(j)) :: myList
} else {
myList = null :: myList
}
j -= 1
}
result = result :+ InternalRow.apply(myList: _*)
i += 1
}
new GenericArrayData(result)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need override def prettyName: String = "arrays_zip".

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,11 @@ class CollectionExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper
val val2 = List(Row(9001, 4), Row(9002, 5), Row(null, 6))
val val3 = List(Row("a", 4), Row("b", null), Row(null, null))

checkEvaluation(Zip(lit1._1, lit1._2), val1)
checkEvaluation(Zip(lit2._1, lit2._2), val2)
checkEvaluation(Zip(lit3._1, lit3._2), val3)
checkEvaluation(Zip(Seq(Literal.create(Seq(1, 0)), Literal.create(Seq(1, 0)))),
List(Row(1, 0), Row(1, 0)))
checkEvaluation(Zip(Seq(lit1._1, lit1._2)), val1)
checkEvaluation(Zip(Seq(lit2._1, lit2._2)), val2)
checkEvaluation(Zip(Seq(lit3._1, lit3._2)), val3)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a case for something like Zip(Seq(null, literals(0))) or Zip(Seq(literals(0), null))?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also what if Zip(Seq())?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to test the case with Seq(null, literals(0)), but it breaks before reaching checkEvalWithCodeGen/withoutCodegen (looks like when you iterate in a sequence with a null element it explodes). I checked and I don't saw any tests that accept Seq[Expression] testing this case (for instance: Concat turn null inputs in Literals with null values).

Should I change something?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried, but looks like I can't create an empty genericarray. I'm pushing a code with the tests that cover these scenarios commented so maybe anyone could give me suggestions while I look for another solution.


test("Array Min") {
Expand Down
4 changes: 2 additions & 2 deletions sql/core/src/main/scala/org/apache/spark/sql/functions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3509,12 +3509,12 @@ object functions {
def map_entries(e: Column): Column = withExpr { MapEntries(e.expr) }

/**
* Merge two columns into a resulting one.
* Merge multiple columns into a resulting one.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would match the doc in Scala / Python (probably SQL too).

*
* @group collection_funcs
* @since 2.4.0
*/
def zip(e1: Column, e2: Column): Column = withExpr { Zip(e1.expr, e2.expr) }
def zip(e: Column*): Column = withExpr { Zip(e.map(_.expr)) }

//////////////////////////////////////////////////////////////////////////////////////////////
// Mask functions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -481,16 +481,16 @@ class DataFrameFunctionsSuite extends QueryTest with SharedSQLContext {

test("dataframe zip function") {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add some test cases with nulls.

val df1 = Seq((Seq(9001, 9002, 9003), Seq(4, 5, 6))).toDF("val1", "val2")
val df2 = Seq((Seq(9001, 9002), Seq(4, 5, 6))).toDF("val1", "val2")
val df2 = Seq((Seq("a", "b"), Seq(4, 5), Seq(10, 11))).toDF("val1", "val2", "val3")
val df3 = Seq((Seq("a", "b"), Seq(4, 5, 6))).toDF("val1", "val2")

val expectedValue1 = Row(Seq(Row(9001, 4), Row(9002, 5), Row(9003, 6)))
checkAnswer(df1.select(zip($"val1", $"val2")), expectedValue1)
checkAnswer(df1.selectExpr("zip(val1, val2)"), expectedValue1)

val expectedValue2 = Row(Seq(Row(9001, 4), Row(9002, 5), Row(null, 6)))
checkAnswer(df2.select(zip($"val1", $"val2")), expectedValue2)
checkAnswer(df2.selectExpr("zip(val1, val2)"), expectedValue2)
val expectedValue2 = Row(Seq(Row("a", 4, 10), Row("b", 5, 11)))
checkAnswer(df2.select(zip($"val1", $"val2", $"val3")), expectedValue2)
checkAnswer(df2.selectExpr("zip(val1, val2, val3)"), expectedValue2)

val expectedValue3 = Row(Seq(Row("a", 4), Row("b", 5), Row(null, 6)))
checkAnswer(df3.select(zip($"val1", $"val2")), expectedValue3)
Expand Down