UNPKG

edgevector-db-sdk

Version:

Official TypeScript/JavaScript SDK for EdgeVector DB - A globally distributed, edge-native database platform combining document storage, vector search, time series, and real-time streaming

533 lines 15.9 kB
/** * Time series operations for high-performance metrics and analytics */ import { EventEmitter } from 'eventemitter3'; import { HttpClient } from './http-client'; import { EdgeVectorConfig, TimeSeriesPoint, TimeSeriesQuery, TimeSeriesResult, TimeSeriesSchema, DownsamplingRule, AggregationType, AggregationSpec } from '../types'; export interface TimeSeriesWriteOptions { /** Batch size for bulk writes */ batchSize?: number; /** Flush interval in milliseconds */ flushInterval?: number; /** Enable compression */ compression?: boolean; /** Precision for timestamps */ precision?: 'nanosecond' | 'microsecond' | 'millisecond' | 'second'; /** Tags to apply to all points */ defaultTags?: Record<string, string>; } export interface TimeSeriesStreamOptions { /** Buffer size for streaming */ bufferSize?: number; /** Compression type */ compression?: 'gzip' | 'lz4' | 'none'; /** Format for streaming data */ format?: 'json' | 'line-protocol' | 'parquet'; } export interface ContinuousQueryOptions { /** Query name */ name: string; /** SQL query to execute */ query: string; /** Execution interval */ interval: string; /** Data retention period */ retention?: string; /** Output collection */ outputCollection?: string; /** Enable query */ enabled?: boolean; } export interface TimeSeriesSubscriptionOptions { /** Metrics to subscribe to */ metrics: string | string[]; /** Tag filters */ filters?: Record<string, string | string[]>; /** Aggregation window */ window?: string; /** Aggregation functions */ aggregations?: AggregationType[]; /** Real-time threshold for anomaly detection */ anomalyThreshold?: number; /** Buffer size for real-time updates */ bufferSize?: number; } export interface AnomalyDetectionOptions { /** Detection method */ method: 'isolation_forest' | 'statistical' | 'threshold' | 'seasonal'; /** Sensitivity level (0-1) */ sensitivity?: number; /** Training window size */ trainingWindow?: string; /** Minimum anomaly score */ minScore?: number; /** Context window for comparison */ contextWindow?: string; } export interface ForecastingOptions { /** Forecasting method */ method: 'prophet' | 'arima' | 'linear_regression' | 'exponential_smoothing'; /** Forecast horizon */ horizon: string; /** Include confidence intervals */ includeConfidence?: boolean; /** Confidence level (0-1) */ confidenceLevel?: number; /** Seasonal periods to consider */ seasonalPeriods?: string[]; } /** * Time series operations class for metrics, analytics, and real-time data processing * * @example * ```typescript * const ts = db.collection('metrics').timeseries(); * * // Write time series data * await ts.write({ * metric: 'cpu_usage', * timestamp: Date.now(), * value: 85.2, * tags: { host: 'server-1', region: 'us-east' } * }); * * // Query time series data * const results = await ts.query({ * metric: 'cpu_usage', * timeRange: { start: '-1h', end: 'now' }, * aggregations: [{ type: 'avg', alias: 'average_cpu' }], * interval: '5m' * }); * ``` */ export declare class TimeSeriesOperations extends EventEmitter { private httpClient; private baseUrl; private config; private writeBuffer; private writeTimer; private writeOptions; constructor(httpClient: HttpClient, baseUrl: string, config: EdgeVectorConfig); /** * Write a single time series point * * @param point - Time series data point * @param options - Write options * * @example * ```typescript * await ts.write({ * metric: 'temperature', * timestamp: Date.now(), * value: 22.5, * tags: { sensor: 'sensor-1', location: 'warehouse' }, * fields: { humidity: 45.2, pressure: 1013.25 } * }); * ``` */ write(point: TimeSeriesPoint, options?: TimeSeriesWriteOptions): Promise<void>; /** * Write multiple time series points in batch * * @param points - Array of time series points * @param options - Write options * * @example * ```typescript * const points = [ * { metric: 'cpu_usage', timestamp: Date.now(), value: 85.2, tags: { host: 'server-1' } }, * { metric: 'memory_usage', timestamp: Date.now(), value: 67.8, tags: { host: 'server-1' } } * ]; * * await ts.writeBatch(points); * ``` */ writeBatch(points: TimeSeriesPoint[], options?: TimeSeriesWriteOptions): Promise<void>; /** * Create a write stream for high-throughput ingestion * * @param options - Stream options * @returns Write stream * * @example * ```typescript * const stream = await ts.createWriteStream({ * batchSize: 5000, * flushInterval: 100, * compression: true * }); * * // Write data continuously * setInterval(() => { * stream.write({ * metric: 'requests_per_second', * timestamp: Date.now(), * value: Math.random() * 100, * tags: { service: 'api' } * }); * }, 100); * ``` */ createWriteStream(options?: TimeSeriesStreamOptions): Promise<TimeSeriesWriteStream>; /** * Query time series data with aggregations * * @param query - Time series query * @returns Query results * * @example * ```typescript * const results = await ts.query({ * metric: 'cpu_usage', * timeRange: { start: '-24h', end: 'now' }, * filters: { host: 'server-1', region: 'us-east' }, * aggregations: [ * { type: 'avg', alias: 'average' }, * { type: 'p95', alias: 'p95' }, * { type: 'max', alias: 'maximum' } * ], * groupBy: ['host'], * interval: '1h', * fill: 'linear' * }); * ``` */ query(query: TimeSeriesQuery): Promise<TimeSeriesResult[]>; /** * Query latest values for metrics * * @param metrics - Metric names or patterns * @param filters - Tag filters * @returns Latest values * * @example * ```typescript * const latest = await ts.queryLatest(['cpu_usage', 'memory_usage'], { * host: 'server-1' * }); * ``` */ queryLatest(metrics: string | string[], filters?: Record<string, string | string[]>): Promise<TimeSeriesResult[]>; /** * Execute raw SQL query for complex analytics * * @param sql - SQL query string * @param params - Query parameters * @returns Query results * * @example * ```typescript * const results = await ts.sql(` * SELECT * time_bucket('1 hour', timestamp) as hour, * avg(value) as avg_cpu, * max(value) as max_cpu * FROM timeseries * WHERE metric = ? AND timestamp >= now() - interval '24 hours' * GROUP BY hour * ORDER BY hour DESC * `, ['cpu_usage']); * ``` */ sql(sql: string, params?: any[]): Promise<any[]>; /** * Calculate moving averages for a metric * * @param metric - Metric name * @param window - Window size (e.g., '15m', '1h') * @param options - Additional options * @returns Moving average results * * @example * ```typescript * const movingAvg = await ts.movingAverage('cpu_usage', '15m', { * timeRange: { start: '-24h' }, * filters: { host: 'server-1' } * }); * ``` */ movingAverage(metric: string, window: string, options?: { timeRange?: { start: string | number | Date; end?: string | number | Date; }; filters?: Record<string, string | string[]>; groupBy?: string[]; }): Promise<TimeSeriesResult[]>; /** * Calculate rate of change (derivative) for a metric * * @param metric - Metric name * @param options - Calculation options * @returns Rate of change results * * @example * ```typescript * const rates = await ts.rate('requests_total', { * interval: '1m', * timeRange: { start: '-1h' } * }); * ``` */ rate(metric: string, options?: { interval?: string; timeRange?: { start: string | number | Date; end?: string | number | Date; }; filters?: Record<string, string | string[]>; groupBy?: string[]; }): Promise<TimeSeriesResult[]>; /** * Perform aggregation across multiple metrics * * @param aggregation - Aggregation specification * @returns Aggregated results * * @example * ```typescript * const result = await ts.aggregate({ * metrics: ['cpu_usage', 'memory_usage'], * timeRange: { start: '-1h', end: 'now' }, * groupBy: ['host', 'region'], * aggregations: [ * { type: 'avg', alias: 'mean' }, * { type: 'p95', alias: 'p95' } * ], * interval: '5m' * }); * ``` */ aggregate(aggregation: { metrics: string | string[]; timeRange: { start: string | number | Date; end?: string | number | Date; }; groupBy?: string[]; aggregations: AggregationSpec[]; interval?: string; filters?: Record<string, string | string[]>; having?: Record<string, any>; }): Promise<TimeSeriesResult[]>; /** * Detect anomalies in time series data * * @param metric - Metric name * @param options - Anomaly detection options * @returns Detected anomalies * * @example * ```typescript * const anomalies = await ts.detectAnomalies('error_rate', { * method: 'isolation_forest', * sensitivity: 0.8, * trainingWindow: '7d', * timeRange: { start: '-24h' } * }); * ``` */ detectAnomalies(metric: string, options: AnomalyDetectionOptions & { timeRange?: { start: string | number | Date; end?: string | number | Date; }; filters?: Record<string, string | string[]>; }): Promise<Array<{ timestamp: number; value: number; expected: number; score: number; severity: 'low' | 'medium' | 'high' | 'critical'; tags: Record<string, string>; }>>; /** * Generate forecasts for time series data * * @param metric - Metric name * @param options - Forecasting options * @returns Forecast results * * @example * ```typescript * const forecast = await ts.forecast('sales', { * method: 'prophet', * horizon: '7d', * includeConfidence: true, * seasonalPeriods: ['daily', 'weekly'] * }); * ``` */ forecast(metric: string, options: ForecastingOptions & { timeRange?: { start: string | number | Date; end?: string | number | Date; }; filters?: Record<string, string | string[]>; }): Promise<{ forecast: Array<{ timestamp: number; value: number; lower?: number; upper?: number; }>; metrics: { mae: number; mape: number; rmse: number; }; model: string; }>; /** * Set schema and retention rules for a metric * * @param schema - Time series schema * * @example * ```typescript * await ts.setSchema({ * metric: 'cpu_usage', * dataType: 'gauge', * unit: 'percent', * description: 'CPU utilization percentage', * retentionDays: 30, * downsamplingRules: [ * { interval: '1m', retention: '24h', aggregations: ['avg', 'max'] }, * { interval: '5m', retention: '7d', aggregations: ['avg'] }, * { interval: '1h', retention: '30d', aggregations: ['avg'] } * ], * compressionType: 'gorilla' * }); * ``` */ setSchema(schema: TimeSeriesSchema): Promise<void>; /** * Get schema for a metric * * @param metric - Metric name * @returns Metric schema */ getSchema(metric: string): Promise<TimeSeriesSchema | null>; /** * Set up automatic downsampling rules * * @param metric - Metric name * @param rules - Downsampling rules * * @example * ```typescript * await ts.setDownsampling('response_time', [ * { interval: '1m', retention: '24h', aggregations: ['avg', 'p95', 'p99'] }, * { interval: '5m', retention: '7d', aggregations: ['avg', 'p95'] }, * { interval: '1h', retention: '30d', aggregations: ['avg'] } * ]); * ``` */ setDownsampling(metric: string, rules: DownsamplingRule[]): Promise<void>; /** * Subscribe to real-time time series updates * * @param options - Subscription options * @param callback - Data callback function * @returns Subscription handle * * @example * ```typescript * const subscription = await ts.subscribe({ * metrics: ['cpu.*', 'memory.*'], * filters: { host: 'server-1' }, * window: '10s', * aggregations: ['avg', 'max'] * }, (data) => { * console.log('Real-time update:', data); * }); * ``` */ subscribe(options: TimeSeriesSubscriptionOptions, callback: (data: TimeSeriesResult) => void): Promise<{ unsubscribe: () => Promise<void>; }>; /** * Create a continuous query for real-time aggregations * * @param options - Continuous query options * * @example * ```typescript * await ts.createContinuousQuery({ * name: 'hourly_cpu_summary', * query: ` * INSERT INTO cpu_hourly * SELECT * time_bucket('1 hour', timestamp) as hour, * tags->>'host' as host, * avg(value) as avg_cpu, * max(value) as max_cpu, * count(*) as data_points * FROM timeseries * WHERE metric = 'cpu_usage' AND timestamp >= ? * GROUP BY hour, host * `, * interval: '5m', * retention: '90d' * }); * ``` */ createContinuousQuery(options: ContinuousQueryOptions): Promise<void>; /** * List all continuous queries * * @returns Array of continuous queries */ listContinuousQueries(): Promise<ContinuousQueryOptions[]>; /** * Drop a continuous query * * @param name - Query name */ dropContinuousQuery(name: string): Promise<void>; /** * Flush any buffered writes immediately */ flush(): Promise<void>; /** * Get time series statistics * * @param metric - Metric name (optional) * @returns Statistics */ getStats(metric?: string): Promise<{ totalPoints: number; totalMetrics: number; retentionSize: number; compressionRatio: number; ingestionRate: number; }>; private validatePoint; private validateQuery; private processPoint; private addToBuffer; } /** * Write stream for high-throughput time series ingestion */ export declare class TimeSeriesWriteStream extends EventEmitter { private httpClient; private baseUrl; private options; private buffer; private flushTimer; constructor(httpClient: HttpClient, baseUrl: string, options: TimeSeriesStreamOptions); /** * Write a point to the stream */ write(point: TimeSeriesPoint): void; /** * Flush buffered points */ flush(): Promise<void>; /** * Close the stream */ close(): Promise<void>; } //# sourceMappingURL=timeseries-operations.d.ts.map