Skip to main content

Key-Value Store

ekoDB includes a built-in key-value (KV) store optimized for fast lookups, caching, and metadata storage. Use KV operations for simple key-value pairs when you don't need the full document structure.

When to Use KV Store
  • Caching - Store frequently accessed data
  • Session Management - User sessions and temporary data
  • Configuration - Application settings and flags
  • Counters - Track metrics and statistics
  • Metadata - Additional data linked to documents

First, generate an access token using your API key:

curl -X POST https://{EKODB_API_URL}/api/auth/token \
-H "Content-Type: application/json" \
-d '{"api_key": "YOUR_API_KEY"}'

Response:

{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Get Value

Retrieve a value by key.

let value = client.kv_get("session:user123").await?;

println!("{:?}", value);
Response Format

The get operation returns the value directly without wrapping it in an object. The key is part of the URL path.

Set Value

Store or update a key-value pair.

let value = serde_json::json!({
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z"
});

client.kv_set("session:user123", value).await?;
Response Format

The set operation returns the stored value directly, confirming what was saved.

Value Types:

KV store accepts any JSON value:

// String
"simple value"

// Number
42

// Boolean
true

// Object
{"nested": "data", "count": 10}

// Array
["item1", "item2", "item3"]

Set Value with TTL

Store a key-value pair that automatically expires after a specified duration. This is ideal for caching, session management, and temporary data.

// Set with 1 hour TTL (pass TTL as optional 3rd parameter)
let value = serde_json::json!({
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z"
});

client.kv_set("session:user123", value, Some("1h")).await?;

TTL Format

TTL supports human-readable duration formats:

FormatDescriptionExample
30sSeconds30 seconds
5mMinutes5 minutes
1hHours1 hour
2dDays2 days
1wWeeks1 week
TTL Behavior
  • Keys are automatically deleted when TTL expires
  • Updating a key resets or clears the TTL depending on whether you include the TTL parameter
  • Expired keys return null/{} on get operations (no error)
  • TTL is optional; keys without TTL persist indefinitely

Delete Value

Delete a key-value pair.

client.kv_delete("session:user123").await?;

Batch Get

Retrieve multiple values in a single request.

let keys = vec!["session_1", "session_2", "session_3"];
let values = client.kv_batch_get(&keys).await?;

println!("{:?}", values);
Response Format

Returns an array of values in the same order as the requested keys. Missing keys return an empty object {}.

Batch Set

Set multiple key-value pairs in a single operation.

let operations = vec![
("counter_views", serde_json::json!(1000)),
("counter_clicks", serde_json::json!(250)),
("feature_flags", serde_json::json!({
"new_ui": true,
"beta_features": false,
})),
];

client.kv_batch_set(operations).await?;
Response Format

Returns an array of [key, success] tuples indicating which keys were successfully set.

Batch Delete

Delete multiple keys in a single operation.

let keys = vec!["session:user123", "session:user456", "session:user789"];
let result = client.kv_batch_delete(&keys).await?;

println!("Deleted: {}", result.deleted_count);
Response Format

Returns an array of [key, success] tuples indicating which keys were successfully deleted.

Clear All

Delete all key-value pairs.

Destructive Operation

This operation permanently deletes all KV data and cannot be undone.

curl -X DELETE https://{EKODB_API_URL}/api/kv/clear \
-H "Authorization: Bearer {ADMIN_TOKEN}"

# Response
{
"message": "success"
}
Direct API Only

The KV clear operation is available via the REST API only. Client libraries do not include a dedicated clear method. Use the API directly for this operation.

Find Keys

Query keys with filters and patterns.

POST https://{EKODB_API_URL}/api/kv/find
Content-Type: application/json
Authorization: Bearer {YOUR_API_TOKEN}

{
"prefix": "user_session_",
"limit": 10,
"offset": 0
}

# Response
[
{"key": "user_session_123", ...},
{"key": "user_session_456", ...},
{"key": "user_session_789", ...}
]
Response Format

Returns an array of key-value records directly, not wrapped in an object. Each record contains the key and its associated value.

Filter Options:

{
"prefix": "cache_", // Keys starting with prefix
"suffix": "_temp", // Keys ending with suffix
"contains": "session", // Keys containing string
"limit": 100, // Max results
"offset": 0 // Pagination offset
}

Linking KV to Documents

Link key-value pairs to document records for additional metadata.

Link a KV pair to a document.

POST https://{EKODB_API_URL}/api/kv/{key}/links/{collection}/{record_id}
Content-Type: application/json
Authorization: Bearer {YOUR_API_TOKEN}

{
"metadata": {
"created_by": "user_123",
"purpose": "analytics",
"expires": "2026-12-31"
}
}

# Response
null
Response Format

Returns null on success. Check HTTP status code (200) to confirm the link was created.

Retrieve all document links for a key.

GET https://{EKODB_API_URL}/api/kv/{key}/links
Authorization: Bearer {YOUR_API_TOKEN}

# Response
[
{
"collection": "reports",
"record_id": "report_456",
"metadata": {
"created_by": "user_123",
"purpose": "analytics"
}
},
{
"collection": "dashboards",
"record_id": "dashboard_789",
"metadata": {
"created_by": "user_456"
}
}
]
Response Format

Returns an array of link objects directly, not wrapped in an object.

Remove a link between a KV pair and a document.

DELETE https://{EKODB_API_URL}/api/kv/{key}/links/{collection}/{record_id}
Authorization: Bearer {YOUR_API_TOKEN}

# Response
null
Response Format

Returns null on success. Check HTTP status code (200) to confirm the link was removed.

Complete Example

Here's a complete workflow using KV store for session management:

#!/bin/bash

# 1. Create session on login
session_id=$(uuidgen)
curl -X POST https://{EKODB_API_URL}/api/kv/set/session_$session_id \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {YOUR_API_TOKEN}" \
-d '{
"user_id": "user_123",
"login_time": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
"ip_address": "192.168.1.1"
}'

