You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "SparkApplicationMaster (via GitHub)" <gi...@apache.org> on 2025/09/06 21:26:26 UTC

[PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

SparkApplicationMaster opened a new pull request, #17456:
URL: https://github.com/apache/datafusion/pull/17456

   ## Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   part of #15914 
   
   ## Rationale for this change
   
   Migrate spark functions from https://github.com/lakehq/sail/ to datafusion engine to unify codebase
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   ## What changes are included in this PR?
   
   implement spark udf `map_from_arrays`
   https://spark.apache.org/docs/latest/api/sql/index.html#map_from_arrays
    
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   ## Are these changes tested?
   
   sqllogictests added
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   ## Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   map_from_arrays(keys_array_col, values_array_col) now can be called in queries
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2345257689


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,208 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,

Review Comment:
   yes, this is actually known problem we covered a little bit in https://github.com/apache/datafusion/pull/16936 but still not everywhere



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2346941752


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,208 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,

Review Comment:
   finally understood the root cause of the problem:
   array() is `spark_array` function call
   spark_array has 'element' field name
   
   NULL casted to array type is datafusion core array
   datafusion core array has 'item' field name
   so they are really not coercible because of different field name
   
   this causes the error (spark and datafusion arrays mixed):
   ```
   query ?
   select map_from_arrays(a, b)
   from values 
       (array(1), array('a')), 
       (NULL, NULL),
       (array(2, 3), array('b', 'c'))
   as tab(a, b);
   ----
   {1: a}
   NULL
   {2: b, 3: c}
   ```
   
   but this works (only datafusion arrays):
   ```
   query ?
   select map_from_arrays(a, b)
   from values 
       (array[1], array['a']), 
       (NULL, NULL),
       (array[2, 3], array['b', 'c'])
   as tab(a, b);
   ----
   {1: a}
   NULL
   {2: b, 3: c}
   ```
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2342821730


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,208 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(

Review Comment:
   added docstrings for both public functions



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead merged PR #17456:
URL: https://github.com/apache/datafusion/pull/17456


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328800105


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;
+        let num_entries = next_offset - cur_offset;
+        let keys_slice = keys.slice(cur_offset, num_entries);
+        let mut seen_keys = HashSet::new();

Review Comment:
   deduplication is made for array in each row independently, keys from row1 are not deduplicated with keys from row2
   this can be achieved by building a global hash for all rows, but will require something like HashMap(key: (KeyScalar, RowNumber), value: GlobalArrayLastLocalIndex)
   and then arrow take(keys, GlobalArrayLastLocalIndex), take(values, GlobalArrayLastLocalIndex)
   take function by indices from arrays can be faster than building key and value arrays by 1 value at a time, but this will require a lot more memory than the local hashset



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#issuecomment-3263235043

   Some caveats:
   1) Tried to implement type signature like this:
   ```rust
   Signature::arrays(2, Some(ListCoercion::FixedSizedListToList), Volatility::Immutable)
   ```
   but it coerces list field to same type which is not acceptable for this function
   
   2) This function requres to be confugurable, but this is not implemented yet in datafusion as I know
   Keys can be deduplicated or an error can be raised according to spark-conf
   So by default a more permissive deduplicating  behaviour is implemented, as it is more useful and passes spark-tests
   TODO added where the future work needed when configuration will be possible


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328780505


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;

