-
Notifications
You must be signed in to change notification settings - Fork 12
Add variant_contains UDF #59
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
getChan
wants to merge
5
commits into
datafusion-contrib:main
Choose a base branch
from
getChan:variant-contains-issue-50
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b2eb3a2
Add variant_contains UDF
getChan 16d38d2
chore: remove .idea from gitignore
Copilot a727fe0
Merge pull request #2 from getChan/copilot/remove-idea-from-gitignore
getChan 4e2fb8f
cargo fmt
getChan 99a9760
Merge remote-tracking branch 'origin/variant-contains-issue-50' into …
getChan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| /target | ||
| /data/* | ||
| profile.json.gz | ||
| profile.json.gz | ||
| .idea | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,280 @@ | ||
| use std::sync::Arc; | ||
|
|
||
| use arrow::array::{ArrayRef, BooleanArray}; | ||
| use arrow_schema::DataType; | ||
| use datafusion::common::{exec_datafusion_err, exec_err}; | ||
| use datafusion::error::{DataFusionError, Result}; | ||
| use datafusion::logical_expr::{ | ||
| ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, Volatility, | ||
| }; | ||
| use datafusion::scalar::ScalarValue; | ||
| use parquet_variant::{Variant, VariantPath}; | ||
| use parquet_variant_compute::VariantArray; | ||
|
|
||
| use crate::shared::{path_from_scalar, try_field_as_variant_array, try_parse_string_columnar}; | ||
|
|
||
| #[derive(Debug, Hash, PartialEq, Eq)] | ||
| pub struct VariantContainsUdf { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for VariantContainsUdf { | ||
| fn default() -> Self { | ||
| Self { | ||
| signature: Signature::new(TypeSignature::Any(2), Volatility::Immutable), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn variant_contains( | ||
| variant: Option<&Variant<'_, '_>>, | ||
| path: &VariantPath<'_>, | ||
| ) -> Option<bool> { | ||
| variant.map(|value| value.get_path(path).is_some()) | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for VariantContainsUdf { | ||
| fn as_any(&self) -> &dyn std::any::Any { | ||
| self | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| "variant_contains" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { | ||
| Ok(DataType::Boolean) | ||
| } | ||
|
|
||
| fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { | ||
| let (variant_arg, path_arg) = match args.args.as_slice() { | ||
| [variant_arg, path_arg] => (variant_arg, path_arg), | ||
| _ => return exec_err!("expected 2 arguments"), | ||
| }; | ||
|
|
||
| let variant_field = args | ||
| .arg_fields | ||
| .first() | ||
| .ok_or_else(|| exec_datafusion_err!("expected argument field"))?; | ||
|
|
||
| try_field_as_variant_array(variant_field.as_ref())?; | ||
|
|
||
| match (variant_arg, path_arg) { | ||
| (ColumnarValue::Array(variant_array), ColumnarValue::Scalar(path_scalar)) => { | ||
| if path_scalar.is_null() { | ||
| return exec_err!("path argument must be non-null"); | ||
| } | ||
|
|
||
| let path = path_from_scalar(path_scalar)?; | ||
| let variant_array = VariantArray::try_new(variant_array.as_ref())?; | ||
| let values = variant_array | ||
| .iter() | ||
| .map(|variant| variant_contains(variant.as_ref(), &path)) | ||
| .collect::<Vec<_>>(); | ||
|
|
||
| Ok(ColumnarValue::Array( | ||
| Arc::new(BooleanArray::from(values)) as ArrayRef, | ||
| )) | ||
| } | ||
| (ColumnarValue::Scalar(scalar_variant), ColumnarValue::Scalar(path_scalar)) => { | ||
| let ScalarValue::Struct(variant_array) = scalar_variant else { | ||
| return exec_err!("expected struct array"); | ||
| }; | ||
|
|
||
| if path_scalar.is_null() { | ||
| return exec_err!("path argument must be non-null"); | ||
| } | ||
|
|
||
| let path = path_from_scalar(path_scalar)?; | ||
| let variant_array = VariantArray::try_new(variant_array.as_ref())?; | ||
| let variant = variant_array.iter().next().flatten(); | ||
| let value = variant_contains(variant.as_ref(), &path); | ||
|
|
||
| Ok(ColumnarValue::Scalar(ScalarValue::Boolean(value))) | ||
| } | ||
| (ColumnarValue::Array(variant_array), ColumnarValue::Array(paths)) => { | ||
| if variant_array.len() != paths.len() { | ||
| return exec_err!("expected variant array and paths to be of same length"); | ||
| } | ||
|
|
||
| let variant_array = VariantArray::try_new(variant_array.as_ref())?; | ||
| let paths = try_parse_string_columnar(paths)?; | ||
|
|
||
| let values = variant_array | ||
| .iter() | ||
| .zip(paths) | ||
| .map(|(maybe_variant, path_str)| { | ||
| let path_str = path_str.ok_or_else(|| { | ||
| exec_datafusion_err!("path argument must be non-null") | ||
| })?; | ||
| let path = VariantPath::try_from(path_str) | ||
| .map_err(Into::<DataFusionError>::into)?; | ||
|
|
||
| Ok(variant_contains(maybe_variant.as_ref(), &path)) | ||
| }) | ||
| .collect::<Result<Vec<_>>>()?; | ||
|
|
||
| Ok(ColumnarValue::Array(Arc::new(BooleanArray::from(values)) as ArrayRef)) | ||
| } | ||
| (ColumnarValue::Scalar(scalar_variant), ColumnarValue::Array(paths)) => { | ||
| let ScalarValue::Struct(variant_array) = scalar_variant else { | ||
| return exec_err!("expected struct array"); | ||
| }; | ||
|
|
||
| let variant_array = VariantArray::try_new(variant_array.as_ref())?; | ||
| let variant = variant_array.iter().next().flatten(); | ||
| let paths = try_parse_string_columnar(paths)?; | ||
|
|
||
| let values = paths | ||
| .into_iter() | ||
| .map(|path_str| { | ||
| let path_str = path_str.ok_or_else(|| { | ||
| exec_datafusion_err!("path argument must be non-null") | ||
| })?; | ||
| let path = VariantPath::try_from(path_str) | ||
| .map_err(Into::<DataFusionError>::into)?; | ||
|
|
||
| Ok(variant_contains(variant.as_ref(), &path)) | ||
| }) | ||
| .collect::<Result<Vec<_>>>()?; | ||
|
|
||
| Ok(ColumnarValue::Array(Arc::new(BooleanArray::from(values)) as ArrayRef)) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::sync::Arc; | ||
|
|
||
| use arrow::array::{Array, ArrayRef, BooleanArray, StringArray}; | ||
| use arrow_schema::{Field, Fields}; | ||
| use parquet_variant_compute::VariantType; | ||
|
|
||
| use crate::shared::{build_variant_array_from_json_array, variant_scalar_from_json}; | ||
|
|
||
| use super::*; | ||
|
|
||
| fn arg_fields() -> Vec<Arc<Field>> { | ||
| vec![ | ||
| Arc::new( | ||
| Field::new("input", DataType::Struct(Fields::empty()), true) | ||
| .with_extension_type(VariantType), | ||
| ), | ||
| Arc::new(Field::new("path", DataType::Utf8, true)), | ||
| ] | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_scalar_existing_path_returns_true() { | ||
| let udf = VariantContainsUdf::default(); | ||
| let args = ScalarFunctionArgs { | ||
| args: vec![ | ||
| ColumnarValue::Scalar(variant_scalar_from_json(serde_json::json!({ | ||
| "a": {"b": null} | ||
| }))), | ||
| ColumnarValue::Scalar(ScalarValue::Utf8(Some("a.b".to_string()))), | ||
| ], | ||
| return_field: Arc::new(Field::new("result", DataType::Boolean, true)), | ||
| arg_fields: arg_fields(), | ||
| number_rows: Default::default(), | ||
| config_options: Default::default(), | ||
| }; | ||
|
|
||
| let result = udf.invoke_with_args(args).unwrap(); | ||
| let ColumnarValue::Scalar(ScalarValue::Boolean(Some(value))) = result else { | ||
| panic!("expected boolean scalar") | ||
| }; | ||
|
|
||
| assert!(value); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_scalar_missing_path_returns_false() { | ||
| let udf = VariantContainsUdf::default(); | ||
| let args = ScalarFunctionArgs { | ||
| args: vec![ | ||
| ColumnarValue::Scalar(variant_scalar_from_json(serde_json::json!({ | ||
| "a": 1 | ||
| }))), | ||
| ColumnarValue::Scalar(ScalarValue::Utf8(Some("a.b".to_string()))), | ||
| ], | ||
| return_field: Arc::new(Field::new("result", DataType::Boolean, true)), | ||
| arg_fields: arg_fields(), | ||
| number_rows: Default::default(), | ||
| config_options: Default::default(), | ||
| }; | ||
|
|
||
| let result = udf.invoke_with_args(args).unwrap(); | ||
| let ColumnarValue::Scalar(ScalarValue::Boolean(Some(value))) = result else { | ||
| panic!("expected boolean scalar") | ||
| }; | ||
|
|
||
| assert!(!value); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_array_paths_and_null_variant() { | ||
| let udf = VariantContainsUdf::default(); | ||
| let input = build_variant_array_from_json_array(&[ | ||
| Some(serde_json::json!({"a": 1})), | ||
| Some(serde_json::json!({"a": null})), | ||
| None, | ||
| ]); | ||
| let args = ScalarFunctionArgs { | ||
| args: vec![ | ||
| ColumnarValue::Array(Arc::new(arrow::array::StructArray::from(input)) as ArrayRef), | ||
| ColumnarValue::Array(Arc::new(StringArray::from(vec![ | ||
| Some("a"), | ||
| Some("a"), | ||
| Some("a"), | ||
| ])) as ArrayRef), | ||
| ], | ||
| return_field: Arc::new(Field::new("result", DataType::Boolean, true)), | ||
| arg_fields: arg_fields(), | ||
| number_rows: Default::default(), | ||
| config_options: Default::default(), | ||
| }; | ||
|
|
||
| let result = udf.invoke_with_args(args).unwrap(); | ||
| let ColumnarValue::Array(values) = result else { | ||
| panic!("expected boolean array") | ||
| }; | ||
|
|
||
| let values = values.as_any().downcast_ref::<BooleanArray>().unwrap(); | ||
| assert_eq!(values.into_iter().collect::<Vec<_>>(), vec![Some(true), Some(true), None]); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_array_variant_scalar_path() { | ||
| let udf = VariantContainsUdf::default(); | ||
| let input = build_variant_array_from_json_array(&[ | ||
| Some(serde_json::json!({"a": 1})), | ||
| Some(serde_json::json!({"b": 1})), | ||
| ]); | ||
| let args = ScalarFunctionArgs { | ||
| args: vec![ | ||
| ColumnarValue::Array(Arc::new(arrow::array::StructArray::from(input)) as ArrayRef), | ||
| ColumnarValue::Scalar(ScalarValue::Utf8(Some("a".to_string()))), | ||
| ], | ||
| return_field: Arc::new(Field::new("result", DataType::Boolean, true)), | ||
| arg_fields: arg_fields(), | ||
| number_rows: Default::default(), | ||
| config_options: Default::default(), | ||
| }; | ||
|
|
||
| let result = udf.invoke_with_args(args).unwrap(); | ||
| let ColumnarValue::Array(values) = result else { | ||
| panic!("expected boolean array") | ||
| }; | ||
|
|
||
| let values = values.as_any().downcast_ref::<BooleanArray>().unwrap(); | ||
| assert_eq!(values.into_iter().collect::<Vec<_>>(), vec![Some(true), Some(false)]); | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.