# 2. Link session to user document
curl -X POST https://{EKODB_API_URL}/api/kv/session_$session_id/links/users/user_123 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {YOUR_API_TOKEN}" \
-d '{
"metadata": {
"session_type": "web",
"device": "desktop"
}
}'

# 3. Get session data
curl -X GET https://{EKODB_API_URL}/api/kv/get/session_$session_id \
-H "Authorization: Bearer {YOUR_API_TOKEN}"

# 4. Get all sessions for user (using find)
curl -X POST https://{EKODB_API_URL}/api/kv/find \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {YOUR_API_TOKEN}" \
-d '{
"prefix": "session_",
"limit": 100
}'

# 5. Cleanup session on logout
curl -X DELETE https://{EKODB_API_URL}/api/kv/delete/session_$session_id \
-H "Authorization: Bearer {YOUR_API_TOKEN}"

Best Practices

Choose KV vs Documents

Use CaseRecommendationWhy
Simple key-value lookupKV StoreFaster, simpler
Complex queries/filteringDocumentsFull query capabilities
Temporary data/cacheKV StoreFast writes, auto-cleanup
Structured recordsDocumentsSchema validation, relationships
Session managementKV StoreQuick lookups, TTL support
User profilesDocumentsComplex queries, joins

Use Prefixes for Organization

# Group related keys with prefixes
POST /api/kv/set/cache:users:123
POST /api/kv/set/cache:posts:456
POST /api/kv/set/session:abc123
POST /api/kv/set/session:def456
POST /api/kv/set/config:feature_flags

Batch Operations for Efficiency

# Good: Batch get for multiple keys
POST /api/kv/batch/get
{"keys": ["session_1", "session_2", "session_3"]}

# Avoid: Multiple individual requests
GET /api/kv/get/session_1
GET /api/kv/get/session_2
GET /api/kv/get/session_3
# Store analytics in KV, link to report document
POST /api/kv/set/analytics_2024_01
{"views": 1000, "clicks": 250}

POST /api/kv/analytics_2024_01/links/reports/report_123
{"metadata": {"period": "monthly"}}

# Query report to get linked analytics
GET /api/find/reports/report_123
# Then fetch linked KV data
GET /api/kv/analytics_2024_01/links

Use Cases

Caching API Responses

# Cache expensive query results
POST /api/kv/set/cache:trending_posts
{
"posts": [...],
"generated_at": "2026-01-15T10:30:00Z",
"ttl": 300
}

# Retrieve cached data
GET /api/kv/get/cache:trending_posts

Feature Flags

# Store feature flags
POST /api/kv/set/feature_flags
{
"new_dashboard": true,
"beta_search": false,
"experimental_ai": true
}

# Quick lookup
GET /api/kv/get/feature_flags

Rate Limiting Counters

# Increment API call counter
GET /api/kv/get/rate_limit:user_123
# {"count": 95, "reset_at": "2026-01-15T11:00:00Z"}

# Update counter
POST /api/kv/set/rate_limit:user_123
{"count": 96, "reset_at": "2026-01-15T11:00:00Z"}

Session Storage

# Store user session
POST /api/kv/set/session:abc123
{
"user_id": "user_456",
"roles": ["user", "premium"],
}

# Validate session
GET /api/kv/get/session:abc123

Example Code

Direct HTTP/REST API Examples

Raw HTTP examples demonstrating the REST API directly:

Client Library Examples

Production-ready examples using official client libraries:

  • Rust: client_kv_operations.rs
  • Python: client_kv_operations.py
  • TypeScript: client_kv_operations.ts
  • Go: client_kv_operations.go
  • Kotlin: ClientKvOperations.kt
  • JavaScript: client_kv_operations.js