Skip to main content

Advanced Operations

This guide covers advanced features available in ekoDB client libraries, including search operations, chat functionality, and real-time data handling.

tip

For complete, runnable examples, visit the ekoDB Examples Repository. It contains 105 working examples across all languages.

Search Operations

ekoDB provides powerful search capabilities including full-text search, fuzzy search, and vector search.

Search across all fields in your documents:

use ekodb_client::{Client, SearchQuery};

let search = SearchQuery::builder()
.query("database")
.min_score(0.1)
.limit(10)
.build();

let results = client.search("articles", search).await?;

for result in results.results {
println!("Score: {:.4} - {:?}", result.score, result.record);
}

Search with custom field weights to prioritize certain fields:

use std::collections::HashMap;

let mut weights = HashMap::new();
weights.insert("title".to_string(), 2.0);
weights.insert("description".to_string(), 1.0);

let search = SearchQuery::builder()
.query("rust database")
.fields(vec!["title".to_string(), "description".to_string()])
.weights(weights)
.limit(5)
.build();

let results = client.search("articles", search).await?;

Enable typo tolerance with fuzzy matching:

let search = SearchQuery::builder()
.query("databse") // Typo: "databse" instead of "database"
.fuzzy(true)
.fuzziness(2) // Allow up to 2 character differences
.limit(10)
.build();

let results = client.search("articles", search).await?;

Perform semantic similarity search using embeddings:

// First, create a collection with vector index
let schema = Schema::builder()
.add_field("content", FieldType::String)
.add_field("embedding", FieldType::Vector(384)) // 384-dimensional vector
.build();

client.create_collection("documents", schema).await?;

// Insert document with embedding
let mut doc = Record::new();
doc.insert("content", "ekoDB is a high-performance database");
doc.insert("embedding", vec![0.1, 0.2, 0.3, /* ... 384 dimensions */]);
client.insert("documents", doc).await?;

// Search by vector similarity
let query_vector = vec![0.1, 0.2, 0.3, /* ... */];
let search = SearchQuery::builder()
.vector(query_vector)
.limit(10)
.build();

let results = client.search("documents", search).await?;

Combine text and vector search for best results:

let search = SearchQuery::builder()
.query("database performance") // Text query
.vector(query_vector) // Vector query
.limit(10)
.build();

let results = client.search("documents", search).await?;

Chat Operations

Build AI-powered chat applications with built-in context management and session handling.

Basic Chat

use ekodb_client::chat::{ChatClient, ChatMessage};

// Create chat client
let chat = ChatClient::new(client, "products");

// Send a message
let response = chat.send_message(
"What products do you have?",
"gpt-4"
).await?;

println!("AI: {}", response.content);

Chat Sessions

Manage conversation history with sessions:

// Create a new session
let session = chat.create_session("Customer Support Chat").await?;

// Send messages in the session
let response1 = chat.send_message_in_session(
&session.id,
"What's the price of ekoDB Pro?",
"gpt-4"
).await?;

let response2 = chat.send_message_in_session(
&session.id,
"What features does it include?",
"gpt-4"
).await?;

// Get session history
let messages = chat.get_session_messages(&session.id).await?;
println!("Total messages: {}", messages.len());

Real-Time Operations

WebSocket Queries

Subscribe to real-time data changes:

use ekodb_client::WebSocketClient;

// Connect to WebSocket
let ws_url = "wss://your-subdomain.production.google.ekodb.net/ws";
let mut ws_client = client.websocket(ws_url).await?;

// Subscribe to collection changes
let results = ws_client.find_all("users").await?;

// Process real-time updates
for record in results {
println!("New/Updated record: {:?}", record);
}

ws_client.close().await?;

TTL (Time-To-Live)

Set automatic expiration for documents:

// Insert with 1 hour TTL
let mut session = Record::new();
session.insert("user_id", "user-123");
session.insert("token", "abc123");

let result = client.insert_with_ttl(
"sessions",
session,
"1h" // Expires in 1 hour
).await?;

Functions

Server-Side Feature

Functions are ekoDB's stored procedures system that runs on the server. They can be called from any client library or via REST API to execute complex business logic, queries, CRUD operations, AI workflows, and batch processing.

Functions let you create, store, and execute complete business logic as composable operations. Define your data logic once in ekoDB, then call it like puzzle pieces from any client.

What You Can Do

  • Complete business logic - Queries, CRUD, AI operations in one place
  • Parameterize everything - Dynamic values via {{param_name}}
  • Version control - Track function versions
  • Compose like puzzles - Chain operations together
  • Call from anywhere - REST API or any client library

