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.

use std::sync::Arc;

use datafusion::arrow::array::{ArrayRef, Int32Array, StringArray};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
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 builder = SessionStateBuilder::new().with_default_features();
    let ctx = new_match_recognize_context(builder)?;

    ctx.register_batch("ticks", ticks_batch()?)?;

    let query = r#"
        SELECT
            ticker,
            start_ts,
            bottom_ts,
            end_ts,
            start_price,
            bottom_price,
            end_price,
            match_no
        FROM ticks
        MATCH_RECOGNIZE (
            PARTITION BY ticker
            ORDER BY ts
            MEASURES
                FIRST(DOWN.ts) AS start_ts,
                LAST(DOWN.ts) AS bottom_ts,
                LAST(UP.ts) AS end_ts,
                FIRST(DOWN.price) AS start_price,
                LAST(DOWN.price) AS bottom_price,
                LAST(UP.price) AS end_price,
                MATCH_NUMBER() AS match_no
            ONE ROW PER MATCH
            AFTER MATCH SKIP PAST LAST ROW
            PATTERN (DOWN+ UP+)
            DEFINE
                DOWN AS price < PREV(price),
                UP AS price > PREV(price)
        )
        ORDER BY ticker, match_no
    "#;

    let batches = ctx.sql(query).await?.collect().await?;
    let formatted = pretty_format_batches(&batches)?.to_string();
    println!("{formatted}");

    let expected = [
        "+--------+----------+-----------+--------+-------------+--------------+-----------+----------+",
        "| ticker | start_ts | bottom_ts | end_ts | start_price | bottom_price | end_price | match_no |",
        "+--------+----------+-----------+--------+-------------+--------------+-----------+----------+",
        "| ACME   | 2        | 3         | 5      | 95          | 90           | 105       | 1        |",
        "| ACME   | 6        | 6         | 7      | 101         | 101          | 108       | 2        |",
        "| ACME   | 8        | 8         | 9      | 99          | 99           | 111       | 3        |",
        "+--------+----------+-----------+--------+-------------+--------------+-----------+----------+",
    ]
    .join("\n");
    assert_eq!(formatted, expected);

    Ok(())
}

fn ticks_batch() -> Result<RecordBatch> {
    let schema = Arc::new(Schema::new(vec![
        Field::new("ticker", DataType::Utf8, false),
        Field::new("ts", DataType::Int32, false),
        Field::new("price", DataType::Int32, false),
    ]));

    let columns: Vec<ArrayRef> = vec![
        Arc::new(StringArray::from(vec![
            "ACME", "ACME", "ACME", "ACME", "ACME", "ACME", "ACME", "ACME", "ACME",
        ])),
        Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9])),
        Arc::new(Int32Array::from(vec![
            120, 95, 90, 98, 105, 101, 108, 99, 111,
        ])),
    ];

    Ok(RecordBatch::try_new(schema, columns)?)
}