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.
- 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.
- Client Libraries (Recommended)
- Direct API
- 🦀 Rust
- 🐍 Python
- 📘 TypeScript
- 📦 JavaScript
- 🟣 Kotlin
- 🔷 Go
let value = client.kv_get("session:user123").await?;
println!("{:?}", value);
value = await client.kv_get('session:user123')
print(value)
# {'user_id': 'user_456', 'login_time': '2026-01-15T10:30:00Z'}
const value = await client.kvGet('session:user123');
console.log(value);
// { user_id: 'user_456', login_time: '2026-01-15T10:30:00Z' }
const value = await client.kvGet('session:user123');
console.log(value);
// { user_id: 'user_456', login_time: '2026-01-15T10:30:00Z' }
val value = client.kvGet("session:user123")
println(value)
value, err := client.KVGet("session:user123")
fmt.Println(value)
curl https://{EKODB_API_URL}/api/kv/get/session:user123 \
-H "Authorization: Bearer {TOKEN}"
# Response
{
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z"
}
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.
- Client Libraries (Recommended)
- Direct API
- 🦀 Rust
- 🐍 Python
- 📘 TypeScript
- 📦 JavaScript
- 🟣 Kotlin
- 🔷 Go
let value = serde_json::json!({
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z"
});
client.kv_set("session:user123", value).await?;
value = {
'user_id': 'user_456',
'login_time': '2026-01-15T10:30:00Z'
}
await client.kv_set('session:user123', value)
const value = {
user_id: 'user_456',
login_time: '2026-01-15T10:30:00Z'
};
await client.kvSet('session:user123', value);
const value = {
user_id: 'user_456',
login_time: '2026-01-15T10:30:00Z'
};
await client.kvSet('session:user123', value);
val value = mapOf(
"user_id" to "user_456",
"login_time" to "2026-01-15T10:30:00Z"
)
client.kvSet("session:user123", value)
value := map[string]interface{}{
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z",
}
err := client.KVSet("session:user123", value)
curl -X POST https://{EKODB_API_URL}/api/kv/set/session:user123 \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z"
}'
# Response
{
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z"
}
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.
- Client Libraries (Recommended)
- Direct API
- 🦀 Rust
- 🐍 Python
- 📘 TypeScript
- 📦 JavaScript
- 🟣 Kotlin
- 🔷 Go
// 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?;
# Set with 1 hour TTL (pass TTL as optional parameter)
value = {
'user_id': 'user_456',
'login_time': '2026-01-15T10:30:00Z'
}
await client.kv_set('session:user123', value, ttl='1h')
// Set with 1 hour TTL (TTL in seconds)
const value = {
user_id: 'user_456',
login_time: '2026-01-15T10:30:00Z'
};
await client.kvSet('session:user123', value, 3600); // 3600 seconds = 1 hour
// Set with 1 hour TTL (TTL in seconds)
const value = {
user_id: 'user_456',
login_time: '2026-01-15T10:30:00Z'
};
await client.kvSet('session:user123', value, 3600); // 3600 seconds = 1 hour
// Set with 1 hour TTL (Kotlin has a dedicated method)
val value = buildJsonObject {
put("user_id", "user_456")
put("login_time", "2026-01-15T10:30:00Z")
}
client.kvSetWithTtl("session:user123", value, "1h")
// Set with TTL using batch operation
// Note: Go single KVSet doesn't support TTL directly
// Use KVBatchSet for TTL support
value := map[string]interface{}{
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z",
}
entries := []map[string]interface{}{
{"key": "session:user123", "value": value, "ttl": int64(3600)}, // 1 hour
}
_, err := client.KVBatchSet(entries)
curl -X POST https://{EKODB_API_URL}/api/kv/set/session:user123 \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"value": {
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z"
},
"ttl": "1h"
}'
# Response
{
"user_id": "user_456",
"login_time": "2026-01-15T10:30:00Z"
}
TTL Format
TTL supports human-readable duration formats:
| Format | Description | Example |
|---|---|---|
30s | Seconds | 30 seconds |
5m | Minutes | 5 minutes |
1h | Hours | 1 hour |
2d | Days | 2 days |
1w | Weeks | 1 week |
- 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 Libraries (Recommended)
- Direct API
- 🦀 Rust
- 🐍 Python
- 📘 TypeScript
- 📦 JavaScript
- 🟣 Kotlin
- 🔷 Go
client.kv_delete("session:user123").await?;
await client.kv_delete('session:user123')
await client.kvDelete('session:user123');
await client.kvDelete('session:user123');
client.kvDelete("session:user123")
err := client.KVDelete("session:user123")
curl -X DELETE https://{EKODB_API_URL}/api/kv/delete/session:user123 \
-H "Authorization: Bearer {TOKEN}"
# Response
{
"message": "deleted"
}
Batch Get
Retrieve multiple values in a single request.
- Client Libraries (Recommended)
- Direct API
- 🦀 Rust
- 🐍 Python
- 📘 TypeScript
- 📦 JavaScript
- 🟣 Kotlin
- 🔷 Go
let keys = vec!["session_1", "session_2", "session_3"];
let values = client.kv_batch_get(&keys).await?;
println!("{:?}", values);
keys = ['session_1', 'session_2', 'session_3']
values = await client.kv_batch_get(keys)
print(values)
# [{"user_id": "user_1"}, {"user_id": "user_2"}, {}]
const keys = ['session_1', 'session_2', 'session_3'];
const values = await client.kvBatchGet(keys);
console.log(values);
// [{"user_id": "user_1"}, {"user_id": "user_2"}, {}]
const keys = ['session_1', 'session_2', 'session_3'];
const values = await client.kvBatchGet(keys);
console.log(values);
// [{"user_id": "user_1"}, {"user_id": "user_2"}, {}]
val keys = listOf("session_1", "session_2", "session_3")
val values = client.kvBatchGet(keys)
println(values)
// [{"user_id": "user_1"}, {"user_id": "user_2"}, {}]
keys := []string{"session_1", "session_2", "session_3"}
values, err := client.KVBatchGet(keys)
fmt.Println(values)
// [{"user_id": "user_1"}, {"user_id": "user_2"}, {}]
curl -X POST https://{EKODB_API_URL}/api/kv/batch/get \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"keys": ["session_1", "session_2", "session_3"]
}'
# Response
[
{"user_id": "user_1"},
{"user_id": "user_2"},
{}
]
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.
- Client Libraries (Recommended)
- Direct API
- 🦀 Rust
- 🐍 Python
- 📘 TypeScript
- 📦 JavaScript
- 🟣 Kotlin
- 🔷 Go
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?;
operations = [
{'key': 'counter_views', 'value': 1000},
{'key': 'counter_clicks', 'value': 250},
{'key': 'feature_flags', 'value': {'new_ui': True, 'beta_features': False}}
]
await client.kv_batch_set(operations)
const operations = [
{ key: 'counter_views', value: 1000 },
{ key: 'counter_clicks', value: 250 },
{ key: 'feature_flags', value: { new_ui: true, beta_features: false } }
];
await client.kvBatchSet(operations);
const operations = [
{ key: 'counter_views', value: 1000 },
{ key: 'counter_clicks', value: 250 },
{ key: 'feature_flags', value: { new_ui: true, beta_features: false } }
];
await client.kvBatchSet(operations);
val operations = listOf(
mapOf("key" to "counter_views", "value" to 1000),
mapOf("key" to "counter_clicks", "value" to 250),
mapOf("key" to "feature_flags", "value" to mapOf("new_ui" to true, "beta_features" to false))
)
client.kvBatchSet(operations)
operations := []map[string]interface{}{
{"key": "counter_views", "value": 1000},
{"key": "counter_clicks", "value": 250},
{"key": "feature_flags", "value": map[string]interface{}{"new_ui": true, "beta_features": false}},
}
err := client.KVBatchSet(operations)
curl -X POST https://{EKODB_API_URL}/api/kv/batch/set \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"operations": [
{
"key": "counter_views",
"value": 1000
},
{
"key": "counter_clicks",
"value": 250
},
{
"key": "feature_flags",
"value": {
"new_ui": true,
"beta_features": false
}
}
]
}'
# Response
[
["counter_views", true],
["counter_clicks", true],
["feature_flags", true]
]
Returns an array of [key, success] tuples indicating which keys were successfully set.
Batch Delete
Delete multiple keys in a single operation.
- Client Libraries (Recommended)
- Direct API
- 🦀 Rust
- 🐍 Python
- 📘 TypeScript
- 📦 JavaScript
- 🟣 Kotlin
- 🔷 Go
let keys = vec!["session:user123", "session:user456", "session:user789"];
let result = client.kv_batch_delete(&keys).await?;
println!("Deleted: {}", result.deleted_count);
result = await client.kv_batch_delete([
'session:user123',
'session:user456',
'session:user789'
])
print(result['deleted_count']) # 3
const result = await client.kvBatchDelete([
'session:user123',
'session:user456',
'session:user789'
]);
console.log(result.deleted_count); // 3
const result = await client.kvBatchDelete([
'session:user123',
'session:user456',
'session:user789'
]);
console.log(result.deleted_count); // 3
val result = client.kvBatchDelete(listOf(
"session:user123",
"session:user456",
"session:user789"
))
println("Deleted: ${result.deletedCount}")
result, err := client.KVBatchDelete([]string{
"session:user123",
"session:user456",
"session:user789",
})
fmt.Printf("Deleted: %v\n", result)
curl -X DELETE https://{EKODB_API_URL}/api/kv/batch/delete \
-H "Authorization: Bearer {ADMIN_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"keys": [
"session:user123",
"session:user456",
"session:user789"
]
}'
# Response
{
"deleted_count": 3
}
Returns an array of [key, success] tuples indicating which keys were successfully deleted.
Clear All
Delete all key-value pairs.
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"
}
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", ...}
]
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.
Create Link
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
Returns null on success. Check HTTP status code (200) to confirm the link was created.
Get Links
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"
}
}
]
Returns an array of link objects directly, not wrapped in an object.
Remove Link
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
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 Case | Recommendation | Why |
|---|---|---|
| Simple key-value lookup | KV Store | Faster, simpler |
| Complex queries/filtering | Documents | Full query capabilities |
| Temporary data/cache | KV Store | Fast writes, auto-cleanup |
| Structured records | Documents | Schema validation, relationships |
| Session management | KV Store | Quick lookups, TTL support |
| User profiles | Documents | Complex 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
Link KV to Documents
# 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
Related Documentation
- Basic Operations - Document CRUD operations
- Batch Operations - Bulk document operations
- Authentication - API key and JWT authentication
Example Code
Direct HTTP/REST API Examples
Raw HTTP examples demonstrating the REST API directly:
- JavaScript:
kv_operations.js - Python:
kv_operations.py - Go:
kv_operations.go - Rust:
kv_operations.rs
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