Review Comment:
   ```suggestion
   let [cur_offset, next_offset] = offsets[row_num..=row_num + 1];
   let (cur_offset, next_offset) = (cur_offset as usize, next_offset as usize);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#issuecomment-3335975162

   @comphead thank you for review and for help with test cases!
   it really helped to reveal and fix some major bugs
   now I can push some other map functions on top of this


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328812179


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;

Review Comment:
   I can rewrite this using cur_offset as previous value of next_offset and updating in the end of each cycle, but then it will be mutable
   will this solution be OK?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328810936


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(

Review Comment:
   return_type_from_key_value_types and map_from_keys_values_offsets functions will be reused in the future work to add  `map_from_entries` and `str_to_map` functions
   but `map_deduplicate_keys` can be made private
   
   maybe this functions can be moved to some `common.rs` file in map module, will it be OK?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2342838886


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,208 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,

Review Comment:
   refactored deduplication logic in utils.rs
   added null and different length tests (2, 3)
   wanted to add some checks with multiple rows, but this error blocks all tries:
   ```
   1. query failed: DataFusion error: Arrow error: Invalid argument error: column types must match schema types, 
   expected  List(Field { name: "item",    data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }) 
   but found List(Field { name: "element", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }) 
   at column index 0
   [SQL] select * from values (array(1, 2), array('a', 'b')), (array(3, 4), array('c', 'd')) as tab(key, value);
   at /mnt/c/projects/datafusion/datafusion/sqllogictest/test_files/spark/map/map_from_arrays.slt:55
   
   2. query failed: DataFusion error: Arrow error: Invalid argument error: It is not possible to concatenate arrays of different data types (
   List(Field { name: "element", data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), 
   List(Field { name: "item",    data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} })
   ).
   [SQL] SELECT * from values (array('b', 'c')), (NULL) as tab(a);
   ```
   nested functions cannot be tested properly with sqllogictests without this functionality



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#issuecomment-3328009492

   @comphead please take a look at the new version when you have some time


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2345261041


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,208 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,

Review Comment:
   basically when comparing schemas it is better to compare like 
   
   ```
           if left_data_type.is_nested() {
               if !left_data_type.equals_datatype(&right_data_type) {
                   return internal_err!("Cannot evaluate binary expression because of type mismatch: left {}, right {} ", left_data_type, right_data_type);
               }
               return apply_cmp_for_nested(self.op, &lhs, &rhs);
           }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#issuecomment-3268150583

   Thanks @SparkApplicationMaster I'll check this again later this week


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328810188


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;

Review Comment:
   right, there is no guarantee, another option with `windows(2)` which I'm not sure if brings any benefit. I'd like to avoid access by index twice as behind the scene rustc will do a boundary check. Lets leave it as is



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328816975


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;
+        let num_entries = next_offset - cur_offset;
+        let keys_slice = keys.slice(cur_offset, num_entries);
+        let mut seen_keys = HashSet::new();