Function Capabilities

  • Query Operations: Find, filter, search, vector search, hybrid search
  • CRUD Operations: Insert, update, delete (single and batch)
  • Transformations: Group, project, count
  • AI Operations: Chat completions, embeddings generation
  • Conditional Logic: If/then/else, foreach loops
  • External Integrations: HTTP requests to any REST API

Basic Example

Create a function to query active users:

POST /api/functions
Content-Type: application/json

{
"label": "get_active_users",
"name": "Get Active Users",
"description": "Returns active users with a limit",
"version": "1.0",
"parameters": {
"limit": {
"default": 10,
"required": false
}
},
"functions": [
{
"type": "Query",
"collection": "users",
"filter": {
"type": "Condition",
"field": "status",
"operator": "Eq",
"value": "active"
},
"limit": "{{limit}}"
}
]
}

Call a Function

Execute via REST API:

POST /api/functions/get_active_users
Content-Type: application/json

{
"limit": 20
}

Managing Functions

# List all functions
GET /api/functions

# Get a specific function
GET /api/functions/get_active_users

# Update a function
PUT /api/functions/{id}

# Delete a function
DELETE /api/functions/get_active_users

Parameters

Make functions dynamic with parameters:

{
"parameters": {
"status": {
"default": "active",
"required": false,
"description": "Filter by status"
},
"min_amount": {
"required": true,
"description": "Minimum amount"
}
}
}

Reference parameters in your function definitions using {{param_name}}:

{
"type": "Query",
"collection": "orders",
"filter": {
"type": "Condition",
"field": "status",
"operator": "Eq",
"value": "{{status}}"
}
}

Available Operations

Functions support these operation types:

Query Operations

  • FindAll - Retrieve all records
  • Query - Advanced filtering, sorting, pagination
  • VectorSearch - Semantic similarity search
  • HybridSearch - Combine text + vector search
  • TextSearch - Full-text search
  • FindById - Get specific record by ID
  • FindOne - Find one by key/value

CRUD Operations

  • Insert - Insert single record
  • BatchInsert - Insert multiple records
  • Update - Update with filter
  • UpdateById - Update specific record
  • Delete - Delete with filter
  • DeleteById - Delete specific record
  • BatchDelete - Delete multiple records

Transformations

  • Group - Group and aggregate
  • Project - Select/exclude fields
  • Count - Count records

AI Operations

  • Chat - AI chat completions
  • Embed - Generate embeddings

Logic & Control

  • If - Conditional execution
  • ForEach - Loop over records
  • CallFunction - Call another function

External Integrations

  • HttpRequest - Call external APIs (Stripe, SendGrid, etc.)

Combine embeddings with search:

{
"label": "smart_search",
"name": "Smart Product Search",
"parameters": {
"query": { "required": true }
},
"functions": [
{
"type": "Embed",
"input_field": "query",
"output_field": "query_embedding"
},
{
"type": "HybridSearch",
"collection": "products",
"query_text": "{{query}}",
"query_vector": "{{query_embedding}}",
"limit": 10
}
]
}

Example: Batch Processing

Process multiple records with AI:

{
"label": "enrich_articles",
"name": "AI Content Enrichment",
"functions": [
{
"type": "Query",
"collection": "articles",
"filter": {
"type": "Condition",
"field": "embedding",
"operator": "Eq",
"value": null
},
"limit": 100
},
{
"type": "ForEach",
"functions": [
{
"type": "Embed",
"input_field": "content",
"output_field": "embedding"
},
{
"type": "UpdateById",
"collection": "articles",
"record_id": "{{id}}",
"updates": {
"embedding": "{{embedding}}"
}
}
]
}
]
}

Best Practices

  • Keep it simple - Start with single operations, build up
  • Use parameters - Make functions reusable with dynamic values
  • Filter early - Reduce data before expensive operations
  • Add descriptions - Document what each function does
  • Tag for organization - Use tags like analytics, users, ai
  • Version your functions - Track changes with version field
  • Test thoroughly - Validate with edge cases

Storage

Functions are stored in a dedicated collection: functions_{db_name} (configurable)

Complete Documentation

For complete details including:

  • All operation types and parameters
  • Advanced parameter resolution
  • Conditional logic patterns
  • External API integration examples
  • Error handling

See the Functions GitHub Examples with working code in all 6 languages.


Next Steps

Need Help?