You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2020/09/15 21:02:45 UTC

[GitHub] [arrow] jorgecarleitao opened a new pull request #8199: [Rust] Add substring kernel

jorgecarleitao opened a new pull request #8199:
URL: https://github.com/apache/arrow/pull/8199


   This PR adds a new function to kernels called `substring` that yields a substring of a StringArray starting at a given index, and with a given optional length.
   
   fn substring(array: &Array, start: i32, length: &Option<u32>) -> Result<ArrayRef>
   
   This operation is common in strings, and it is useful for string-based transformations.
   
   The API is inspired by Spark's API.


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#discussion_r495409403



##########
File path: rust/arrow/src/compute/kernels/substring.rs
##########
@@ -0,0 +1,262 @@
+// 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.
+
+//! Defines kernel to extract a substring of a StringArray
+
+use num::Zero;
+use std::convert::TryInto;
+
+use crate::{array::*, buffer::Buffer, datatypes::ToByteSlice};
+use crate::{
+    datatypes::DataType,
+    error::{ArrowError, Result},
+};
+use std::sync::Arc;
+
+macro_rules! substring {

Review comment:
       done :)




----------------------------------------------------------------
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.

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



[GitHub] [arrow] jhorstmann commented on a change in pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
jhorstmann commented on a change in pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#discussion_r489406369



