datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
// Licensed 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.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Match rows using a running count in DEFINE.

use datafusion::arrow::array::Int64Array;
use datafusion::arrow::util::pretty::pretty_format_batches;
use datafusion::error::Result;
use datafusion::execution::SessionStateBuilder;
use datafusion_match_recognize::new_match_recognize_context;

#[tokio::main]
async fn main() -> Result<()> {
    let ctx =
        new_match_recognize_context(SessionStateBuilder::new().with_default_features())?;
    let batches = ctx
        .sql(
            r#"
            WITH events(ts) AS (VALUES (1), (2), (3), (4), (5))
            SELECT first_ts, last_ts, rows_in_match
            FROM events
            MATCH_RECOGNIZE (
                ORDER BY ts
                MEASURES
                    FIRST(A.ts) AS first_ts,
                    LAST(A.ts) AS last_ts,
                    COUNT(A.*) AS rows_in_match
                ONE ROW PER MATCH
                AFTER MATCH SKIP PAST LAST ROW
                PATTERN (A+)
                DEFINE A AS COUNT(A.*) <= 2
            )
            ORDER BY first_ts
            "#,
        )
        .await?
        .collect()
        .await?;
    println!("{}", pretty_format_batches(&batches)?);

    let actual: Vec<[i64; 3]> = batches
        .iter()
        .flat_map(|batch| {
            let columns: [&Int64Array; 3] = std::array::from_fn(|index| {
                batch.column(index).as_any().downcast_ref().unwrap()
            });
            (0..batch.num_rows())
                .map(|row| columns.each_ref().map(|column| column.value(row)))
                .collect::<Vec<_>>()
        })
        .collect();
    assert_eq!(actual, [[1, 2, 2], [3, 4, 2], [5, 5, 1]]);
    Ok(())
}