Skip to content

Apache DataFusion SQL Query Engine

Support GetIndexedFieldExpr for ScalarValue (#2196)

Dmitry Patsuraa11b79e11efd
diff --git a/datafusion/core/tests/sql/expr.rs b/datafusion/core/tests/sql/expr.rs
index 6046fc6d8b..c228d54569 100644
--- a/datafusion/core/tests/sql/expr.rs
+++ b/datafusion/core/tests/sql/expr.rs
@@ -518,6 +518,26 @@ async fn test_crypto_expressions() -> Result<()> {
Ok(())
}
+#[tokio::test]
+async fn test_array_index() -> Result<()> {
+ // By default PostgreSQL uses a one-based numbering convention for arrays, that is, an array of n elements starts with array[1] and ends with array[n]
+ test_expression!("([5,4,3,2,1])[1]", "5");
+ test_expression!("([5,4,3,2,1])[2]", "4");
+ test_expression!("([5,4,3,2,1])[5]", "1");
+ test_expression!("([[1, 2], [2, 3], [3,4]])[1]", "[1, 2]");
+ test_expression!("([[1, 2], [2, 3], [3,4]])[3]", "[3, 4]");
+ test_expression!("([[1, 2], [2, 3], [3,4]])[1][1]", "1");
+ test_expression!("([[1, 2], [2, 3], [3,4]])[2][2]", "3");
+ test_expression!("([[1, 2], [2, 3], [3,4]])[3][2]", "4");
+ // out of bounds
+ test_expression!("([5,4,3,2,1])[0]", "NULL");
+ test_expression!("([5,4,3,2,1])[6]", "NULL");
+ // test_expression!("([5,4,3,2,1])[-1]", "NULL");
+ test_expression!("([5,4,3,2,1])[100]", "NULL");
+
+ Ok(())
+}
+
#[tokio::test]
async fn test_array_literals() -> Result<()> {
// Named, just another syntax
diff --git a/datafusion/core/tests/sql/select.rs b/datafusion/core/tests/sql/select.rs
index 3eb297ed71..9119e21e8b 100644
--- a/datafusion/core/tests/sql/select.rs
+++ b/datafusion/core/tests/sql/select.rs
@@ -529,7 +529,7 @@ async fn query_get_indexed_field() -> Result<()> {
ctx.register_table("ints", table_a)?;
// Original column is micros, convert to millis and check timestamp
- let sql = "SELECT some_list[0] as i0 FROM ints LIMIT 3";
+ let sql = "SELECT some_list[1] as i0 FROM ints LIMIT 3";
let actual = execute_to_batches(&ctx, sql).await;
#[rustfmt::skip]
let expected = vec![
@@ -582,7 +582,7 @@ async fn query_nested_get_indexed_field() -> Result<()> {
ctx.register_table("ints", table_a)?;
// Original column is micros, convert to millis and check timestamp
- let sql = "SELECT some_list[0] as i0 FROM ints LIMIT 3";
+ let sql = "SELECT some_list[1] as i0 FROM ints LIMIT 3";
let actual = execute_to_batches(&ctx, sql).await;
let expected = vec![
"+----------+",
@@ -594,7 +594,7 @@ async fn query_nested_get_indexed_field() -> Result<()> {
"+----------+",
];
assert_batches_eq!(expected, &actual);
- let sql = "SELECT some_list[0][0] as i0 FROM ints LIMIT 3";
+ let sql = "SELECT some_list[1][1] as i0 FROM ints LIMIT 3";
let actual = execute_to_batches(&ctx, sql).await;
#[rustfmt::skip]
let expected = vec![
@@ -666,7 +666,7 @@ async fn query_nested_get_indexed_field_on_struct() -> Result<()> {
];
assert_batches_eq!(expected, &actual);
- let sql = "SELECT some_struct['bar'][0] as i0 FROM structs LIMIT 3";
+ let sql = "SELECT some_struct['bar'][1] as i0 FROM structs LIMIT 3";
let actual = execute_to_batches(&ctx, sql).await;
#[rustfmt::skip]
let expected = vec![
diff --git a/datafusion/expr/src/field_util.rs b/datafusion/expr/src/field_util.rs
index a69171ad6d..629f3952d8 100644
--- a/datafusion/expr/src/field_util.rs
+++ b/datafusion/expr/src/field_util.rs
@@ -28,14 +28,7 @@ use datafusion_common::{DataFusionError, Result, ScalarValue};
pub fn get_indexed_field(data_type: &DataType, key: &ScalarValue) -> Result<Field> {
match (data_type, key) {
(DataType::List(lt), ScalarValue::Int64(Some(i))) => {
- if *i < 0 {
- Err(DataFusionError::Plan(format!(
- "List based indexed access requires a positive int, was {0}",
- i
- )))
- } else {
- Ok(Field::new(&i.to_string(), lt.data_type().clone(), false))
- }
+ Ok(Field::new(&i.to_string(), lt.data_type().clone(), true))
}
(DataType::Struct(fields), ScalarValue::Utf8(Some(s))) => {
if s.is_empty() {
diff --git a/datafusion/physical-expr/src/expressions/get_indexed_field.rs b/datafusion/physical-expr/src/expressions/get_indexed_field.rs
index 04a7a3cc1a..e084674de7 100644
--- a/datafusion/physical-expr/src/expressions/get_indexed_field.rs
+++ b/datafusion/physical-expr/src/expressions/get_indexed_field.rs
@@ -21,6 +21,7 @@ use crate::PhysicalExpr;
use arrow::array::Array;
use arrow::array::{ListArray, StructArray};
use arrow::compute::concat;
+
use arrow::{
datatypes::{DataType, Schema},
record_batch::RecordBatch,
@@ -76,40 +77,54 @@ impl PhysicalExpr for GetIndexedFieldExpr {
}
fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
- let arg = self.arg.evaluate(batch)?;
- match arg {
- ColumnarValue::Array(array) => match (array.data_type(), &self.key) {
- (DataType::List(_) | DataType::Struct(_), _) if self.key.is_null() => {
+ let array = self.arg.evaluate(batch)?.into_array(1);
+ match (array.data_type(), &self.key) {
+ (DataType::List(_) | DataType::Struct(_), _) if self.key.is_null() => {
+ let scalar_null: ScalarValue = array.data_type().try_into()?;
+ Ok(ColumnarValue::Scalar(scalar_null))
+ }
+ (DataType::List(_), ScalarValue::Int64(Some(i))) => {
+ let as_list_array =
+ array.as_any().downcast_ref::<ListArray>().unwrap();
+
+ if *i < 1 || as_list_array.is_empty() {
let scalar_null: ScalarValue = array.data_type().try_into()?;
- Ok(ColumnarValue::Scalar(scalar_null))
+ return Ok(ColumnarValue::Scalar(scalar_null))
}
- (DataType::List(_), ScalarValue::Int64(Some(i))) => {
- let as_list_array =
- array.as_any().downcast_ref::<ListArray>().unwrap();
- if as_list_array.is_empty() {
- let scalar_null: ScalarValue = array.data_type().try_into()?;
- return Ok(ColumnarValue::Scalar(scalar_null))
- }
- let sliced_array: Vec<Arc<dyn Array>> = as_list_array
- .iter()
- .filter_map(|o| o.map(|list| list.slice(*i as usize, 1)))
- .collect();
+
+ let sliced_array: Vec<Arc<dyn Array>> = as_list_array
+ .iter()
+ .filter_map(|o| match o {
+ Some(list) => if *i as usize > list.len() {
+ None
+ } else {
+ Some(list.slice((*i -1) as usize, 1))
+ },
+ None => None
+ })
+ .collect();
+
+ // concat requires input of at least one array
+ if sliced_array.is_empty() {
+ let scalar_null: ScalarValue = array.data_type().try_into()?;
+ Ok(ColumnarValue::Scalar(scalar_null))
+ } else {
let vec = sliced_array.iter().map(|a| a.as_ref()).collect::<Vec<&dyn Array>>();
let iter = concat(vec.as_slice()).unwrap();
+
Ok(ColumnarValue::Array(iter))
}
- (DataType::Struct(_), ScalarValue::Utf8(Some(k))) => {
- let as_struct_array = array.as_any().downcast_ref::<StructArray>().unwrap();
- match as_struct_array.column_by_name(k) {
- None => Err(DataFusionError::Execution(format!("get indexed field {} not found in struct", k))),
- Some(col) => Ok(ColumnarValue::Array(col.clone()))
- }
+ }
+ (DataType::Struct(_), ScalarValue::Utf8(Some(k))) => {
+ let as_struct_array = array.as_any().downcast_ref::<StructArray>().unwrap();
+ match as_struct_array.column_by_name(k) {
+ None => Err(DataFusionError::Execution(format!("get indexed field {} not found in struct", k))),
+ Some(col) => Ok(ColumnarValue::Array(col.clone()))
}
- (dt, key) => Err(DataFusionError::NotImplemented(format!("get indexed field is only possible on lists with int64 indexes. Tried {} with {} index", dt, key))),
- },
- ColumnarValue::Scalar(_) => Err(DataFusionError::NotImplemented(
- "field access is not yet implemented for scalar values".to_string(),
- )),
+ }
+ (DataType::List(_), key) => Err(DataFusionError::Execution(format!("get indexed field is only possible on lists with int64 indexes. Tried with {:?} index", key))),
+ (DataType::Struct(_), key) => Err(DataFusionError::Execution(format!("get indexed field is only possible on struct with utf8 indexes. Tried with {:?} index", key))),
+ (dt, key) => Err(DataFusionError::Execution(format!("get indexed field is only possible on lists with int64 indexes or struct with utf8 indexes. Tried {:?} with {:?} index", dt, key))),
}
}
}
@@ -186,7 +201,7 @@ mod tests {
];
for (i, expected) in expected_list.into_iter().enumerate() {
- get_indexed_field_test(list_of_lists.clone(), i as i64, expected)?;
+ get_indexed_field_test(list_of_lists.clone(), (i + 1) as i64, expected)?;
}
Ok(())
}
@@ -198,7 +213,7 @@ mod tests {
let mut lb = ListBuilder::new(builder);
let expr = col("l", &schema).unwrap();
let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(lb.finish())])?;
- let key = ScalarValue::Int64(Some(0));
+ let key = ScalarValue::Int64(Some(1));
let expr = Arc::new(GetIndexedFieldExpr::new(expr, key));
let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
assert!(result.is_empty());
@@ -225,14 +240,14 @@ mod tests {
fn get_indexed_field_invalid_scalar() -> Result<()> {
let schema = list_schema("l");
let expr = lit(ScalarValue::Utf8(Some("a".to_string())));
- get_indexed_field_test_failure(schema, expr, ScalarValue::Int64(Some(0)), "This feature is not implemented: field access is not yet implemented for scalar values")
+ get_indexed_field_test_failure(schema, expr, ScalarValue::Int64(Some(0)), "Execution error: get indexed field is only possible on lists with int64 indexes or struct with utf8 indexes. Tried Utf8 with Int64(0) index")
}
#[test]
fn get_indexed_field_invalid_list_index() -> Result<()> {
let schema = list_schema("l");
let expr = col("l", &schema).unwrap();
- get_indexed_field_test_failure(schema, expr, ScalarValue::Int8(Some(0)), "This feature is not implemented: get indexed field is only possible on lists with int64 indexes. Tried List(Field { name: \"item\", data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: None }) with 0 index")
+ get_indexed_field_test_failure(schema, expr, ScalarValue::Int8(Some(0)), "Execution error: get indexed field is only possible on lists with int64 indexes. Tried with Int8(0) index")
}
fn build_struct(
@@ -323,7 +338,7 @@ mod tests {
for (i, expected) in expected_strings.into_iter().enumerate() {
let get_nested_str_expr = Arc::new(GetIndexedFieldExpr::new(
get_list_expr.clone(),
- ScalarValue::Int64(Some(i as i64)),
+ ScalarValue::Int64(Some((i + 1) as i64)),
));
let result = get_nested_str_expr
.evaluate(&batch)?