##########
File path: rust/arrow/src/compute/kernels/substring.rs
##########
@@ -0,0 +1,226 @@
+// 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.
+
+//! Defines kernel to extract a substring of a StringArray
+
+use crate::{array::*, buffer::Buffer, datatypes::ToByteSlice};
+use crate::{
+    datatypes::DataType,
+    error::{ArrowError, Result},
+};
+use std::sync::Arc;
+
+/// Returns an ArrayRef with a substring starting from `start` and with optional length `length` of each of the elements in `array`.
+/// `start` can be negative, in which case the start counts from the end of the string.
+pub fn substring(array: &Array, start: i32, length: &Option<u32>) -> Result<ArrayRef> {
+    match array.data_type() {
+        DataType::Utf8 => {
+            // compute current offsets
+            let offsets = array.data_ref().clone().buffers()[0].clone();
+            let offsets: &[u32] = unsafe { offsets.typed_data::<u32>() };
+
+            // compute null bitmap (copy)
+            let null_bit_buffer = array.data_ref().null_buffer().map(|e| e.clone());
+
+            // compute values
+            let values = &array.data_ref().buffers()[1];
+            let data = values.data();
+
+            let mut new_values = Vec::new(); // we have no way to estimate how much this will be.

Review comment:
       I think we can estimate the capacity as `length * array.len()` if the length is specified and `values.len() - (start*array.len())` otherwise.
   
   Hm, actually depends on the semantics of the `length` parameter, is it supposed to be a maximum length or should it be an error if `start+length` goes out of bounds of one entry?




----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me closed pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
nevi-me closed pull request #8199:
URL: https://github.com/apache/arrow/pull/8199


   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] github-actions[bot] commented on pull request #8199: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#issuecomment-692978934


   <!--
     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.
   -->
   
   Thanks for opening a pull request!
   
   Could you open an issue for this pull request on JIRA?
   https://issues.apache.org/jira/browse/ARROW
   
   Then could you also rename pull request title in the following format?
   
       ARROW-${JIRA_ID}: [${COMPONENT}] ${SUMMARY}
   
   See also:
   
     * [Other pull requests](https://github.com/apache/arrow/pulls/)
     * [Contribution Guidelines - How to contribute patches](https://arrow.apache.org/docs/developers/contributing.html#how-to-contribute-patches)
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on a change in pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#discussion_r495116844



##########
File path: rust/arrow/src/compute/kernels/substring.rs
##########
@@ -0,0 +1,262 @@
+// 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.
+
+//! Defines kernel to extract a substring of a StringArray
+
+use num::Zero;
+use std::convert::TryInto;
+
+use crate::{array::*, buffer::Buffer, datatypes::ToByteSlice};
+use crate::{
+    datatypes::DataType,
+    error::{ArrowError, Result},
+};
+use std::sync::Arc;
+
+macro_rules! substring {

Review comment:
       @jorgecarleitao it might be possible to write this as a generic after the refactoring that you did for strings and lists. Do you want to try that? If so, I'll keep this PR open




----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#issuecomment-699684954


   @nevi-me , no problem, clippy is important. I fixed the ones that `cargo clippy` showed as a separate (last) commit in this PR.


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#discussion_r489554226



##########
File path: rust/arrow/src/compute/kernels/substring.rs
##########
@@ -0,0 +1,226 @@
+// 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.
+
+//! Defines kernel to extract a substring of a StringArray
+
+use crate::{array::*, buffer::Buffer, datatypes::ToByteSlice};
+use crate::{
+    datatypes::DataType,
+    error::{ArrowError, Result},
+};
+use std::sync::Arc;
+
+/// Returns an ArrayRef with a substring starting from `start` and with optional length `length` of each of the elements in `array`.
+/// `start` can be negative, in which case the start counts from the end of the string.
+pub fn substring(array: &Array, start: i32, length: &Option<u32>) -> Result<ArrayRef> {
+    match array.data_type() {
+        DataType::Utf8 => {
+            // compute current offsets
+            let offsets = array.data_ref().clone().buffers()[0].clone();
+            let offsets: &[u32] = unsafe { offsets.typed_data::<u32>() };
+
+            // compute null bitmap (copy)
+            let null_bit_buffer = array.data_ref().null_buffer().map(|e| e.clone());
+
+            // compute values
+            let values = &array.data_ref().buffers()[1];
+            let data = values.data();
+
+            let mut new_values = Vec::new(); // we have no way to estimate how much this will be.

Review comment:
       I think that this all depends on what assumptions we make about a typical query. Specifically:
   
   * what is the average start
   * what is the average length
   * what is the average string size
   
   from these 3, we could compute an initial estimation. For example: is this going to be used to treat texts, on which "string size" can go to Mbs, or is this going to be used on 10-12 character arrays?
   
   I considered this discussion beyond the scope of this PR and just went with the least memory-intensive/highest CPU-intensive approach, just because 100% memory usage usually has more nefarious implications than 100% CPU.
   
   The semantics is so that it does not error: it just goes to the maximum/minimum available for each entry. The rational here is that otherwise the user would have to perform some calculation on the side to ensure no errors at runtime, which are never fun. :)




----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on a change in pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#discussion_r491702713



##########
File path: rust/arrow/src/compute/kernels/substring.rs
##########
@@ -0,0 +1,226 @@
+// 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.
+
+//! Defines kernel to extract a substring of a StringArray
+
+use crate::{array::*, buffer::Buffer, datatypes::ToByteSlice};
+use crate::{
+    datatypes::DataType,
+    error::{ArrowError, Result},
+};
+use std::sync::Arc;
+
+/// Returns an ArrayRef with a substring starting from `start` and with optional length `length` of each of the elements in `array`.
+/// `start` can be negative, in which case the start counts from the end of the string.
+pub fn substring(array: &Array, start: i32, length: &Option<u32>) -> Result<ArrayRef> {
+    match array.data_type() {
+        DataType::Utf8 => {
+            // compute current offsets
+            let offsets = array.data_ref().clone().buffers()[0].clone();
+            let offsets: &[u32] = unsafe { offsets.typed_data::<u32>() };
+
+            // compute null bitmap (copy)
+            let null_bit_buffer = array.data_ref().null_buffer().map(|e| e.clone());
+
+            // compute values
+            let values = &array.data_ref().buffers()[1];
+            let data = values.data();
+
+            let mut new_values = Vec::new(); // we have no way to estimate how much this will be.
+            let mut new_offsets = Vec::with_capacity(array.len() + 1);
+
+            let mut length_so_far = 0i32;
+            new_offsets.push(length_so_far);
+            (0..array.len()).for_each(|i| {
+                // the length of this entry
+                let lenght_i = offsets[i + 1] - offsets[i];
+                // compute where we should start slicing this entry
+                let start = offsets[i] as i32
+                    + if start >= 0 {
+                        start
+                    } else {
+                        lenght_i as i32 + start
+                    };
+
+                let start =
+                    start.max(offsets[i] as i32).min(offsets[i + 1] as i32) as usize;
+                // compute the lenght of the slice
+                let length = length
+                    .unwrap_or(lenght_i)
+                    // .max(0) is not needed as it is guaranteed
+                    .min(offsets[i + 1] - start as u32) // so we do not go beyond this entry
+                    as i32;
+
+                length_so_far += length;
+
+                new_offsets.push(length_so_far);
+                new_values.extend_from_slice(&data[start..start + length as usize]);
+            });
+
+            let data = ArrayData::new(
+                DataType::Utf8,
+                array.len(),
+                None,
+                null_bit_buffer,
+                0,
+                vec![
+                    Buffer::from(new_offsets.to_byte_slice()),
+                    Buffer::from(&new_values[..]),
+                ],
+                vec![],
+            );
+            Ok(Arc::new(StringArray::from(Arc::new(data))))
+        }
+        _ => Err(ArrowError::ComputeError(format!(

Review comment:
       We should also support `DataType::LargeUtf8`. We're likely to get a scenario where Arrow users who deal with large data would want to use the `LargeList` and `LargeString` arrays by default (something I would also do), so it's ideal to support both string arrays from the onset going forward.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
nevi-me commented on pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#issuecomment-699469333


   Just checked out the PR and ran a clippy check. The PR and a few others before have introduced a few warnings and errors.
   I find clearing lints helps me learn interesting shortcuts along the line, @jorgecarleitao do you mind checking the lints and clearing them (even those beyond the scope of this PR if you'd like)?
   
   The most interesting for me was learning that to clone an optional reference (`let some_struct_ref = Option<&MyStruct>`), you can use `let some_struct: Option<MyStruct> = some_struct_ref.cloned()` instead of `some_struct_ref.map(|s| s.clone())`.


----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on a change in pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#discussion_r491702713



##########
File path: rust/arrow/src/compute/kernels/substring.rs
##########
@@ -0,0 +1,226 @@
+// 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.
+
+//! Defines kernel to extract a substring of a StringArray
+
+use crate::{array::*, buffer::Buffer, datatypes::ToByteSlice};
+use crate::{
+    datatypes::DataType,
+    error::{ArrowError, Result},
+};
+use std::sync::Arc;
+
+/// Returns an ArrayRef with a substring starting from `start` and with optional length `length` of each of the elements in `array`.
+/// `start` can be negative, in which case the start counts from the end of the string.
+pub fn substring(array: &Array, start: i32, length: &Option<u32>) -> Result<ArrayRef> {
+    match array.data_type() {
+        DataType::Utf8 => {
+            // compute current offsets
+            let offsets = array.data_ref().clone().buffers()[0].clone();
+            let offsets: &[u32] = unsafe { offsets.typed_data::<u32>() };
+
+            // compute null bitmap (copy)
+            let null_bit_buffer = array.data_ref().null_buffer().map(|e| e.clone());
+
+            // compute values
+            let values = &array.data_ref().buffers()[1];
+            let data = values.data();
+
+            let mut new_values = Vec::new(); // we have no way to estimate how much this will be.
+            let mut new_offsets = Vec::with_capacity(array.len() + 1);
+
+            let mut length_so_far = 0i32;
+            new_offsets.push(length_so_far);
+            (0..array.len()).for_each(|i| {
+                // the length of this entry
+                let lenght_i = offsets[i + 1] - offsets[i];
+                // compute where we should start slicing this entry
+                let start = offsets[i] as i32
+                    + if start >= 0 {
+                        start
+                    } else {
+                        lenght_i as i32 + start
+                    };
+
+                let start =
+                    start.max(offsets[i] as i32).min(offsets[i + 1] as i32) as usize;
+                // compute the lenght of the slice
+                let length = length
+                    .unwrap_or(lenght_i)
+                    // .max(0) is not needed as it is guaranteed
+                    .min(offsets[i + 1] - start as u32) // so we do not go beyond this entry
+                    as i32;
+
+                length_so_far += length;
+
+                new_offsets.push(length_so_far);
+                new_values.extend_from_slice(&data[start..start + length as usize]);
+            });
+
+            let data = ArrayData::new(
+                DataType::Utf8,
+                array.len(),
+                None,
+                null_bit_buffer,
+                0,
+                vec![
+                    Buffer::from(new_offsets.to_byte_slice()),
+                    Buffer::from(&new_values[..]),
+                ],
+                vec![],
+            );
+            Ok(Arc::new(StringArray::from(Arc::new(data))))
+        }
+        _ => Err(ArrowError::ComputeError(format!(

Review comment:
       We should also support `DataType::LargeUtf8`. We're likely to get a scenario where Arrow users who deal with large data would want to use the `LargeList` and `LargeString` arrays by default (something I would also do), so it's ideal to support both string arrays from the onset going forward.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] github-actions[bot] commented on pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#issuecomment-692986812


   https://issues.apache.org/jira/browse/ARROW-10019


----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me edited a comment on pull request #8199: ARROW-10019: [Rust] Add substring kernel

Posted by GitBox <gi...@apache.org>.
nevi-me edited a comment on pull request #8199:
URL: https://github.com/apache/arrow/pull/8199#issuecomment-699469333


   Apologies for the back & forth.
   Just checked out the PR and ran a clippy check. The PR and a few others before have introduced a few warnings and errors.
   I find clearing lints helps me learn interesting shortcuts along the line, @jorgecarleitao do you mind checking the lints and clearing them (even those beyond the scope of this PR if you'd like)?
   
   The most interesting for me was learning that to clone an optional reference (`let some_struct_ref = Option<&MyStruct>`), you can use `let some_struct: Option<MyStruct> = some_struct_ref.cloned()` instead of `some_struct_ref.map(|s| s.clone())`.


----------------------------------------------------------------
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.

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