datafusion_functions_nested/expr_ext.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Extension methods for Expr.
6
7use datafusion_expr::Expr;
8
9use crate::extract::{array_element, array_slice};
10
11/// Return access to the element field. Example `expr["name"]`
12///
13/// ## Example Access element 2 from column "c1"
14///
15/// For example if column "c1" holds documents like this
16///
17/// ```json
18/// [10, 20, 30, 40]
19/// ```
20///
21/// You can access the value "30" with
22///
23/// ```
24/// # use datafusion_expr::{lit, col, Expr};
25/// # use datafusion_functions_nested::expr_ext::IndexAccessor;
26/// let expr = col("c1").index(lit(3));
27/// assert_eq!(expr.schema_name().to_string(), "c1[Int32(3)]");
28/// ```
29pub trait IndexAccessor {
30 fn index(self, key: Expr) -> Expr;
31}
32
33impl IndexAccessor for Expr {
34 fn index(self, key: Expr) -> Expr {
35 array_element(self, key)
36 }
37}
38
39/// Return elements between `1` based `start` and `stop`, for
40/// example `expr[1:3]`
41///
42/// ## Example: Access element 2, 3, 4 from column "c1"
43///
44/// For example if column "c1" holds documents like this
45///
46/// ```json
47/// [10, 20, 30, 40]
48/// ```
49///
50/// You can access the value `[20, 30, 40]` with
51///
52/// ```
53/// # use datafusion_expr::{lit, col};
54/// # use datafusion_functions_nested::expr_ext::SliceAccessor;
55/// let expr = col("c1").range(lit(2), lit(4));
56/// assert_eq!(expr.schema_name().to_string(), "c1[Int32(2):Int32(4)]");
57/// ```
58pub trait SliceAccessor {
59 fn range(self, start: Expr, stop: Expr) -> Expr;
60}
61
62impl SliceAccessor for Expr {
63 fn range(self, start: Expr, stop: Expr) -> Expr {
64 array_slice(self, start, stop, None)
65 }
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 use datafusion_expr::{col, lit};
73
74 #[test]
75 fn test_index() {
76 let expr1 = col("a").index(lit(1));
77 let expr2 = array_element(col("a"), lit(1));
78 assert_eq!(expr1, expr2);
79 }
80
81 #[test]
82 fn test_range() {
83 let expr1 = col("a").range(lit(1), lit(2));
84 let expr2 = array_slice(col("a"), lit(1), lit(2), None);
85 assert_eq!(expr1, expr2);
86 }
87}