Forecasting & Geospatial Functions
Built-in forecasting and geospatial UDFs for advanced time series analytics. Predict future values directly in SQL queries and perform spatial calculations on location-aware time series data without external tools or libraries.
All forecasting and geospatial functions are implemented as native UDFs within the DataFusion query engine. They run in-process with zero serialization overhead, enabling real-time predictions and spatial queries alongside standard SQL aggregations.
Forecasting Functions
MynaDB provides a suite of forecasting functions that operate on time series data to predict future values. These functions analyze historical patterns and extrapolate forward by the specified number of periods.
| Function | Description |
|---|---|
forecast_linear(column, periods) |
Simple linear regression forecast. Fits a straight line to historical data and projects forward by the given number of periods. |
forecast_ema(column, periods, alpha) |
Exponential moving average forecast. Uses weighted averaging with a smoothing factor (alpha between 0 and 1) for trend-sensitive predictions. |
forecast_arima(column, periods, p, d, q) |
ARIMA model forecast. Autoregressive integrated moving average with configurable order parameters p (AR), d (differencing), and q (MA). |
forecast_auto(column, periods) |
Automatic model selection forecast. Evaluates multiple models and selects the best fit based on AIC/BIC criteria. |
forecast_series(column, periods, model) |
Forecast using a named model. The model parameter accepts 'linear', 'ema', 'arima', 'holt_winters', or 'seasonal'. |
forecast_linear
Fits a simple linear regression (least squares) to the historical data and projects the trend forward. Best suited for data with a consistent upward or downward trend and minimal seasonality.
-- Predict the next 12 hourly CPU usage values using linear regression
SELECT
forecast_linear(usage, 12) AS predicted
FROM cpu
WHERE host = 'server01'
GROUP BY time(1h);
forecast_ema
Uses an exponential moving average with a configurable smoothing factor. A higher alpha
(closer to 1) gives more weight to recent observations, making the forecast more responsive to
recent changes. A lower alpha (closer to 0) produces smoother, more stable predictions.
-- Forecast next 24 data points with EMA (alpha=0.3 for moderate smoothing)
SELECT
time_bucket('15 minutes', time) AS bucket,
AVG(temperature) AS actual,
forecast_ema(temperature, 24, 0.3) AS predicted
FROM sensors.default.environment
WHERE location = 'datacenter-east'
AND time > now() - INTERVAL '7 days'
GROUP BY bucket
ORDER BY bucket;
forecast_arima
Implements the ARIMA (Autoregressive Integrated Moving Average) model, which is well-suited for
time series with complex trends and autocorrelation. The parameters p, d,
and q control the autoregressive order, differencing degree, and moving average order
respectively.
-- ARIMA(2,1,1) forecast for memory usage over the next 48 periods
SELECT
time_bucket('30 minutes', time) AS bucket,
AVG(mem_used_percent) AS actual,
forecast_arima(mem_used_percent, 48, 2, 1, 1) AS predicted
FROM mydb.default.system_metrics
WHERE host = 'db-primary'
AND time > now() - INTERVAL '14 days'
GROUP BY bucket
ORDER BY bucket;
forecast_auto
Automatically evaluates multiple forecasting models (linear, EMA, ARIMA variants) against the input data and selects the best-fitting model based on information criteria (AIC/BIC). This is the recommended function when you are unsure which model best fits your data.
-- Let MynaDB automatically select the best forecasting model
SELECT
time_bucket('1 hour', time) AS bucket,
AVG(request_rate) AS actual,
forecast_auto(request_rate, 72) AS predicted
FROM mydb.default.api_metrics
WHERE service = 'payment-gateway'
AND time > now() - INTERVAL '30 days'
GROUP BY bucket
ORDER BY bucket;
forecast_series
A flexible forecasting function that accepts the model name as a string parameter. This is useful when the model selection is driven by application logic or when comparing different models on the same data.
-- Forecast using Holt-Winters for seasonal data (e.g., daily traffic patterns)
SELECT
time_bucket('1 hour', time) AS bucket,
AVG(active_connections) AS actual,
forecast_series(active_connections, 168, 'holt_winters') AS predicted
FROM mydb.default.network
WHERE interface = 'eth0'
AND time > now() - INTERVAL '60 days'
GROUP BY bucket
ORDER BY bucket;
-- Compare different models side by side
SELECT
time_bucket('1 hour', time) AS bucket,
AVG(cpu_usage) AS actual,
forecast_series(cpu_usage, 24, 'linear') AS linear_pred,
forecast_series(cpu_usage, 24, 'ema') AS ema_pred,
forecast_series(cpu_usage, 24, 'seasonal') AS seasonal_pred
FROM mydb.default.host_metrics
WHERE host = 'web-01'
AND time > now() - INTERVAL '14 days'
GROUP BY bucket
ORDER BY bucket;
Linear works best for data with a clear trend and no seasonality.
EMA is ideal for noisy data where recent values matter most.
ARIMA handles complex autocorrelated patterns.
Holt-Winters and Seasonal excel at data with repeating
periodic patterns (e.g., daily or weekly cycles). When in doubt, use
forecast_auto to let MynaDB choose.
Geospatial Functions
MynaDB includes geospatial UDFs for calculating distances, encoding locations, and performing spatial filtering on time series data with latitude/longitude coordinates. These functions use the WGS84 ellipsoid model for accurate Earth-surface calculations.
| Function | Description |
|---|---|
geo_distance(lat1, lon1, lat2, lon2) |
Calculates the great-circle distance in meters between two geographic points using the Haversine formula. |
geo_hash(lat, lon, precision) |
Encodes a latitude/longitude pair into a Geohash string with the specified precision (1-12 characters). |
geo_within(lat, lon, polygon) |
Returns true if the point is inside the given polygon. The polygon is specified as a WKT string (e.g., 'POLYGON((...))' ). |
geo_bounding_box(lat, lon, min_lat, min_lon, max_lat, max_lon) |
Returns true if the point falls within the specified bounding box (rectangle). |
geo_bearing(lat1, lon1, lat2, lon2) |
Calculates the initial bearing (forward azimuth) in degrees from point 1 to point 2, measured clockwise from north (0-360). |
geo_distance
Computes the great-circle distance between two points on the Earth's surface using the Haversine formula. The result is returned in meters. This is useful for proximity queries, geofencing, and calculating travel distances for IoT fleet tracking.
-- Find all vehicle positions within 5km of a warehouse
SELECT
time,
vehicle_id,
lat,
lon,
geo_distance(lat, lon, 37.7749, -122.4194) AS distance_m
FROM fleet.default.vehicle_positions
WHERE time > now() - INTERVAL '1 hour'
AND geo_distance(lat, lon, 37.7749, -122.4194) < 5000
ORDER BY distance_m ASC;
geo_hash
Encodes geographic coordinates into a Geohash string, which is useful for spatial indexing, clustering nearby points, and efficient area-based grouping. Higher precision values produce longer strings representing smaller geographic areas.
-- Group sensor readings by geographic region (precision 5 ~ 4.9km x 4.9km cells)
SELECT
geo_hash(lat, lon, 5) AS region,
COUNT(*) AS reading_count,
AVG(temperature) AS avg_temp,
MIN(temperature) AS min_temp,
MAX(temperature) AS max_temp
FROM iot.default.weather_stations
WHERE time > now() - INTERVAL '24 hours'
GROUP BY region
ORDER BY avg_temp DESC;
geo_within
Tests whether a point lies inside a polygon defined in Well-Known Text (WKT) format. This is essential for geofencing applications, such as determining if a vehicle has entered or exited a defined zone.
-- Find all delivery trucks currently inside the downtown service zone
SELECT
time,
vehicle_id,
lat,
lon,
speed_kmh
FROM fleet.default.vehicle_positions
WHERE time > now() - INTERVAL '5 minutes'
AND geo_within(lat, lon,
'POLYGON((-122.42 37.77, -122.42 37.79, -122.40 37.79, -122.40 37.77, -122.42 37.77))')
ORDER BY time DESC;
geo_bounding_box
A fast rectangular containment check that determines whether a point falls within a given bounding box. This is computationally cheaper than polygon checks and ideal for initial spatial filtering before applying more precise geometry tests.
-- Filter IoT sensor data to the San Francisco Bay Area bounding box
SELECT
time,
sensor_id,
lat,
lon,
pm25,
pm10
FROM iot.default.air_quality
WHERE time > now() - INTERVAL '6 hours'
AND geo_bounding_box(lat, lon, 37.20, -122.60, 37.90, -122.00)
ORDER BY pm25 DESC
LIMIT 100;
geo_bearing
Calculates the initial bearing (forward azimuth) from one geographic point to another. The result is in degrees measured clockwise from true north (0 = north, 90 = east, 180 = south, 270 = west). Useful for determining movement direction in tracking applications.
-- Calculate heading direction between consecutive vehicle positions
SELECT
time,
vehicle_id,
lat,
lon,
geo_bearing(
LAG(lat) OVER (PARTITION BY vehicle_id ORDER BY time),
LAG(lon) OVER (PARTITION BY vehicle_id ORDER BY time),
lat,
lon
) AS heading_degrees,
geo_distance(
LAG(lat) OVER (PARTITION BY vehicle_id ORDER BY time),
LAG(lon) OVER (PARTITION BY vehicle_id ORDER BY time),
lat,
lon
) AS distance_m
FROM fleet.default.vehicle_positions
WHERE vehicle_id = 'truck-42'
AND time > now() - INTERVAL '2 hours'
ORDER BY time;
Combined Examples
The real power of MynaDB's analytical UDFs emerges when combining forecasting and geospatial functions in a single query. Below are examples that demonstrate advanced use cases leveraging both capabilities together.
Predict Air Quality by Region
Forecast PM2.5 levels for different geographic regions by combining geohash-based grouping with time series forecasting.
-- Forecast PM2.5 levels per geographic region for the next 24 hours
SELECT
geo_hash(lat, lon, 4) AS region,
time_bucket('1 hour', time) AS bucket,
AVG(pm25) AS avg_pm25,
forecast_auto(pm25, 24) AS predicted_pm25
FROM iot.default.air_quality
WHERE time > now() - INTERVAL '30 days'
AND geo_bounding_box(lat, lon, 37.20, -122.60, 37.90, -122.00)
GROUP BY region, bucket
ORDER BY region, bucket;
Fleet Arrival Time Prediction
Estimate arrival times for delivery vehicles by combining distance calculations with speed trend forecasting.
-- Predict remaining travel time for active deliveries
SELECT
vehicle_id,
lat,
lon,
geo_distance(lat, lon, dest_lat, dest_lon) AS remaining_distance_m,
speed_kmh,
forecast_ema(speed_kmh, 6, 0.5) AS predicted_speed,
geo_distance(lat, lon, dest_lat, dest_lon) / (forecast_ema(speed_kmh, 6, 0.5) * 1000.0 / 3600.0) AS eta_seconds,
geo_bearing(lat, lon, dest_lat, dest_lon) AS heading_to_dest
FROM fleet.default.vehicle_positions v
JOIN fleet.default.active_deliveries d
ON v.vehicle_id = d.vehicle_id
WHERE v.time > now() - INTERVAL '30 minutes'
AND d.status = 'in_transit'
ORDER BY eta_seconds ASC;
Geofenced Capacity Forecasting
Forecast resource utilization for servers within a specific data center region, combining spatial filtering with capacity prediction.
-- Forecast disk usage for servers in the US-West region
SELECT
host,
geo_hash(datacenter_lat, datacenter_lon, 3) AS dc_region,
time_bucket('1 day', time) AS bucket,
AVG(disk_used_percent) AS current_usage,
forecast_linear(disk_used_percent, 30) AS predicted_30d,
CASE
WHEN forecast_linear(disk_used_percent, 30) > 90 THEN 'CRITICAL'
WHEN forecast_linear(disk_used_percent, 30) > 75 THEN 'WARNING'
ELSE 'OK'
END AS capacity_status
FROM mydb.default.host_metrics
WHERE time > now() - INTERVAL '90 days'
AND geo_within(datacenter_lat, datacenter_lon,
'POLYGON((-125.0 32.0, -125.0 49.0, -104.0 49.0, -104.0 32.0, -125.0 32.0))')
GROUP BY host, dc_region, bucket
ORDER BY predicted_30d DESC;
Anomaly Detection with Spatial Context
Identify temperature sensor anomalies by comparing actual readings against forecasted values, enriched with spatial proximity data.
-- Detect anomalous temperature readings vs. forecast, grouped by area
SELECT
sensor_id,
geo_hash(lat, lon, 6) AS micro_region,
time_bucket('15 minutes', time) AS bucket,
AVG(temperature) AS actual_temp,
forecast_ema(temperature, 1, 0.2) AS expected_temp,
ABS(AVG(temperature) - forecast_ema(temperature, 1, 0.2)) AS deviation,
geo_distance(lat, lon, 37.7749, -122.4194) AS distance_from_center
FROM iot.default.temperature_sensors
WHERE time > now() - INTERVAL '7 days'
AND geo_bounding_box(lat, lon, 37.70, -122.50, 37.85, -122.35)
GROUP BY sensor_id, micro_region, bucket, lat, lon
HAVING ABS(AVG(temperature) - forecast_ema(temperature, 1, 0.2)) > 5.0
ORDER BY deviation DESC
LIMIT 50;
When combining geospatial filters with forecasting functions, place the spatial filters
(geo_bounding_box, geo_within) in the WHERE clause
to reduce the dataset before the forecasting computation runs. Forecasting functions
benefit from partition pruning via time range filters, so always include a
time > now() - INTERVAL '...' predicate.