Review Comment:
   the problem is that the arrays coming to this function are already flattened
   but the nested structure must be remembered and taken care of
   ```
   # rows is virtual structure for visibility, actually only offsets [0, 4, 7] are existing in offsets array
   rows:   [ 0,   0,   0,   0,   1,   1,   1 ] 
   keys:   [ 0,   1,   2,   0,   0,   1,   2 ]
   values: ['a', 'b', 'c', 'd', 'a', 'b', 'c']
   ------
   result: 
   rows: [            0           ,            1            ]
   maps: [{1: 'b', 2: 'c', 0: 'd'}, {0: 'a', 1: 'b', 2: 'c'}]
   ```
   deduplication is row-wise, not all-rows-wise
   there can be same keys in different rows, and they are not deduplicated with each other
   so hashset of keys can be local for one row or global but contain info about from what row the key was taken



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2341607716


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(

Review Comment:
   Moving this to utility map module sounds great, please add a description for the pub method so it will show nicely in the autogenerated doc



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328781392


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(

Review Comment:
   is it needed to be pub? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328781000


##########
datafusion/sqllogictest/test_files/spark/map/map_from_arrays.slt:
##########
@@ -0,0 +1,60 @@
+# 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.
+
+# Spark doctests
+query ?
+SELECT map_from_arrays(array(1.0, 3.0), array('2', '4'));
+----
+{1.0: 2, 3.0: 4}
+
+query ?
+SELECT map_from_arrays(array(2, 5), array('a', 'b'));
+----
+{2: a, 5: b}
+
+query ?
+SELECT map_from_arrays(array(1, 2), array('a', NULL));
+----
+{1: a, 2: NULL}
+
+query ?
+SELECT map_from_arrays(cast(array() as array<int>), cast(array() as array<string>));
+----
+{}
+
+# Test with complex types
+query ?
+SELECT map_from_arrays(array(array('a', 'b'), array('c', 'd')), array(struct(1, 2, 3), struct(4, 5, 6)));
+----
+{[a, b]: {c0: 1, c1: 2, c2: 3}, [c, d]: {c0: 4, c1: 5, c2: 6}}
+
+# Test with duplicate keys
+query ?
+SELECT map_from_arrays(array(true, false, true), array('a', NULL, 'b'));
+----
+{false: NULL, true: b}
+
+# Tests with different list types
+query ?
+SELECT map_from_arrays(arrow_cast(array(2, 5), 'LargeList(Int32)'), arrow_cast(array('a', 'b'), 'FixedSizeList(2, Utf8)'));
+----
+{2: a, 5: b}
+
+query ?
+SELECT map_from_arrays(arrow_cast(array('a', 'b', 'c'), 'FixedSizeList(3, Utf8)'), arrow_cast(array(1, 2, 3), 'LargeList(Int32)'));

Review Comment:
   can we have a nested map_from_arrays test? 
   
   Something like 
   
   ```
   SELECT
       map_from_arrays(
           array['outer_key1', 'outer_key2'],
           array[
               -- value for outer_key1: a map itself
               map_from_arrays(
                   array['inner_a', 'inner_b'],
                   array[1, 2]
               ),
               -- value for outer_key2: another map
               map_from_arrays(
                   array['inner_x', 'inner_y', 'inner_z'],
                   array[10, 20, 30]
               )
           ]
       ) AS nested_map;
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328816975


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;
+        let num_entries = next_offset - cur_offset;
+        let keys_slice = keys.slice(cur_offset, num_entries);
+        let mut seen_keys = HashSet::new();

Review Comment:
   the problem is that the arrays coming to this function are already flattened
   but the nested structure must be remembered and taken care of
   ```
   # rows is virtual structure for visibility, actually only offsets [0, 4, 7] are existing in offsets array
   rows:   [ 0,   0,   0,   0,   1,   1,   1 ] 
   keys:   [ 0,   1,   2,   0,   0,   1,   2 ]
   values: ['a', 'b', 'c', 'd', 'a', 'b', 'c']
   ------
   result: 
   rows: [            0           ,            1            ]
   maps: [{1: 'b', 2: 'c', 0: 'd'}, {0: 'a', 1: 'b', 2: 'c'}]
   ```
   deduplication is row-wise, not all-rows-wise
   there can be same keys in different rows, and they are not duplicated with each other
   so hashset of keys can be local for one row or global but contain info about from what row the key was taken



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328809232


##########
datafusion/sqllogictest/test_files/spark/map/map_from_arrays.slt:
##########
@@ -0,0 +1,60 @@
+# 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.
+
+# Spark doctests
+query ?
+SELECT map_from_arrays(array(1.0, 3.0), array('2', '4'));
+----
+{1.0: 2, 3.0: 4}
+
+query ?
+SELECT map_from_arrays(array(2, 5), array('a', 'b'));
+----
+{2: a, 5: b}
+
+query ?
+SELECT map_from_arrays(array(1, 2), array('a', NULL));
+----
+{1: a, 2: NULL}
+
+query ?
+SELECT map_from_arrays(cast(array() as array<int>), cast(array() as array<string>));
+----
+{}
+
+# Test with complex types
+query ?
+SELECT map_from_arrays(array(array('a', 'b'), array('c', 'd')), array(struct(1, 2, 3), struct(4, 5, 6)));
+----
+{[a, b]: {c0: 1, c1: 2, c2: 3}, [c, d]: {c0: 4, c1: 5, c2: 6}}
+
+# Test with duplicate keys
+query ?
+SELECT map_from_arrays(array(true, false, true), array('a', NULL, 'b'));
+----
+{false: NULL, true: b}
+
+# Tests with different list types
+query ?
+SELECT map_from_arrays(arrow_cast(array(2, 5), 'LargeList(Int32)'), arrow_cast(array('a', 'b'), 'FixedSizeList(2, Utf8)'));
+----
+{2: a, 5: b}
+
+query ?
+SELECT map_from_arrays(arrow_cast(array('a', 'b', 'c'), 'FixedSizeList(3, Utf8)'), arrow_cast(array(1, 2, 3), 'LargeList(Int32)'));

Review Comment:
   great example, thanks!
   it works fine so I wil just check the result and add it to the tests



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328800105


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;
+        let num_entries = next_offset - cur_offset;
+        let keys_slice = keys.slice(cur_offset, num_entries);
+        let mut seen_keys = HashSet::new();

Review Comment:
   deduplication is made for array in each row independently, keys from row1 are not deduplicated with keys from row2
   this can be achieved by building a global hash for all rows, but will require something like HashMap(key: (KeyScalar, RowNumber), value: GlobalArrayLastLocalIndex)
   and then arrow take(keys, GlobalArrayLastLocalIndex), take(values, GlobalArrayLastLocalIndex)
   this will require a lot more memory than the local hashset
   UPD: forgot that there is already filter function by boolean mask which is fast, so unfortunately I don't understand where a performance gain can be achieved



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328784413


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;
+        let num_entries = next_offset - cur_offset;
+        let keys_slice = keys.slice(cur_offset, num_entries);
+        let mut seen_keys = HashSet::new();

Review Comment:
   it might be expensive to calc dedup per row? would be that easier to build keys/values arrays and duplicate table indices with LAST WIN strategy and then filter keys/values arrays? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328816975


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;
+        let num_entries = next_offset - cur_offset;
+        let keys_slice = keys.slice(cur_offset, num_entries);
+        let mut seen_keys = HashSet::new();

Review Comment:
   the problem is that the arrays coming to this function are already flattened
   but the nested structure must be remembered and taken care of
   ```
   # rows is virtual structure for visibility, actually only offsets [0, 4, 7] are existing in offsets array
   rows:   [ 0,   0,   0,   0,   1,   1,   1 ] 
   keys:   [ 0,   1,   2,   0,   0,   1,   2 ]
   values: ['a', 'b', 'c', 'd', 'a', 'b', 'c']
   ------
   result: 
   rows: [            0           ,            1            ]
   maps: [{1: 'b', 2: 'c', 0: 'd'}, {0: 'a', 1: 'b', 2: 'c'}]
   ```
   deduplication is row-wise, not all-rows-wise
   there can be same keys in different rows, and they are not duplicated with each other



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328810936


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(

Review Comment:
   `return_type_from_key_value_types` and `map_from_keys_values_offsets` functions will be reused in the future work to add  `map_from_entries` and `str_to_map` functions
   but `map_deduplicate_keys` can be made private
   
   maybe this functions can be moved to some `common.rs` file in map module, will it be OK?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2342584850


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,208 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,

Review Comment:
   huge thanks for this test!
   started to check it and dug down to a whole bunch of errors
   1) `from values` with arrays fails sqllogictest even without my code (will create an issue on this soon)
   2) `map_from_arrays` fails with one or both NullType
   3) my fast but naive implementation of getting keys and values by same filter mask is not working if some null arrays present in rows  - because offsets are not equal for keys and values
   (must skip indices in one of arrays where null is present and create null result value for the row
   
   2 and 3 is true for the implementation in Sail too
   
   I will return with some refactored implementation of this
   two parallel filter masks and also nulls row masks for both arrays will be needed I suppose



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2342822437


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(

Review Comment:
   moved public functions which can be reused to utils.rs file



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2341616223


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,208 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(

Review Comment:
   please add function description



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2341628818


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,208 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,

Review Comment:
   what about nulls? 
   
   ```
   scala> spark.sql("select map_from_arrays(null, null)").show(false)
   +---------------------------+
   |map_from_arrays(NULL, NULL)|
   +---------------------------+
   |NULL                       |
   +---------------------------+
   ```
   Lets include this test into `slt`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#issuecomment-3288856544

   added multi-row test which failed in previous version of code
   
   moved some more functions to utils.rs and added docstrings for them
   because they will later be needed for `map_from_entries` and `str_to_map` functions


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328808131


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;

Review Comment:
   sorry, this causes compile error, I suppose it cannot be guaranteed that size of this slice equals 2:
   ```rust
   let [cur_offset, next_offset] = offsets[row_num..=row_num + 1];
   ```
   ```
   refutable pattern in local binding
   `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
   for more information, visit https://doc.rust-lang.org/book/ch19-02-refutability.html
   the matched value is of type `[i32]`rustcClick for full compiler diagnostic
   map_from_arrays.rs(180, 71): you might want to use `let else` to handle the variants that aren't matched: ` else { todo!() }`
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328812074


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;
+        let num_entries = next_offset - cur_offset;
+        let keys_slice = keys.slice(cur_offset, num_entries);
+        let mut seen_keys = HashSet::new();

Review Comment:
   I was thinking if we can avoid allocating `seen_keys` every row? 
   
   My naive suggestion was to build arrays for the input
   
   ```
   keys [0, 1, 2, 0] 
   values ['a', 'b', 'c', 'd']
   seen[1, 0, 0, 0] 
   ```
   
   and the filter keys/values by seen, WDYT would that work?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2328810188


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;

Review Comment:
   right, there is no guarantee, another option with `windows(2)` which I'm not sure if brings any benefit. I'd like to avoid access by index twice as behind the scene rustc spends some ticks on boundary check. Lets leave it as is for now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2331438737


##########
datafusion/spark/src/function/map/map_from_arrays.rs:
##########
@@ -0,0 +1,207 @@
+// 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.
+
+use std::any::Any;
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanBuilder, MapArray, StructArray};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::{DataType, Field, Fields};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, internal_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct MapFromArrays {
+    signature: Signature,
+}
+
+impl Default for MapFromArrays {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MapFromArrays {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(2, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for MapFromArrays {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "map_from_arrays"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [key_type, value_type] = take_function_args("map_from_arrays", arg_types)?;
+        Ok(return_type_from_key_value_types(
+            get_element_type(key_type)?,
+            get_element_type(value_type)?,
+        ))
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: datafusion_expr::ScalarFunctionArgs,
+    ) -> Result<ColumnarValue> {
+        make_scalar_function(map_from_arrays_inner, vec![])(&args.args)
+    }
+}
+
+fn get_list_field(data_type: &DataType) -> Result<&Arc<Field>> {
+    match data_type {
+        DataType::List(element)
+        | DataType::LargeList(element)
+        | DataType::FixedSizeList(element, _) => Ok(element),
+        _ => exec_err!(
+            "map_from_arrays expects 2 listarrays for keys and values as arguments, got {data_type:?}"
+        ),
+    }
+}
+
+fn get_element_type(data_type: &DataType) -> Result<&DataType> {
+    get_list_field(data_type).map(|field| field.data_type())
+}
+
+pub fn return_type_from_key_value_types(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> DataType {
+    DataType::Map(
+        Arc::new(Field::new(
+            "entries",
+            DataType::Struct(Fields::from(vec![
+                // the key must not be nullable
+                Field::new("key", key_type.clone(), false),
+                Field::new("value", value_type.clone(), true),
+            ])),
+            false, // the entry is not nullable
+        )),
+        false, // the keys are not sorted
+    )
+}
+
+fn get_list_values(array: &ArrayRef) -> Result<&ArrayRef> {
+    match array.data_type() {
+        DataType::List(_) => Ok(array.as_list::<i32>().values()),
+        DataType::LargeList(_) => Ok(array.as_list::<i64>().values()),
+        DataType::FixedSizeList(..) => Ok(array.as_fixed_size_list().values()),
+        wrong_type => internal_err!(
+            "get_list_values expects List/LargeList/FixedSizeList as argument, got {wrong_type:?}"
+        ),
+    }
+}
+
+fn map_from_arrays_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let [keys, values] = take_function_args("map_from_arrays", args)?;
+
+    let flat_keys = get_list_values(keys)?;
+    let flat_values = get_list_values(values)?;
+
+    let offsets: Cow<[i32]> = match keys.data_type() {
+        DataType::List(_) => Ok(Cow::Borrowed(keys.as_list::<i32>().offsets().as_ref())),
+        DataType::LargeList(_) => Ok(Cow::Owned(
+            keys.as_list::<i64>()
+                .offsets()
+                .iter()
+                .map(|i| *i as i32)
+                .collect::<Vec<_>>(),
+        )),
+        DataType::FixedSizeList(_, size) => Ok(Cow::Owned(
+             (0..=keys.len() as i32).map(|i| size * i).collect()
+        )),
+        wrong_type => internal_err!(
+            "map_from_arrays expects List/LargeList/FixedSizeList as first argument, got {wrong_type:?}"
+        ),
+    }?;
+
+    map_from_keys_values_offsets(flat_keys, flat_values, &offsets)
+}
+
+pub fn map_from_keys_values_offsets(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<ArrayRef> {
+    let (keys, values, offsets) = map_deduplicate_keys(keys, values, offsets)?;
+
+    let fields = Fields::from(vec![
+        Field::new("key", keys.data_type().clone(), false),
+        Field::new("value", values.data_type().clone(), true),
+    ]);
+    let entries = StructArray::try_new(fields.clone(), vec![keys, values], None)?;
+    let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
+    Ok(Arc::new(MapArray::try_new(
+        field, offsets, entries, None, false,
+    )?))
+}
+
+pub fn map_deduplicate_keys(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    offsets: &[i32],
+) -> Result<(ArrayRef, ArrayRef, OffsetBuffer<i32>)> {
+    let num_rows = offsets.len() - 1;
+    let mut new_offsets = Vec::with_capacity(num_rows + 1);
+    new_offsets.push(0);
+    let mut last_offset = 0;
+
+    let mut needed_rows_builder = BooleanBuilder::new();
+    for row_num in 0..num_rows {
+        let cur_offset = offsets[row_num] as usize;
+        let next_offset = offsets[row_num + 1] as usize;

Review Comment:
   rewritten with removing cur_offset assignment from offsets array and keys array slicing, now global indexing is used



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(spark): implement Spark `map` function `map_from_arrays` [datafusion]

Posted by "SparkApplicationMaster (via GitHub)" <gi...@apache.org>.
SparkApplicationMaster commented on code in PR #17456:
URL: https://github.com/apache/datafusion/pull/17456#discussion_r2331439273


##########
datafusion/sqllogictest/test_files/spark/map/map_from_arrays.slt:
##########
@@ -0,0 +1,60 @@
+# 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.
+
+# Spark doctests
+query ?
+SELECT map_from_arrays(array(1.0, 3.0), array('2', '4'));
+----
+{1.0: 2, 3.0: 4}
+
+query ?
+SELECT map_from_arrays(array(2, 5), array('a', 'b'));
+----
+{2: a, 5: b}
+
+query ?
+SELECT map_from_arrays(array(1, 2), array('a', NULL));
+----
+{1: a, 2: NULL}
+
+query ?
+SELECT map_from_arrays(cast(array() as array<int>), cast(array() as array<string>));
+----
+{}
+
+# Test with complex types
+query ?
+SELECT map_from_arrays(array(array('a', 'b'), array('c', 'd')), array(struct(1, 2, 3), struct(4, 5, 6)));
+----
+{[a, b]: {c0: 1, c1: 2, c2: 3}, [c, d]: {c0: 4, c1: 5, c2: 6}}
+
+# Test with duplicate keys
+query ?
+SELECT map_from_arrays(array(true, false, true), array('a', NULL, 'b'));
+----
+{false: NULL, true: b}
+
+# Tests with different list types
+query ?
+SELECT map_from_arrays(arrow_cast(array(2, 5), 'LargeList(Int32)'), arrow_cast(array('a', 'b'), 'FixedSizeList(2, Utf8)'));
+----
+{2: a, 5: b}
+
+query ?
+SELECT map_from_arrays(arrow_cast(array('a', 'b', 'c'), 'FixedSizeList(3, Utf8)'), arrow_cast(array(1, 2, 3), 'LargeList(Int32)'));

Review Comment:
   added this test



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org