Arrow Flight API

MynaDB exposes an Apache Arrow Flight interface for high-performance data streaming. Arrow Flight is a gRPC-based protocol optimized for transferring large datasets with zero-copy efficiency.

✈ Why Arrow Flight?

Arrow Flight provides 10-100x faster data transfer compared to REST APIs for large result sets. It's ideal for analytics dashboards, data pipelines, and machine learning workloads.

Overview

The Arrow Flight API provides:

Feature HTTP API Arrow Flight
Protocol REST/JSON gRPC/Arrow IPC
Data Format JSON (text) Arrow (binary)
Best For Small queries, writes Large result sets
Streaming No Yes
Client Libraries Any HTTP client Arrow Flight clients

Connection

The Arrow Flight server runs on port 7001 by default (configurable via flight_port).

Default Port 7001
Protocol gRPC (HTTP/2)
Connection String grpc://localhost:7001

Configuration

toml
[server]
http_port = 7000
flight_port = 7001  # Arrow Flight gRPC port

DataFusion CLI

The easiest way to query MynaDB via Flight is using the DataFusion CLI. It provides an interactive SQL shell with full Arrow Flight support.

Installation

bash
# Install via Cargo
cargo install datafusion-cli

# Or download pre-built binary
# https://github.com/apache/arrow-datafusion/releases

Connect to MynaDB

bash
# Connect to Flight server
datafusion-cli --host localhost --port 7001

# With specific database catalog
datafusion-cli --host localhost --port 7001 --catalog mydb

Interactive Session

sql
-- List available tables
SHOW TABLES;

-- Query data
SELECT host, AVG(usage) AS avg_cpu
FROM mydb.default.cpu
WHERE time > now() - interval '1 hour'
GROUP BY host
ORDER BY avg_cpu DESC;

-- Describe table schema
DESCRIBE mydb.default.cpu;

Python Client

Use pyarrow to connect to MynaDB via Arrow Flight.

Installation

bash
pip install pyarrow pandas

Basic Query

python
import pyarrow.flight as flight
import pandas as pd

# Connect to MynaDB
client = flight.connect("grpc://localhost:7001")

# Execute SQL query
sql = """
    SELECT host, region, AVG(usage) as avg_cpu
    FROM mydb.default.cpu
    WHERE time > now() - interval '1 hour'
    GROUP BY host, region
"""

# Get Flight info and read data
flight_info = client.get_flight_info(flight.FlightDescriptor.for_command(sql))
reader = client.do_get(flight_info.endpoints[0].ticket)

# Convert to Pandas DataFrame
df = reader.read_pandas()
print(df)

Streaming Large Results

python
import pyarrow.flight as flight

client = flight.connect("grpc://localhost:7001")

sql = "SELECT * FROM mydb.default.cpu"
flight_info = client.get_flight_info(flight.FlightDescriptor.for_command(sql))

# Stream record batches (memory efficient)
reader = client.do_get(flight_info.endpoints[0].ticket)

total_rows = 0
for batch in reader:
    total_rows += batch.data.num_rows
    # Process each batch...
    print(f"Received batch with {batch.data.num_rows} rows")

print(f"Total rows: {total_rows}")

Integration with Pandas/Polars

python
import pyarrow.flight as flight
import polars as pl

def query_stats_service(sql: str) -> pl.DataFrame:
    """Execute SQL and return Polars DataFrame."""
    client = flight.connect("grpc://localhost:7001")
    flight_info = client.get_flight_info(
        flight.FlightDescriptor.for_command(sql)
    )
    reader = client.do_get(flight_info.endpoints[0].ticket)

    # Read as Arrow table, convert to Polars
    arrow_table = reader.read_all()
    return pl.from_arrow(arrow_table)

# Example usage
df = query_stats_service("""
    SELECT
        date_trunc('minute', to_timestamp(timestamp/1000000000)) as minute,
        host,
        AVG(usage) as avg_cpu,
        MAX(usage) as max_cpu
    FROM mydb.default.cpu
    GROUP BY 1, 2
    ORDER BY 1 DESC
    LIMIT 100
""")
print(df)

Rust Client

Use the arrow-flight crate to connect from Rust applications.

Cargo.toml

toml
[dependencies]
arrow-flight = "50"
arrow = "50"
tonic = "0.10"
tokio = { version = "1", features = ["full"] }
futures = "0.3"

Example Client

rust
use arrow_flight::flight_service_client::FlightServiceClient;
use arrow_flight::{FlightDescriptor, Ticket};
use futures::StreamExt;

async fn query_stats_service() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Flight server
    let mut client = FlightServiceClient::connect(
        "http://localhost:7001"
    ).await?;

    // Create SQL command
    let sql = "SELECT * FROM mydb.default.cpu LIMIT 100";
    let descriptor = FlightDescriptor::new_cmd(sql.to_string());

    // Get flight info
    let flight_info = client
        .get_flight_info(descriptor)
        .await?
        .into_inner();

    // Read data from first endpoint
    if let Some(endpoint) = flight_info.endpoint.first() {
        let ticket = endpoint.ticket.clone().unwrap();
        let mut stream = client.do_get(ticket).await?.into_inner();

        while let Some(batch) = stream.next().await {
            let batch = batch?;
            println!("Received batch with {} bytes", batch.data_body.len());
        }
    }

    Ok(())
}

SQL Queries via Flight

Arrow Flight in MynaDB uses FlightSQL semantics. SQL queries are passed as command descriptors.

Supported Operations

Operation Description Example
SELECT Query data SELECT * FROM cpu
SHOW TABLES List tables SHOW TABLES
DESCRIBE Table schema DESCRIBE cpu
Aggregations GROUP BY, window functions SELECT AVG(x) FROM t GROUP BY y
Joins Cross-table queries SELECT * FROM a JOIN b ON ...

Table Naming

-- Fully qualified name (recommended)
SELECT * FROM mydb.default.cpu;

-- With schema
SELECT * FROM default.cpu;

-- Simple name (uses default catalog/schema)
SELECT * FROM cpu;

Performance Tips

🔥 Performance Best Practices
  • Use column projection - only select needed columns
  • Apply time filters - leverage partition pruning
  • Use streaming reads for large datasets
  • Enable compression for network-bound transfers

Column Projection

-- Good: Only select needed columns
SELECT time, host, usage FROM cpu;

-- Avoid: Selecting all columns
SELECT * FROM cpu;

Time Range Filtering

-- Leverages date partition pruning
SELECT * FROM cpu
WHERE time >= 1704067200000000000  -- epoch nanos
  AND time <  1704153600000000000;

-- Or using date functions
SELECT * FROM cpu
WHERE time > now() - interval '1 day';

Compression Options

python
import pyarrow.flight as flight

# Enable gRPC compression
options = flight.FlightCallOptions(
    headers=[(b"grpc-encoding", b"gzip")]
)

client = flight.connect("grpc://localhost:7001")
flight_info = client.get_flight_info(
    flight.FlightDescriptor.for_command(sql),
    options=options
)

Troubleshooting

Issue Solution
Connection refused Check flight_port config, ensure server is running
Table not found Use fully qualified name: catalog.schema.table
Timeout on large queries Increase gRPC timeout, use streaming reads
Memory issues Stream batches instead of read_all()

Next Steps