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
276 lines (214 loc) ⢠6.77 kB
Markdown
# EdgeVector DB SDK for TypeScript/JavaScript
The official TypeScript/JavaScript SDK for EdgeVector DB - a globally distributed, edge-native database platform combining document storage, vector search, time series analytics, and real-time streaming.
š **Production Ready** - Live at https://edgevector-db.finhub.workers.dev
## Features
- š **Document Database** - MongoDB-compatible API with advanced querying
- š **Vector Search** - AI-powered similarity search with multiple embedding models
- š **Time Series** - High-frequency metrics with real-time analytics
- š“ **Real-time Streaming** - WebSocket and SSE subscriptions
- ā” **Edge-Native** - Sub-10ms latency globally via Cloudflare Workers
- šÆ **Type-Safe** - Full TypeScript support with intelligent auto-completion
- āļø **React Ready** - Built-in hooks and components for React apps
## Quick Start
### Installation
```bash
npm install @edgevector/sdk
# or
yarn add @edgevector/sdk
# or
pnpm add @edgevector/sdk
```
### Basic Usage
```typescript
import { quickStart } from '@edgevector/sdk';
// Initialize client (uses production URL by default)
const client = quickStart(process.env.EDGEVECTOR_API_KEY, 'my-app');
// Get collection
const users = client.db().collection('users');
// Insert documents
await users.insertOne({
name: 'Alice Johnson',
email: 'alice@example.com',
age: 28,
tags: ['developer', 'typescript']
});
// Query documents
const activeUsers = await users.find({ status: 'active' }).toArray();
// Vector search
const vectors = users.vectors();
const embedding = await vectors.generateEmbedding('JavaScript developer');
const similar = await vectors.search(embedding.vector, { limit: 5 });
// Time series metrics
const ts = users.timeseries();
await ts.write({
metric: 'user_logins',
timestamp: Date.now(),
value: 1,
tags: { region: 'us-east' }
});
// Real-time subscriptions
const subscription = await users.watch({ status: 'active' }, (event) => {
console.log('User changed:', event.operationType);
});
```
## React Integration
```tsx
import React from 'react';
import { EdgeVectorProvider, useDocuments } from '@edgevector/sdk/react';
const client = quickStart(process.env.REACT_APP_EDGEVECTOR_API_KEY, 'my-app');
function App() {
return (
<EdgeVectorProvider client={client} database="my-app">
<UserList />
</EdgeVectorProvider>
);
}
function UserList() {
const { data: users, loading, error } = useDocuments('users', {
filter: { status: 'active' },
realtime: true // Auto-update on changes
});
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<ul>
{users.map(user => (
<li key={user._id}>{user.name} - {user.email}</li>
))}
</ul>
);
}
```
## Advanced Features
### Hybrid Search (Vector + Text + Metadata)
```typescript
const results = await vectors.hybridSearch(queryVector, {
textQuery: 'machine learning AI',
vectorWeight: 0.7,
textWeight: 0.2,
metadataWeight: 0.1,
filter: { category: 'technology' }
});
```
### Time Series Analytics
```typescript
// Real-time anomaly detection
const anomalies = await ts.detectAnomalies('cpu_usage', {
method: 'isolation_forest',
sensitivity: 0.8,
timeRange: { start: '-24h' }
});
// Forecasting
const forecast = await ts.forecast('sales', {
method: 'prophet',
horizon: '7d',
includeConfidence: true
});
```
### Transactions
```typescript
const session = await db.startTransaction();
try {
await accounts.updateOne({ id: 'from' }, { $inc: { balance: -100 } });
await accounts.updateOne({ id: 'to' }, { $inc: { balance: 100 } });
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
throw error;
}
```
## Configuration Options
```typescript
import { createClient } from '@edgevector/sdk';
const client = createClient({
// URL defaults to production: https://edgevector-db.finhub.workers.dev
apiKey: 'your-api-key',
database: 'my-app',
// Optional configuration
timeout: 30000,
retry: {
maxAttempts: 3,
initialDelay: 1000,
maxDelay: 10000
},
cache: {
enabled: true,
ttl: 300000, // 5 minutes
maxSize: 100
},
debug: {
enabled: true,
level: 'info'
}
});
```
## Examples
Run the included examples to see the SDK in action:
```bash
# Quick demo (recommended first run)
npm run demo:quick
# Comprehensive examples
npm run demo:comprehensive
# All examples with full configuration
npm run demo
```
## API Reference
### Core Classes
- **`EdgeVectorClient`** - Main client for connecting to EdgeVector DB
- **`Database`** - Database operations and transaction management
- **`Collection`** - Document CRUD operations with MongoDB compatibility
- **`VectorOperations`** - Vector search and AI operations
- **`TimeSeriesOperations`** - Time series data and analytics
- **`RealtimeSubscriptions`** - WebSocket and SSE streaming
### Framework Integrations
- **React**: `@edgevector/sdk/react` - Hooks and providers
- **Next.js**: `@edgevector/sdk/nextjs` - App and Pages router support
- **Remix**: `@edgevector/sdk/remix` - Loader and action utilities
- **Svelte**: `@edgevector/sdk/svelte` - Stores and components
## Performance
EdgeVector DB is built for speed:
- ā” **Sub-10ms** vector search globally
- š **1M+ vectors** per database
- š **1M+ metrics/second** time series ingestion
- š **Global edge deployment** via Cloudflare Workers
- š¾ **Automatic caching** with intelligent invalidation
## TypeScript Support
The SDK is built with TypeScript first:
```typescript
interface User {
name: string;
email: string;
age: number;
preferences: {
theme: 'light' | 'dark';
notifications: boolean;
};
}
// Full type safety
const users = db.collection<User>('users');
const user = await users.findOne({ email: 'alice@example.com' });
// user is typed as User | null
```
## Error Handling
Built-in retry logic and comprehensive error types:
```typescript
import { ValidationError, NetworkError } from '@edgevector/sdk';
try {
await users.insertOne({ name: 'Invalid User' });
} catch (error) {
if (error instanceof ValidationError) {
console.log('Validation failed:', error.message);
} else if (error instanceof NetworkError) {
console.log('Network issue, will retry automatically');
}
}
```
## License
MIT License - see [LICENSE](LICENSE) file for details.
## Support
- š **Documentation**: https://edgevector-db.finhub.workers.dev/docs
- š **Issues**: https://github.com/am/NoSQL/issues
- š¬ **Discussions**: https://github.com/am/NoSQL/discussions
- š§ **Email**: support@edgevector.com
---
Built with ā¤ļø by the EdgeVector team. Powered by Cloudflare Workers.