DataFusion can also evaluate arbitrary expressions on Arrow arrays.
()
| 126 | |
| 127 | /// DataFusion can also evaluate arbitrary expressions on Arrow arrays. |
| 128 | fn evaluate_demo() -> Result<()> { |
| 129 | // For example, let's say you have some integers in an array |
| 130 | let batch = RecordBatch::try_from_iter([( |
| 131 | "a", |
| 132 | Arc::new(Int32Array::from(vec![4, 5, 6, 7, 8, 7, 4])) as _, |
| 133 | )])?; |
| 134 | |
| 135 | // If you want to find all rows where the expression `a < 5 OR a = 8` is true |
| 136 | let expr = col("a").lt(lit(5)).or(col("a").eq(lit(8))); |
| 137 | |
| 138 | // First, you make a "physical expression" from the logical `Expr` |
| 139 | let df_schema = DFSchema::try_from(batch.schema())?; |
| 140 | let physical_expr = SessionContext::new().create_physical_expr(expr, &df_schema)?; |
| 141 | |
| 142 | // Now, you can evaluate the expression against the RecordBatch |
| 143 | let result = physical_expr.evaluate(&batch)?; |
| 144 | |
| 145 | // The result contain an array that is true only for where `a < 5 OR a = 8` |
| 146 | let expected_result = Arc::new(BooleanArray::from(vec![ |
| 147 | true, false, false, false, true, false, true, |
| 148 | ])) as _; |
| 149 | assert!( |
| 150 | matches!(&result, ColumnarValue::Array(r) if r == &expected_result), |
| 151 | "result: {result:?}" |
| 152 | ); |
| 153 | |
| 154 | Ok(()) |
| 155 | } |
| 156 | |
| 157 | /// In addition to easy construction, DataFusion exposes APIs for simplifying |
| 158 | /// such expression so they are more efficient to evaluate. This code is also |
no test coverage detected
searching dependent graphs…