ekoDB Rust Client Library
Official Rust client library for ekoDB - A high-performance database with intelligent caching, real-time capabilities, AI integration, and automatic optimization.
Features
- ✅ Async/Await: Built on Tokio for high-performance async operations
- ✅ Type-Safe: Strong typing with Rust's type system and comprehensive error handling
- ✅ Auto-Retry: Automatic retry with exponential backoff for transient failures (429, 503, timeouts)
- ✅ Connection Pooling: Efficient HTTP connection management
- ✅ Query Builder: Fluent API for building complex queries with operators, sorting, and pagination
- ✅ Search: Full-text search, vector search, and hybrid search with scoring
- ✅ AI Chat: Natural language queries with context-aware AI responses (OpenAI, Anthropic, Perplexity)
- ✅ Schema Management: Define and enforce data schemas with validation
- ✅ WebSocket Support: Real-time queries and subscriptions with automatic reconnection
- ✅ Batch Operations: Efficient bulk inserts, updates, and deletes
- ✅ TTL Support: Automatic document expiration with time-to-live
- ✅ Key-Value Operations: Simple key-value store operations
- ✅ Collection Management: Create, list, count, and delete collections
- ✅ Token Caching: Automatic authentication token management and refresh
Installation
Add this to your Cargo.toml
:
[]
= "0.1"
= { = "1", = ["full"] }
Quick Start
use ;
async
Configuration
Environment Variables
You can configure the client using environment variables:
# Run example
use env;
let client = builder
.base_url
.api_key
.timeout
.max_retries
.build?;
Examples
CRUD Operations
use ;
// Insert
let mut user = new;
user.insert;
user.insert;
let inserted = client.insert.await?;
// Extract ID from response
let user_id = if let Some = inserted.get else ;
// Find by ID
let user = client.find_by_id.await?;
// Update
let mut updates = new;
updates.insert;
let updated = client.update.await?;
// Delete
client.delete.await?;
Query Builder
use QueryBuilder;
use json;
// Simple queries
let query = new
.eq
.gte
.lt
.build;
let results = client.find.await?;
// Complex queries with sorting and pagination
let query = new
.in_array
.regex
.sort_desc
.limit
.skip
.build;
let results = client.find.await?;
Batch Operations
use BatchBuilder;
// Create records for batch insert
let mut user1 = new;
user1.insert;
user1.insert;
let mut user2 = new;
user2.insert;
user2.insert;
// Build and execute batch
let batch = new
.insert
.insert
.build;
let results = client.batch_insert.await?;
println!;
WebSocket Operations
// Connect to WebSocket
let ws_client = client.websocket.await?;
// Query via WebSocket
let results = ws_client.find_all.await?;
println!;
// Query with filters
let query = new.filter;
let active_users = ws_client.find.await?;
TTL (Time-To-Live) Support
// Insert with 1 hour TTL
let record = new
.with
.with;
client.insert_with_ttl.await?;
// Insert with 5 minutes TTL
client.insert_with_ttl.await?;
// Supported TTL formats: "30s", "5m", "1h", "2d"
Key-Value Operations
// Set a key-value pair
client.kv_set.await?;
// Get a value
let session = client.kv_get.await?;
// Delete a key
client.kv_delete.await?;
// Set with TTL
client.kv_set_with_ttl.await?;
Search Operations
use SearchQuery;
// Basic text search
let search = new
.min_score
.limit;
let results = client.search.await?;
for result in results.results
// Search with field weights
let search = new
.fields
.weights
.limit;
let results = client.search.await?;
AI Chat Integration
use ;
// Create a chat session
let session_request = CreateChatSessionRequest ;
let session = client.create_chat_session.await?;
// Send a message
let message = new;
let response = client.chat_message.await?;
println!;
println!;
Schema Management
use ;
// Create a collection with schema
let schema = new
.add_field
.add_field
.add_field
.add_field;
client.create_collection.await?;
// Get schema
let schema = client.get_schema.await?;
for in &schema.fields
Collection Management
// List all collections
let collections = client.list_collections.await?;
println!;
// Count documents in a collection
let count = client.count.await?;
println!;
// Check if collection exists
let exists = client.collection_exists.await?;
// Delete a collection
client.delete_collection.await?;
Error Handling
use Error;
match client.insert.await
Supported Data Types
ekoDB supports the following data types:
Primitive Types
String
- Text dataInteger
- 64-bit signed integersFloat
- 64-bit floating point numbersNumber
- Flexible numeric type (Integer, Float, or Decimal)Boolean
- True/false valuesDecimal
- High-precision decimal numbers for financial calculationsNull
- Explicit null values
Date/Time Types
DateTime
- ISO-8601 formatted timestampsDuration
- Time durations (e.g., "30s", "5m", "1h")
Identifier Types
UUID
- Universally unique identifiers (auto-validated)
Collection Types
Object
- Nested structures (HashMap)Array
- Ordered collectionsSet
- Unordered collections (automatically deduplicated by server)Vector
- Vector embeddings for similarity search
Binary Types
Binary
- Binary data (base64 encoded)Bytes
- Raw byte arrays
Running Examples
The library includes 13 comprehensive examples demonstrating all features:
# Set environment variables
# Run individual examples
Available Examples
Basic Operations
- client_simple_crud - Basic CRUD operations (Create, Read, Update, Delete)
- client_batch_operations - Bulk insert, update, and delete operations
- client_kv_operations - Key-value store operations with TTL
- client_collection_management - Collection listing, counting, and deletion
- client_document_ttl - Documents with automatic expiration
Real-time & WebSocket
- client_simple_websocket - Real-time queries via WebSocket
- client_websocket_ttl - WebSocket queries with TTL documents
Advanced Queries & Search
- client_query_builder - Complex queries with operators, sorting, and pagination
- client_search - Full-text search, vector search, and hybrid search
Schema & Data Modeling
- client_schema_management - Define and enforce data schemas
AI Chat Integration
- client_chat_basic - Simple AI chat with context search
- client_chat_sessions - Multi-turn conversations with session management
- client_chat_advanced - Advanced chat features with streaming and context control
All examples are located in examples/rust/examples/
directory.
API Reference
Client Methods
Document Operations
insert(collection, record)
- Insert a documentinsert_with_ttl(collection, record, ttl)
- Insert with expirationfind_by_id(collection, id)
- Find document by IDfind(collection, query)
- Query documents with filtersfind_all(collection)
- Get all documents in collectionupdate(collection, id, updates)
- Update a documentdelete(collection, id)
- Delete a document
Batch Operations
batch_insert(collection, records)
- Bulk insert documentsbatch_update(collection, updates)
- Bulk update documentsbatch_delete(collection, ids)
- Bulk delete documents
Query Building
QueryBuilder::new()
- Create a new query builder.eq(field, value)
- Equal to.ne(field, value)
- Not equal to.gt(field, value)
- Greater than.gte(field, value)
- Greater than or equal.lt(field, value)
- Less than.lte(field, value)
- Less than or equal.in_array(field, values)
- In array.nin(field, values)
- Not in array.regex(field, pattern)
- Regex match.sort_asc(field)
/.sort_desc(field)
- Sorting.limit(n)
/.skip(n)
- Pagination.build()
- Build the query
Search Operations
search(collection, search_query)
- Full-text searchSearchQuery::new(query)
- Create search query.fields(fields)
- Specify fields to search.weights(weights)
- Field weights for scoring.min_score(score)
- Minimum relevance score.limit(n)
- Maximum results
AI Chat Operations
create_chat_session(request)
- Create a new chat sessionchat_message(chat_id, message)
- Send a chat messageget_chat_messages(chat_id, query)
- Get message historylist_chat_sessions(query)
- List all chat sessionsupdate_chat_session(chat_id, request)
- Update session configurationdelete_chat_session(chat_id)
- Delete a chat session
Schema Management
create_collection(collection, schema)
- Create collection with schemaget_schema(collection)
- Get collection schemaupdate_schema(collection, schema)
- Update collection schemaSchema::new()
- Create a new schema.add_field(name, field_type)
- Add field to schemaFieldTypeSchema::new(type)
- Create field type.required()
- Mark field as required
Key-Value Operations
kv_set(key, value)
- Set a key-value pairkv_set_with_ttl(key, value, ttl)
- Set with expirationkv_get(key)
- Get value by keykv_delete(key)
- Delete a key
Collection Operations
list_collections()
- List all collectionscount(collection)
- Count documents in collectioncollection_exists(collection)
- Check if collection existsdelete_collection(collection)
- Delete entire collection
WebSocket Operations
websocket(url)
- Connect to WebSocket endpointws_client.find(collection, query)
- Query via WebSocketws_client.find_all(collection)
- Get all via WebSocket
Best Practices
Connection Management
// Create one client instance and reuse it
let client = builder
.base_url
.api_key
.timeout
.max_retries
.build?;
// The client is thread-safe and can be cloned cheaply
let client_clone = client.clone;
Error Handling
use Error;
match client.insert.await
Performance Tips
- Use Batch Operations - For multiple inserts/updates/deletes, use batch operations instead of individual calls
- Reuse Client - Create one client instance and reuse it across your application
- Set Appropriate Timeouts - Configure timeouts based on your use case
- Use Pagination - For large result sets, use
.limit()
and.skip()
to paginate - Index Fields - Use schema management to define indexes on frequently queried fields
- Cache Tokens - The client automatically caches authentication tokens
Collection Cleanup
All client examples follow a cleanup convention to prevent test pollution:
// At the end of your example/test
println!;
client.delete_collection.await?;
println!;
Troubleshooting
Authentication Errors
If you see authentication errors:
- Verify your API key is correct
- Check that the ekoDB server is running
- Ensure the API key is registered with the server
Connection Timeouts
If requests are timing out:
- Increase the timeout:
.timeout(Duration::from_secs(60))
- Check network connectivity
- Verify the server URL is correct
Rate Limiting
The client automatically retries on rate limits (429), but you can also handle them manually:
if let Err = result
License
This project is licensed under either of:
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
at your option.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.