ekodb

package module
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 27, 2026 License: MIT Imports: 12 Imported by: 0

README ΒΆ

ekoDB Go Client πŸ”·

Go Reference Go Report Card

Official Go client library for ekoDB - a high-performance document database.

πŸ“¦ Installation

go get github.com/ekoDB/ekodb-client-go

πŸš€ Quick Start

Basic Usage
package main

import (
    "fmt"
    "log"

    "github.com/ekoDB/ekodb-client-go"
)

func main() {
    // Create client with default configuration
    client, err := ekodb.NewClient("http://localhost:8080", "your-api-key")
    if err != nil {
        log.Fatal(err)
    }

    // Insert a document
    record := ekodb.Record{
        "name":  "John Doe",
        "email": "john@example.com",
        "age":   30,
    }

    inserted, err := client.Insert("users", record)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Inserted: %+v\n", inserted)

    // Check rate limit status
    if rateLimitInfo := client.GetRateLimitInfo(); rateLimitInfo != nil {
        fmt.Printf("Rate limit: %d/%d remaining (%.1f%%)\n",
            rateLimitInfo.Remaining, rateLimitInfo.Limit, rateLimitInfo.RemainingPercentage())
    }

    // Find documents
    query := ekodb.Query{
        Limit: intPtr(10),
    }
    results, err := client.Find("users", query)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Found %d documents\n", len(results))
}

func intPtr(i int) *int {
    return &i
}
Advanced Configuration
package main

import (
    "errors"
    "fmt"
    "log"
    "time"

    "github.com/ekoDB/ekodb-client-go"
)

func main() {
    // Create client with custom configuration
    client, err := ekodb.NewClientWithConfig(ekodb.ClientConfig{
        BaseURL:    "http://localhost:8080",
        APIKey:     "your-api-key",
        ShouldRetry: true,              // Enable automatic retries (default: true)
        MaxRetries: 3,                  // Maximum retry attempts (default: 3)
        Timeout:    30 * time.Second,   // Request timeout (default: 30s)
    })
    if err != nil {
        log.Fatal(err)
    }

    // Insert with error handling
    record := ekodb.Record{
        "name":  "John Doe",
        "email": "john@example.com",
    }

    inserted, err := client.Insert("users", record)
    if err != nil {
        // Check if it's a rate limit error
        var rateLimitErr *ekodb.RateLimitError
        if errors.As(err, &rateLimitErr) {
            fmt.Printf("Rate limited! Retry after %d seconds\n", rateLimitErr.RetryAfterSecs)
            // Handle rate limiting manually if needed
            return
        }
        log.Fatal(err)
    }
    fmt.Printf("Inserted: %+v\n", inserted)

    // Check if approaching rate limit
    if client.IsNearRateLimit() {
        fmt.Println("Warning: Approaching rate limit!")
    }
}

✨ Features

  • βœ… CRUD operations
  • βœ… Batch operations
  • βœ… Key-value operations
  • βœ… Collection management
  • βœ… WebSocket support
  • βœ… TTL support
  • βœ… Automatic token management
  • βœ… Query Builder - Fluent API for complex queries with operators, sorting, and pagination
  • βœ… Search - Full-text search, fuzzy search, and field-specific search with scoring
  • βœ… Schema Management - Define and enforce data schemas with validation
  • βœ… Join Operations - Single and multi-collection joins with queries
  • βœ… Rate limiting with automatic retry (429, 503, network errors)
  • βœ… Rate limit tracking (X-RateLimit-* headers)
  • βœ… Configurable retry behavior
  • βœ… Retry-After header support

πŸ“– Usage Examples

Query Builder
// Simple query with operators
query := ekodb.NewQueryBuilder().
    Eq("status", "active").
    Gte("age", 18).
    Lt("age", 65).
    Limit(10).
    Build()

results, err := client.Find("users", query)

// Complex query with sorting and pagination
query := ekodb.NewQueryBuilder().
    In("status", []interface{}{"active", "pending"}).
    Contains("email", "@example.com").
    SortDescending("created_at").
    Skip(20).
    Limit(10).
    Build()

results, err := client.Find("users", query)
Search Operations
// Basic text search
searchQuery := ekodb.SearchQuery{
    Query:    "programming",
    MinScore: 0.1,
    Limit:    10,
}

results, err := client.Search("articles", searchQuery)
for _, result := range results.Results {
    fmt.Printf("Score: %.4f - %v\n", result.Score, result.Record["title"])
}

// Search with field weights
searchQuery := ekodb.SearchQuery{
    Query:   "rust database",
    Fields:  []string{"title", "description"},
    Weights: map[string]float64{"title": 2.0},
    Limit:   5,
}

results, err := client.Search("articles", searchQuery)
Schema Management
// Create a collection with schema
schema := ekodb.NewSchemaBuilder().
    AddField("name", ekodb.NewFieldTypeSchemaBuilder("String").
        Required().
        Pattern("^[a-zA-Z ]+$").
        Build()).
    AddField("email", ekodb.NewFieldTypeSchemaBuilder("String").
        Required().
        Unique().
        Build()).
    AddField("age", ekodb.NewFieldTypeSchemaBuilder("Integer").
        Range(0, 150).
        Build()).
    Build()

err := client.CreateCollection("users", schema)

// Get collection schema
schema, err := client.GetSchema("users")
Join Operations
// Single collection join
join := ekodb.NewSingleJoin("departments", "department_id", "id", "department")

query := ekodb.NewQueryBuilder().
    Join(join.ToMap()).
    Limit(10).
    Build()

results, err := client.Find("users", query)

// Multi-collection join
join := ekodb.NewJoinConfig(
    []string{"departments", "profiles"},
    "department_id",
    "id",
    "related_data",
)

query := ekodb.NewQueryBuilder().
    Join(join.ToMap()).
    Build()

results, err := client.Find("users", query)

πŸ“š API Reference

Client Creation
  • NewClient(baseURL, apiKey string) (*Client, error) - Create client with default configuration
  • NewClientWithConfig(config ClientConfig) (*Client, error) - Create client with custom configuration
Rate Limit Methods
  • GetRateLimitInfo() *RateLimitInfo - Get current rate limit information
  • IsNearRateLimit() bool - Check if approaching rate limit (<10% remaining)
CRUD Methods
  • Insert(collection string, record Record, ttl ...string) (Record, error)
  • Find(collection string, query Query) ([]Record, error)
  • FindByID(collection, id string) (Record, error)
  • Update(collection, id string, record Record) (Record, error)
  • Delete(collection, id string) error
  • BatchInsert(collection string, records []Record) ([]Record, error)
  • BatchUpdate(collection string, updates map[string]Record) ([]Record, error)
  • BatchDelete(collection string, ids []string) (int, error)
Query Builder Methods
  • NewQueryBuilder() *QueryBuilder - 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(field, values) - In array
  • Nin(field, values) - Not in array
  • Contains(field, value) - String contains
  • StartsWith(field, value) - String starts with
  • EndsWith(field, value) - String ends with
  • Regex(field, pattern) - Regex match
  • SortAscending(field) / SortDescending(field) - Sorting
  • Limit(n) / Skip(n) - Pagination
  • Build() - Build the query
Search Methods
  • Search(collection string, query SearchQuery) (*SearchResults, error) - Full-text search
Schema Methods
  • CreateCollection(collection string, schema Schema) error - Create collection with schema
  • GetSchema(collection string) (*Schema, error) - Get collection schema
  • GetCollection(collection string) (*CollectionMetadata, error) - Get collection metadata
Join Methods
  • NewSingleJoin(collection, localField, foreignField, as string) *JoinConfig - Single collection join
  • NewJoinConfig(collections []string, localField, foreignField, as string) *JoinConfig - Multi-collection join
Key-Value Methods
  • KVSet(key string, value interface{}) error
  • KVGet(key string) (interface{}, error)
  • KVDelete(key string) error
Collection Methods
  • ListCollections() ([]string, error)
  • DeleteCollection(collection string) error
WebSocket Methods
  • WebSocket(wsURL string) (*WebSocketClient, error)
  • FindAll(collection string) ([]Record, error)
  • Close() error

πŸ’‘ Examples

For complete, runnable examples, visit the ekoDB Examples Repository.

The repository contains 25 working Go examples (15 client library + 10 direct API):

Basic Operations
Advanced Queries
Schema & Batch
Real-time & TTL
Chat Examples
Running Examples
# Clone the examples repository
git clone https://github.com/ekoDB/ekodb-client.git
cd ekodb-client/examples/go

# Set up environment
cp ../.env.example ../.env
# Edit ../.env with your API URL and key

# Run an example
go run client_simple_crud.go

πŸ“š Documentation

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“„ License

MIT License - see the LICENSE file for details.

πŸ’¬ Support

Documentation ΒΆ

Overview ΒΆ

Package ekodb provides a Go client for ekoDB

Package ekodb provides a Go client for ekoDB ΒΆ

Package ekodb provides a Go client for ekoDB ΒΆ

Package ekodb provides a Go client for ekoDB ΒΆ

Package ekodb provides a Go client for ekoDB ΒΆ

Package ekodb provides a Go client for ekoDB

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func ExtractRecord ΒΆ added in v0.6.1

func ExtractRecord(record map[string]interface{}) map[string]interface{}

ExtractRecord transforms an entire record by extracting all field values. Preserves the 'id' field and extracts values from all other fields.

Example:

user, _ := client.FindByID("users", userID)
plainUser := ExtractRecord(user)
// plainUser is now map[string]interface{} with plain values

func FieldArray ΒΆ added in v0.7.0

func FieldArray(values interface{}) map[string]interface{}

FieldArray creates an Array field value

func FieldBinary ΒΆ added in v0.7.0

func FieldBinary(value []byte) map[string]interface{}

FieldBinary creates a Binary field value from bytes

func FieldBinaryBase64 ΒΆ added in v0.7.0

func FieldBinaryBase64(value string) map[string]interface{}

FieldBinaryBase64 creates a Binary field value from a base64 string

func FieldBoolean ΒΆ added in v0.7.0

func FieldBoolean(value bool) map[string]interface{}

FieldBoolean creates a Boolean field value (explicit wrapping)

func FieldBytes ΒΆ added in v0.7.0

func FieldBytes(value []byte) map[string]interface{}

FieldBytes creates a Bytes field value from bytes

func FieldBytesBase64 ΒΆ added in v0.7.0

func FieldBytesBase64(value string) map[string]interface{}

FieldBytesBase64 creates a Bytes field value from a base64 string

func FieldDateTime ΒΆ added in v0.7.0

func FieldDateTime(value time.Time) map[string]interface{}

FieldDateTime creates a DateTime field value

func FieldDateTimeString ΒΆ added in v0.7.0

func FieldDateTimeString(value string) map[string]interface{}

FieldDateTimeString creates a DateTime field value from an RFC3339 string

func FieldDecimal ΒΆ added in v0.7.0

func FieldDecimal(value string) map[string]interface{}

FieldDecimal creates a Decimal field value for precise numeric values

func FieldDuration ΒΆ added in v0.7.0

func FieldDuration(milliseconds int64) map[string]interface{}

FieldDuration creates a Duration field value

func FieldDurationFromGo ΒΆ added in v0.7.0

func FieldDurationFromGo(d time.Duration) map[string]interface{}

FieldDurationFromGo creates a Duration field value from a Go time.Duration

func FieldFloat ΒΆ added in v0.7.0

func FieldFloat(value float64) map[string]interface{}

FieldFloat creates a Float field value (explicit wrapping)

func FieldInteger ΒΆ added in v0.7.0

func FieldInteger(value int64) map[string]interface{}

FieldInteger creates an Integer field value (explicit wrapping)

func FieldNumber ΒΆ added in v0.7.0

func FieldNumber(value interface{}) map[string]interface{}

FieldNumber creates a Number field value (flexible numeric type)

func FieldObject ΒΆ added in v0.7.0

func FieldObject(value map[string]interface{}) map[string]interface{}

FieldObject creates an Object field value

func FieldSet ΒΆ added in v0.7.0

func FieldSet(values interface{}) map[string]interface{}

FieldSet creates a Set field value (unique elements)

func FieldString ΒΆ added in v0.7.0

func FieldString(value string) map[string]interface{}

FieldString creates a String field value (explicit wrapping)

func FieldUUID ΒΆ added in v0.7.0

func FieldUUID(value string) map[string]interface{}

FieldUUID creates a UUID field value

func FieldVector ΒΆ added in v0.7.0

func FieldVector(values []float64) map[string]interface{}

FieldVector creates a Vector field value (for embeddings/similarity search)

func GetArrayValue ΒΆ added in v0.6.1

func GetArrayValue(field interface{}) []interface{}

GetArrayValue extracts a []interface{} from an ekoDB Array field

func GetBinaryValue ΒΆ added in v0.6.1

func GetBinaryValue(field interface{}) []byte

GetBinaryValue extracts a []byte from an ekoDB Binary field.

This function is a thin wrapper around GetBytesValue and is currently functionally identical to it. ekoDB may expose both "Binary" and "Bytes" field types in schemas, but in this client implementation they are represented and decoded in the same way (as []byte).

Having both GetBinaryValue and GetBytesValue allows callers to choose the helper that best matches their logical schema (e.g., using GetBinaryValue for fields declared as "Binary" in ekoDB), while keeping a single shared implementation for the actual conversion logic.

func GetBoolValue ΒΆ added in v0.6.1

func GetBoolValue(field interface{}) bool

GetBoolValue extracts a bool value from an ekoDB field

func GetBytesValue ΒΆ added in v0.6.1

func GetBytesValue(field interface{}) []byte

GetBytesValue extracts a []byte from an ekoDB Bytes field. The underlying field value may be:

  • []byte: returned as-is
  • []interface{}: each element must be a numeric value (typically float64) in the range [0, 255], which is converted to a byte. If any element is not numeric or is out of range, the function returns nil.
  • string: interpreted as a base64-encoded representation of the bytes and decoded using base64.StdEncoding. If decoding fails, the function returns nil.

For any other type or conversion error, GetBytesValue returns nil. Note: Returning nil can mean either a nil field or a conversion error.

func GetDateTimeValue ΒΆ added in v0.6.1

func GetDateTimeValue(field interface{}) *time.Time

GetDateTimeValue extracts a time.Time value from an ekoDB DateTime field. Supports time.Time values directly and RFC3339-formatted strings. Returns nil if the field is not a datetime or if string parsing fails.

func GetDecimalValue ΒΆ added in v0.6.1

func GetDecimalValue(field interface{}) float64

GetDecimalValue extracts a float64 from an ekoDB Decimal field. Accepts underlying values of type float64, int, int64, or a string containing a decimal representation. If conversion fails, it returns 0.0. This function extends GetFloatValue by adding support for string parsing.

func GetDurationValue ΒΆ added in v0.6.1

func GetDurationValue(field interface{}) time.Duration

GetDurationValue extracts a time.Duration from an ekoDB Duration field. It accepts the following underlying value formats:

  • time.Duration: returned as-is.
  • int64: interpreted as a time.Duration value in nanoseconds.
  • float64: interpreted as a duration in nanoseconds after truncation to int64. Warning: Fractional nanoseconds are truncated (e.g., 1.5 becomes 1 nanosecond). Large float64 values may overflow when converted to int64.
  • map[string]interface{} with "secs" and "nanos" float64 fields: {"secs": <seconds>, "nanos": <nanoseconds>} Both secs and nanos are truncated from float64 to int64, losing any fractional components (e.g., 1.5 seconds becomes 1 second). This is converted to secs*time.Second + nanos*time.Nanosecond.

Note: This function returns 0 for both an actual zero duration and invalid/malformed duration objects. Callers cannot distinguish between these cases. If the source of duration data is untrusted or may be corrupted, consider validating the structure before calling this function, or checking the raw field value first.

For any unsupported or invalid format, it returns 0.

func GetFloatValue ΒΆ added in v0.6.1

func GetFloatValue(field interface{}) float64

GetFloatValue extracts a float64 value from an ekoDB field

func GetIntValue ΒΆ added in v0.6.1

func GetIntValue(field interface{}) (int, bool)

GetIntValue extracts an int value from an ekoDB field. It returns the extracted int and a boolean indicating whether the conversion succeeded. Note: This function uses (int, bool) return signature for better error detection, unlike other getters which return zero values on failure. This allows callers to distinguish between actual zero values and conversion errors.

Conversion behavior:

  • int64: Converted to int. On 32-bit systems where int is 32 bits, values outside the range [-2147483648, 2147483647] will overflow. The function now validates this range and returns false for out-of-bounds values on 32-bit systems.
  • float64: Truncates the decimal portion (e.g., 3.9 becomes 3, -2.7 becomes -2). This is intentional for numeric type flexibility but callers should be aware that precision is lost. Returns false if the value would overflow int range.

func GetObjectValue ΒΆ added in v0.6.1

func GetObjectValue(field interface{}) map[string]interface{}

GetObjectValue extracts a map[string]interface{} from an ekoDB Object field

func GetSetValue ΒΆ added in v0.6.1

func GetSetValue(field interface{}) []interface{}

GetSetValue extracts a []interface{} from an ekoDB Set field.

This function is intentionally identical to GetArrayValue and does not validate or enforce element uniqueness. ekoDB enforces set semantics (uniqueness) on the server side, so data retrieved directly from ekoDB is expected to already be unique. If the source of the data is untrusted, manually constructed, or may be corrupted, callers should not rely on this guarantee and should perform their own uniqueness validation or deduplication if required.

func GetStringValue ΒΆ added in v0.6.1

func GetStringValue(field interface{}) string

GetStringValue extracts a string value from an ekoDB field

func GetUUIDValue ΒΆ added in v0.6.1

func GetUUIDValue(field interface{}) string

GetUUIDValue extracts a string UUID from an ekoDB UUID field

func GetValue ΒΆ added in v0.6.1

func GetValue(field interface{}) interface{}

GetValue extracts the value from an ekoDB field object. ekoDB returns fields as {"type": "String", "value": "..."} objects. This helper safely extracts the value or returns the input if it's not a field object.

Example:

user, _ := client.FindByID("users", userID)
email := GetStringValue(user["email"])
age := GetIntValue(user["age"])

func GetValues ΒΆ added in v0.6.1

func GetValues(record map[string]interface{}, fields []string) map[string]interface{}

GetValues extracts values from multiple fields in a record. Useful for processing entire records returned from ekoDB.

Example:

user, _ := client.FindByID("users", userID)
values := GetValues(user, []string{"email", "first_name", "status"})
email := GetStringValue(values["email"])

func GetVectorValue ΒΆ added in v0.6.1

func GetVectorValue(field interface{}) []float64

GetVectorValue extracts a []float64 from an ekoDB Vector field. Returns nil if any element cannot be converted to float64 to ensure vector dimension integrity. Note: Returning nil can mean either a nil field or a conversion error, which is important for vector operations where dimension integrity is critical.

func IntPtr ΒΆ

func IntPtr(v int) *int

IntPtr returns a pointer to an int value

func StringPtr ΒΆ

func StringPtr(v string) *string

StringPtr returns a pointer to a string value

Types ΒΆ

type BatchDeleteOptions ΒΆ added in v0.8.0

type BatchDeleteOptions struct {
	BypassRipple  *bool
	TransactionId *string
}

BatchDeleteOptions contains optional parameters for BatchDelete

type BatchInsertOptions ΒΆ added in v0.8.0

type BatchInsertOptions struct {
	BypassRipple  *bool
	TransactionId *string
}

BatchInsertOptions contains optional parameters for BatchInsert

type BatchUpdateOptions ΒΆ added in v0.8.0

type BatchUpdateOptions struct {
	BypassRipple  *bool
	TransactionId *string
}

BatchUpdateOptions contains optional parameters for BatchUpdate

type ChatMessage ΒΆ added in v0.4.0

type ChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

ChatMessage for AI operations

func NewChatMessage ΒΆ added in v0.4.0

func NewChatMessage(role, content string) ChatMessage

NewChatMessage creates a chat message

type ChatMessageRequest ΒΆ

type ChatMessageRequest struct {
	Message        string `json:"message"`
	BypassRipple   *bool  `json:"bypass_ripple,omitempty"`
	ForceSummarize *bool  `json:"force_summarize,omitempty"`
}

ChatMessageRequest represents a request to send a message in an existing session

type ChatRequest ΒΆ

type ChatRequest struct {
	Collections  []CollectionConfig `json:"collections"`
	LLMProvider  string             `json:"llm_provider"`
	LLMModel     *string            `json:"llm_model,omitempty"`
	Message      string             `json:"message"`
	SystemPrompt *string            `json:"system_prompt,omitempty"`
}

ChatRequest represents a request to send a chat message

type ChatResponse ΒΆ

type ChatResponse struct {
	ChatID          string        `json:"chat_id"`
	MessageID       string        `json:"message_id"`
	Responses       []string      `json:"responses"`
	ContextSnippets []interface{} `json:"context_snippets"`
	ExecutionTimeMs int           `json:"execution_time_ms"`
	TokenUsage      *TokenUsage   `json:"token_usage,omitempty"`
}

ChatResponse represents a response from a chat operation

type ChatSession ΒΆ

type ChatSession struct {
	ChatID       string             `json:"chat_id"`
	CreatedAt    string             `json:"created_at"`
	UpdatedAt    string             `json:"updated_at"`
	LLMProvider  string             `json:"llm_provider"`
	LLMModel     string             `json:"llm_model"`
	Collections  []CollectionConfig `json:"collections"`
	SystemPrompt *string            `json:"system_prompt,omitempty"`
	Title        *string            `json:"title,omitempty"`
	MessageCount int                `json:"message_count"`
}

ChatSession represents a chat session

type ChatSessionResponse ΒΆ

type ChatSessionResponse struct {
	Session      Record `json:"session"`
	MessageCount int    `json:"message_count"`
}

ChatSessionResponse represents a response containing session details

type Client ΒΆ

type Client struct {
	// contains filtered or unexported fields
}

Client represents an ekoDB client

func NewClient ΒΆ

func NewClient(baseURL, apiKey string) (*Client, error)

NewClient creates a new ekoDB client (legacy signature for backward compatibility)

func NewClientWithConfig ΒΆ

func NewClientWithConfig(config ClientConfig) (*Client, error)

NewClientWithConfig creates a new ekoDB client with configuration

func (*Client) BatchDelete ΒΆ

func (c *Client) BatchDelete(collection string, ids []string, opts ...BatchDeleteOptions) (int, error)

BatchDelete deletes multiple documents

func (*Client) BatchInsert ΒΆ

func (c *Client) BatchInsert(collection string, records []Record, opts ...BatchInsertOptions) ([]Record, error)

BatchInsert inserts multiple documents

func (*Client) BatchUpdate ΒΆ

func (c *Client) BatchUpdate(collection string, updates map[string]Record, opts ...BatchUpdateOptions) ([]Record, error)

BatchUpdate updates multiple documents

func (*Client) BeginTransaction ΒΆ added in v0.7.0

func (c *Client) BeginTransaction(isolationLevel string) (string, error)

BeginTransaction starts a new transaction on the server with the given isolation level. The isolationLevel parameter must be one of: "READ_UNCOMMITTED", "READ_COMMITTED", "REPEATABLE_READ", or "SERIALIZABLE". It returns the server-assigned transaction ID as a string, or an error if the transaction could not be created.

func (*Client) BranchChatSession ΒΆ

func (c *Client) BranchChatSession(request CreateChatSessionRequest) (*ChatResponse, error)

BranchChatSession branches a chat session

func (*Client) CallScript ΒΆ added in v0.4.0

func (c *Client) CallScript(labelOrID string, params map[string]interface{}) (*FunctionResult, error)

CallScript executes a script by label or ID

func (*Client) ChatMessage ΒΆ

func (c *Client) ChatMessage(sessionID string, request ChatMessageRequest) (*ChatResponse, error)

ChatMessage sends a message in an existing chat session

func (*Client) CommitTransaction ΒΆ added in v0.7.0

func (c *Client) CommitTransaction(transactionID string) error

CommitTransaction commits a transaction

func (*Client) CreateChatSession ΒΆ

func (c *Client) CreateChatSession(request CreateChatSessionRequest) (*ChatResponse, error)

CreateChatSession creates a new chat session

func (*Client) CreateCollection ΒΆ

func (c *Client) CreateCollection(collection string, schema Schema) error

CreateCollection creates a collection with schema

func (*Client) Delete ΒΆ

func (c *Client) Delete(collection, id string, opts ...DeleteOptions) error

Delete deletes a document

func (*Client) DeleteChatMessage ΒΆ

func (c *Client) DeleteChatMessage(sessionID, messageID string) error

DeleteChatMessage deletes a specific message

func (*Client) DeleteChatSession ΒΆ

func (c *Client) DeleteChatSession(sessionID string) error

DeleteChatSession deletes a chat session

func (*Client) DeleteCollection ΒΆ

func (c *Client) DeleteCollection(collection string) error

DeleteCollection deletes a collection

func (*Client) DeleteScript ΒΆ added in v0.4.0

func (c *Client) DeleteScript(id string) error

DeleteScript deletes a script by ID

func (*Client) Embed ΒΆ added in v0.5.0

func (c *Client) Embed(text, model string) ([]float64, error)

Embed generates embeddings for text using ekoDB's native Functions

This helper simplifies embedding generation by: 1. Creating a temporary collection with the text 2. Running a Script with FindAll + Embed Functions 3. Extracting and returning the embedding vector 4. Cleaning up temporary resources

Example:

embedding, err := client.Embed("Hello world", "text-embedding-3-small")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Generated %d dimensions\n", len(embedding))

func (*Client) Exists ΒΆ added in v0.8.0

func (c *Client) Exists(collection, id string) (bool, error)

Exists checks if a record exists by ID Returns true if the record exists, false if it doesn't.

func (*Client) Find ΒΆ

func (c *Client) Find(collection string, query interface{}, opts ...FindOptions) ([]Record, error)

Find finds documents in a collection

func (*Client) FindAll ΒΆ added in v0.5.0

func (c *Client) FindAll(collection string, limit int) ([]Record, error)

FindAll finds all records in a collection with a limit

Simplified method to query all documents in a collection.

Example:

allMessages, err := client.FindAll("messages", 1000)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Found %d messages\n", len(allMessages))

func (*Client) FindByID ΒΆ

func (c *Client) FindByID(collection, id string) (Record, error)

FindByID finds a document by ID

func (*Client) FindByIDWithProjection ΒΆ added in v0.9.0

func (c *Client) FindByIDWithProjection(collection, id string, selectFields, excludeFields []string) (Record, error)

FindByIDWithProjection finds a document by ID with field projection selectFields: only return these fields (plus 'id') excludeFields: exclude these fields from results

func (*Client) FindOne ΒΆ added in v0.8.0

func (c *Client) FindOne(collection, field string, value interface{}) (Record, error)

FindOne finds a single record by field value Returns nil if no record matches, or the first matching record.

func (*Client) GetChatSession ΒΆ

func (c *Client) GetChatSession(sessionID string) (*ChatSessionResponse, error)

GetChatSession gets a chat session by ID

func (*Client) GetChatSessionMessages ΒΆ

func (c *Client) GetChatSessionMessages(sessionID string, query *GetMessagesQuery) (*GetMessagesResponse, error)

GetChatSessionMessages gets messages from a chat session

func (*Client) GetCollection ΒΆ

func (c *Client) GetCollection(collection string) (*CollectionMetadata, error)

GetCollection gets collection metadata and schema

func (*Client) GetRateLimitInfo ΒΆ

func (c *Client) GetRateLimitInfo() *RateLimitInfo

GetRateLimitInfo returns the current rate limit information

func (*Client) GetSchema ΒΆ

func (c *Client) GetSchema(collection string) (*Schema, error)

GetSchema gets collection schema

func (*Client) GetScript ΒΆ added in v0.4.0

func (c *Client) GetScript(id string) (*Script, error)

GetScript retrieves a script by ID

func (*Client) GetTransactionStatus ΒΆ added in v0.7.0

func (c *Client) GetTransactionStatus(transactionID string) (map[string]interface{}, error)

GetTransactionStatus gets the status of a transaction

func (*Client) Health ΒΆ added in v0.2.0

func (c *Client) Health() error

Health checks if the ekoDB server is healthy

func (*Client) HybridSearch ΒΆ added in v0.5.0

func (c *Client) HybridSearch(collection, queryText string, queryVector []float64, limit int) ([]Record, error)

HybridSearch performs hybrid search combining text and vector search

Combines semantic similarity (vector search) with keyword matching (text search) for more accurate and relevant results.

Example:

embedding, _ := client.Embed(query, "text-embedding-3-small")
results, err := client.HybridSearch("documents", query, embedding, 5)
if err != nil {
    log.Fatal(err)
}

func (*Client) Insert ΒΆ

func (c *Client) Insert(collection string, record Record, opts ...InsertOptions) (Record, error)

Insert inserts a document into a collection Usage:

Insert(collection, record)                                    // basic insert
Insert(collection, record, InsertOptions{TTL: "1h"})          // with TTL
Insert(collection, record, InsertOptions{BypassRipple: &t})   // bypass ripple

func (*Client) IsNearRateLimit ΒΆ

func (c *Client) IsNearRateLimit() bool

IsNearRateLimit checks if approaching rate limit

func (*Client) KVBatchDelete ΒΆ added in v0.9.0

func (c *Client) KVBatchDelete(keys []string) ([][]interface{}, error)

KVBatchDelete deletes multiple keys in a single request

func (*Client) KVBatchGet ΒΆ added in v0.9.0

func (c *Client) KVBatchGet(keys []string) ([]map[string]interface{}, error)

KVBatchGet retrieves multiple keys in a single request

func (*Client) KVBatchSet ΒΆ added in v0.9.0

func (c *Client) KVBatchSet(entries []map[string]interface{}) ([][]interface{}, error)

KVBatchSet sets multiple key-value pairs in a single request. TTL from the first entry with a valid TTL is applied to all entries (server limitation).

func (*Client) KVDelete ΒΆ

func (c *Client) KVDelete(key string) error

KVDelete deletes a key

func (*Client) KVExists ΒΆ added in v0.7.0

func (c *Client) KVExists(key string) (bool, error)

KVExists checks if a key exists

func (*Client) KVFind ΒΆ added in v0.7.0

func (c *Client) KVFind(pattern string, includeExpired bool) ([]map[string]interface{}, error)

KVFind queries/finds KV entries with pattern matching. The pattern supports simple wildcards where '*' matches any sequence of characters in a key. If includeExpired is true, results will also include entries that are past their configured TTL but may still be present in the store.

func (*Client) KVGet ΒΆ

func (c *Client) KVGet(key string) (interface{}, error)

KVGet gets a value by key

func (*Client) KVQuery ΒΆ added in v0.7.0

func (c *Client) KVQuery(pattern string, includeExpired bool) ([]map[string]interface{}, error)

KVQuery is an alias for KVFind - queries KV store with pattern

func (*Client) KVSet ΒΆ

func (c *Client) KVSet(key string, value interface{}) error

KVSet sets a key-value pair

func (*Client) ListChatSessions ΒΆ

func (c *Client) ListChatSessions(query *ListSessionsQuery) (*ListSessionsResponse, error)

ListChatSessions lists all chat sessions

func (*Client) ListCollections ΒΆ

func (c *Client) ListCollections() ([]string, error)

ListCollections lists all collections

func (*Client) ListScripts ΒΆ added in v0.4.0

func (c *Client) ListScripts(tags []string) ([]Script, error)

ListScripts lists all scripts, optionally filtered by tags

func (*Client) MergeChatSessions ΒΆ

func (c *Client) MergeChatSessions(request MergeSessionsRequest) (*ChatSessionResponse, error)

MergeChatSessions merges multiple chat sessions into one

func (*Client) Paginate ΒΆ added in v0.8.0

func (c *Client) Paginate(collection string, page, pageSize int) ([]Record, error)

Paginate retrieves records with pagination (1-indexed page numbers) Page 1 = first page, Page 2 = second page, etc. Returns an error if page < 1 or pageSize < 1.

func (*Client) RegenerateChatMessage ΒΆ

func (c *Client) RegenerateChatMessage(sessionID, messageID string) (*ChatResponse, error)

RegenerateChatMessage regenerates an AI response message

func (*Client) RestoreCollection ΒΆ added in v0.8.0

func (c *Client) RestoreCollection(collection string) (int, error)

RestoreCollection restores all deleted records in a collection from trash Records remain in trash for 30 days before permanent deletion

func (*Client) RestoreRecord ΒΆ added in v0.8.0

func (c *Client) RestoreRecord(collection, id string) error

RestoreRecord restores a deleted record from trash Records remain in trash for 30 days before permanent deletion

func (*Client) RollbackTransaction ΒΆ added in v0.7.0

func (c *Client) RollbackTransaction(transactionID string) error

RollbackTransaction rolls back a transaction

func (*Client) SaveScript ΒΆ added in v0.4.0

func (c *Client) SaveScript(script Script) (string, error)

SaveScript creates a new script

func (*Client) Search ΒΆ

func (c *Client) Search(collection string, searchQuery SearchQuery) (*SearchResponse, error)

Search performs a search query on a collection

func (*Client) TextSearch ΒΆ added in v0.5.0

func (c *Client) TextSearch(collection, queryText string, limit int) ([]Record, error)

TextSearch performs text search without embeddings

Simplified text search with full-text matching, fuzzy search, and stemming.

Example:

results, err := client.TextSearch("documents", "ownership system", 10)
if err != nil {
    log.Fatal(err)
}

func (*Client) ToggleForgottenMessage ΒΆ

func (c *Client) ToggleForgottenMessage(sessionID, messageID string, forgotten bool) error

ToggleForgottenMessage toggles the "forgotten" status of a message

func (*Client) Update ΒΆ

func (c *Client) Update(collection, id string, record Record, opts ...UpdateOptions) (Record, error)

Update updates a document

func (*Client) UpdateChatMessage ΒΆ

func (c *Client) UpdateChatMessage(sessionID, messageID, content string) error

UpdateChatMessage updates a specific message

func (*Client) UpdateChatSession ΒΆ

func (c *Client) UpdateChatSession(sessionID string, request UpdateSessionRequest) (*ChatSessionResponse, error)

UpdateChatSession updates a chat session

func (*Client) UpdateScript ΒΆ added in v0.4.0

func (c *Client) UpdateScript(id string, script Script) error

UpdateScript updates an existing script by ID

func (*Client) Upsert ΒΆ added in v0.8.0

func (c *Client) Upsert(collection, id string, record Record, opts ...UpsertOptions) (Record, error)

Upsert inserts or updates a document (atomic insert-or-update) Attempts to update first. If the record doesn't exist (404), it will be inserted.

func (*Client) WebSocket ΒΆ

func (c *Client) WebSocket(wsURL string) (*WebSocketClient, error)

WebSocket creates a new WebSocket client

type ClientConfig ΒΆ

type ClientConfig struct {
	BaseURL     string              // Base URL of the ekoDB server
	APIKey      string              // API key for authentication
	ShouldRetry bool                // Enable automatic retries (default: true)
	MaxRetries  int                 // Maximum number of retry attempts (default: 3)
	Timeout     time.Duration       // Request timeout (default: 30s)
	Format      SerializationFormat // Serialization format (default: MessagePack for best performance, use JSON for debugging)
}

ClientConfig contains configuration options for the client

type CollectionConfig ΒΆ

type CollectionConfig struct {
	CollectionName string        `json:"collection_name"`
	Fields         []interface{} `json:"fields"`
	SearchOptions  interface{}   `json:"search_options,omitempty"`
}

CollectionConfig represents configuration for searching a specific collection

type CollectionMetadata ΒΆ

type CollectionMetadata struct {
	Collection Schema      `json:"collection"`
	Analytics  interface{} `json:"analytics,omitempty"`
}

CollectionMetadata represents collection metadata with analytics

type CreateChatSessionRequest ΒΆ

type CreateChatSessionRequest struct {
	Collections        []CollectionConfig `json:"collections"`
	LLMProvider        string             `json:"llm_provider"`
	LLMModel           *string            `json:"llm_model,omitempty"`
	SystemPrompt       *string            `json:"system_prompt,omitempty"`
	BypassRipple       *bool              `json:"bypass_ripple,omitempty"`
	ParentID           *string            `json:"parent_id,omitempty"`
	BranchPointIdx     *int               `json:"branch_point_idx,omitempty"`
	MaxContextMessages *int               `json:"max_context_messages,omitempty"`
}

CreateChatSessionRequest represents a request to create a new chat session

type DeleteOptions ΒΆ added in v0.8.0

type DeleteOptions struct {
	BypassRipple  *bool
	TransactionId *string
}

DeleteOptions contains optional parameters for Delete

type DistanceMetric ΒΆ

type DistanceMetric string

DistanceMetric represents the distance metric for vector similarity

const (
	// DistanceMetricCosine represents cosine similarity
	DistanceMetricCosine DistanceMetric = "cosine"
	// DistanceMetricEuclidean represents euclidean distance
	DistanceMetricEuclidean DistanceMetric = "euclidean"
	// DistanceMetricDotProduct represents dot product
	DistanceMetricDotProduct DistanceMetric = "dotproduct"
)

type FieldTypeSchema ΒΆ

type FieldTypeSchema struct {
	FieldType string        `json:"field_type"`
	Default   interface{}   `json:"default,omitempty"`
	Unique    bool          `json:"unique,omitempty"`
	Required  bool          `json:"required,omitempty"`
	Enums     []interface{} `json:"enums,omitempty"`
	Max       interface{}   `json:"max,omitempty"`
	Min       interface{}   `json:"min,omitempty"`
	Regex     *string       `json:"regex,omitempty"`
	Index     *IndexConfig  `json:"index,omitempty"`
}

FieldTypeSchema represents field type schema with constraints

type FieldTypeSchemaBuilder ΒΆ

type FieldTypeSchemaBuilder struct {
	// contains filtered or unexported fields
}

FieldTypeSchemaBuilder provides a fluent API for building field type schemas

func NewFieldTypeSchemaBuilder ΒΆ

func NewFieldTypeSchemaBuilder(fieldType string) *FieldTypeSchemaBuilder

NewFieldTypeSchemaBuilder creates a new FieldTypeSchemaBuilder

func (*FieldTypeSchemaBuilder) BTreeIndex ΒΆ

BTreeIndex adds a B-tree index

func (*FieldTypeSchemaBuilder) Build ΒΆ

Build builds the final FieldTypeSchema

func (*FieldTypeSchemaBuilder) DefaultValue ΒΆ

func (fb *FieldTypeSchemaBuilder) DefaultValue(value interface{}) *FieldTypeSchemaBuilder

DefaultValue sets a default value

func (*FieldTypeSchemaBuilder) Enums ΒΆ

func (fb *FieldTypeSchemaBuilder) Enums(values []interface{}) *FieldTypeSchemaBuilder

Enums sets enum values

func (*FieldTypeSchemaBuilder) HashIndex ΒΆ

HashIndex adds a hash index

func (*FieldTypeSchemaBuilder) Pattern ΒΆ

Pattern sets regex pattern

func (*FieldTypeSchemaBuilder) Range ΒΆ

func (fb *FieldTypeSchemaBuilder) Range(min, max interface{}) *FieldTypeSchemaBuilder

Range sets min/max range

func (*FieldTypeSchemaBuilder) Required ΒΆ

Required sets the field as required

func (*FieldTypeSchemaBuilder) TextIndex ΒΆ

func (fb *FieldTypeSchemaBuilder) TextIndex(language string) *FieldTypeSchemaBuilder

TextIndex adds a text index

func (*FieldTypeSchemaBuilder) Unique ΒΆ

Unique sets the field as unique

func (*FieldTypeSchemaBuilder) VectorIndex ΒΆ

func (fb *FieldTypeSchemaBuilder) VectorIndex(algorithm VectorIndexAlgorithm, metric DistanceMetric, m, efConstruction int) *FieldTypeSchemaBuilder

VectorIndex adds a vector index

type FieldValue ΒΆ added in v0.6.1

type FieldValue struct {
	Type  string      `json:"type"`
	Value interface{} `json:"value"`
}

FieldValue represents an ekoDB field with type and value

type FindOptions ΒΆ added in v0.8.0

type FindOptions struct {
	Filter        interface{}
	Sort          interface{}
	Limit         *int
	Skip          *int
	Join          interface{}
	BypassCache   *bool
	BypassRipple  *bool
	SelectFields  []string
	ExcludeFields []string
}

FindOptions contains optional parameters for Find

type FunctionResult ΒΆ added in v0.4.0

type FunctionResult struct {
	Records []map[string]interface{} `json:"records"`
	Stats   FunctionStats            `json:"stats"`
}

FunctionResult from execution

type FunctionStageConfig ΒΆ added in v0.4.0

type FunctionStageConfig struct {
	Stage string                 `json:"stage"`
	Data  map[string]interface{} `json:",inline"`
}

FunctionStageConfig represents a pipeline stage

func StageBatchDelete ΒΆ added in v0.4.0

func StageBatchDelete(collection string, ids []string, bypassRipple bool) FunctionStageConfig

func StageBatchInsert ΒΆ added in v0.4.0

func StageBatchInsert(collection string, records []map[string]interface{}, bypassRipple bool) FunctionStageConfig

StageBatchInsert inserts multiple records into a collection

func StageCallFunction ΒΆ added in v0.6.0

func StageCallFunction(functionLabel string, params map[string]interface{}) FunctionStageConfig

StageCallFunction calls a saved UserFunction by label

func StageChat ΒΆ added in v0.4.0

func StageChat(messages []ChatMessage, model *string, temperature *float64) FunctionStageConfig

func StageCount ΒΆ added in v0.4.0

func StageCount(outputField string) FunctionStageConfig

func StageCreateSavepoint ΒΆ added in v0.6.0

func StageCreateSavepoint(name string) FunctionStageConfig

StageCreateSavepoint creates a savepoint for partial rollback

func StageDelete ΒΆ added in v0.4.0

func StageDelete(collection string, filter interface{}, bypassRipple bool) FunctionStageConfig

StageDelete deletes records matching a filter (use StageDeleteById for ID-based deletion)

func StageDeleteById ΒΆ added in v0.4.0

func StageDeleteById(collection string, recordId string, bypassRipple bool) FunctionStageConfig

StageDeleteById deletes a specific record by ID

func StageEmbed ΒΆ added in v0.4.0

func StageEmbed(texts interface{}, model *string) FunctionStageConfig

func StageFindAll ΒΆ added in v0.4.0

func StageFindAll(collection string) FunctionStageConfig

Stage builders

func StageFindById ΒΆ added in v0.6.0

func StageFindById(collection string, recordId string) FunctionStageConfig

StageFindById finds a specific record by ID

func StageFindOne ΒΆ added in v0.6.0

func StageFindOne(collection string, key string, value interface{}) FunctionStageConfig

StageFindOne finds one record by key/value pair

func StageFindOneAndUpdate ΒΆ added in v0.6.0

func StageFindOneAndUpdate(collection string, recordId string, updates map[string]interface{}, bypassRipple bool, ttl *int64) FunctionStageConfig

StageFindOneAndUpdate finds and updates a record atomically

func StageForEach ΒΆ added in v0.6.0

func StageForEach(functions []FunctionStageConfig) FunctionStageConfig

StageForEach executes functions for each record

func StageGroup ΒΆ added in v0.4.0

func StageGroup(by_fields []string, functions []GroupFunctionConfig) FunctionStageConfig

func StageHttpRequest ΒΆ added in v0.4.0

func StageHttpRequest(url, method string, headers map[string]string, body interface{}) FunctionStageConfig

func StageHybridSearch ΒΆ added in v0.4.0

func StageHybridSearch(collection string, queryText string, queryVector []float64, options map[string]interface{}) FunctionStageConfig

func StageIf ΒΆ added in v0.6.0

func StageIf(condition ScriptCondition, thenFunctions []FunctionStageConfig, elseFunctions []FunctionStageConfig) FunctionStageConfig

StageIf executes functions conditionally

func StageInsert ΒΆ added in v0.4.0

func StageInsert(collection string, record map[string]interface{}, bypassRipple bool, ttl *int64) FunctionStageConfig

StageInsert inserts a single record into a collection

func StageKvDelete ΒΆ added in v0.7.0

func StageKvDelete(key string) FunctionStageConfig

StageKvDelete deletes a key from the KV store

func StageKvExists ΒΆ added in v0.7.0

func StageKvExists(key string, outputField *string) FunctionStageConfig

StageKvExists checks if a key exists in the KV store

func StageKvGet ΒΆ added in v0.7.0

func StageKvGet(key string, outputField *string) FunctionStageConfig

StageKvGet retrieves a value from the KV store

func StageKvQuery ΒΆ added in v0.7.0

func StageKvQuery(pattern *string, includeExpired bool) FunctionStageConfig

StageKvQuery queries the KV store with a pattern

func StageKvSet ΒΆ added in v0.7.0

func StageKvSet(key string, value interface{}, ttl *int64) FunctionStageConfig

StageKvSet stores a value in the KV store

func StageProject ΒΆ added in v0.4.0

func StageProject(fields []string, exclude bool) FunctionStageConfig

StageProject selects or excludes specific fields from results exclude=false means include only these fields, exclude=true means exclude these fields

func StageQuery ΒΆ added in v0.4.0

func StageQuery(collection string, filter interface{}, sort []SortFieldConfig, limit, skip *int) FunctionStageConfig

StageQuery queries a collection with optional filter, sort, limit, skip

func StageReleaseSavepoint ΒΆ added in v0.6.0

func StageReleaseSavepoint(name string) FunctionStageConfig

StageReleaseSavepoint releases a savepoint

func StageRollbackToSavepoint ΒΆ added in v0.6.0

func StageRollbackToSavepoint(name string) FunctionStageConfig

StageRollbackToSavepoint rolls back to a specific savepoint

func StageSWR ΒΆ added in v0.9.0

func StageSWR(
	cacheKey string,
	ttl interface{},
	url string,
	method string,
	headers map[string]string,
	body interface{},
	timeoutSeconds *int,
	outputField *string,
	collection *string,
) FunctionStageConfig

StageSWR creates a Stale-While-Revalidate pattern for external API caching. Automatically handles: KV cache check β†’ HTTP request β†’ KV cache set β†’ optional audit storage.

Parameters:

  • cacheKey: KV key for caching (supports parameter substitution like "user:{{user_id}}")
  • ttl: Cache TTL - server accepts duration strings ("15m", "1h"), integers (seconds), or ISO timestamps
  • url: HTTP URL to fetch from (supports parameter substitution)
  • method: HTTP method (e.g., "GET", "POST")
  • headers: Optional HTTP headers
  • body: Optional HTTP request body
  • timeoutSeconds: Optional HTTP timeout
  • outputField: Field name for response in enriched params (nil uses server default "response")
  • collection: Optional collection for audit trail storage

func StageTextSearch ΒΆ added in v0.4.0

func StageTextSearch(collection string, queryText string, options map[string]interface{}) FunctionStageConfig

func StageUpdate ΒΆ added in v0.6.0

func StageUpdate(collection string, filter interface{}, updates map[string]interface{}, bypassRipple bool, ttl *int64) FunctionStageConfig

StageUpdate updates records matching a filter

func StageUpdateById ΒΆ added in v0.6.0

func StageUpdateById(collection string, recordId string, updates map[string]interface{}, bypassRipple bool, ttl *int64) FunctionStageConfig

StageUpdateById updates a specific record by ID

func StageUpdateWithAction ΒΆ added in v0.6.0

func StageUpdateWithAction(collection string, recordId string, action string, field string, value interface{}, bypassRipple bool) FunctionStageConfig

StageUpdateWithAction updates a record with a specific action (push, pop, increment, decrement, remove). Use the UpdateAction constants for type safety: UpdateActionPush, UpdateActionPop, UpdateActionIncrement, UpdateActionDecrement, UpdateActionRemove.

func StageVectorSearch ΒΆ added in v0.4.0

func StageVectorSearch(collection string, queryVector []float64, limit *int, threshold *float64) FunctionStageConfig

StageVectorSearch performs vector similarity search

func (FunctionStageConfig) MarshalJSON ΒΆ added in v0.4.0

func (f FunctionStageConfig) MarshalJSON() ([]byte, error)

MarshalJSON custom marshaling for FunctionStageConfig

type FunctionStats ΒΆ added in v0.4.0

type FunctionStats struct {
	InputCount      int          `json:"input_count"`
	OutputCount     int          `json:"output_count"`
	ExecutionTimeMs int64        `json:"execution_time_ms"`
	StagesExecuted  int          `json:"stages_executed"`
	StageStats      []StageStats `json:"stage_stats"`
}

FunctionStats contains execution statistics

type GetMessagesQuery ΒΆ

type GetMessagesQuery struct {
	Limit *int    `json:"limit,omitempty"`
	Skip  *int    `json:"skip,omitempty"`
	Sort  *string `json:"sort,omitempty"`
}

GetMessagesQuery represents query parameters for getting messages

type GetMessagesResponse ΒΆ

type GetMessagesResponse struct {
	Messages []Record `json:"messages"`
	Total    int      `json:"total"`
	Skip     int      `json:"skip"`
	Limit    *int     `json:"limit,omitempty"`
	Returned int      `json:"returned"`
}

GetMessagesResponse represents a response containing messages

type GroupFunctionConfig ΒΆ added in v0.4.0

type GroupFunctionConfig struct {
	OutputField string          `json:"output_field"`
	Operation   GroupFunctionOp `json:"operation"`
	InputField  *string         `json:"input_field,omitempty"`
}

GroupFunctionConfig for Group stage

type GroupFunctionOp ΒΆ added in v0.4.0

type GroupFunctionOp string
const (
	GroupFunctionSum     GroupFunctionOp = "Sum"
	GroupFunctionAverage GroupFunctionOp = "Average"
	GroupFunctionCount   GroupFunctionOp = "Count"
	GroupFunctionMin     GroupFunctionOp = "Min"
	GroupFunctionMax     GroupFunctionOp = "Max"
	GroupFunctionFirst   GroupFunctionOp = "First"
	GroupFunctionLast    GroupFunctionOp = "Last"
	GroupFunctionPush    GroupFunctionOp = "Push"
)

type HTTPError ΒΆ added in v0.7.0

type HTTPError struct {
	StatusCode int
	Message    string
}

HTTPError represents an HTTP error with status code

func (*HTTPError) Error ΒΆ added in v0.7.0

func (e *HTTPError) Error() string

func (*HTTPError) IsNotFound ΒΆ added in v0.7.0

func (e *HTTPError) IsNotFound() bool

IsNotFound checks if the error is a 404 Not Found error

type IndexConfig ΒΆ

type IndexConfig struct {
	Type           string                `json:"type"`
	Language       *string               `json:"language,omitempty"`
	Analyzer       *string               `json:"analyzer,omitempty"`
	Algorithm      *VectorIndexAlgorithm `json:"algorithm,omitempty"`
	Metric         *DistanceMetric       `json:"metric,omitempty"`
	M              *int                  `json:"m,omitempty"`
	EfConstruction *int                  `json:"ef_construction,omitempty"`
}

IndexConfig represents index configuration for a field

type InsertOptions ΒΆ added in v0.8.0

type InsertOptions struct {
	TTL           string
	BypassRipple  *bool
	TransactionId *string
	BypassCache   *bool
}

InsertOptions contains optional parameters for Insert

type JoinConfig ΒΆ

type JoinConfig struct {
	Collections  []string `json:"collections"`
	LocalField   string   `json:"local_field"`
	ForeignField string   `json:"foreign_field"`
	AsField      string   `json:"as_field"`
}

JoinConfig represents configuration for joining collections

func NewJoinConfig ΒΆ

func NewJoinConfig(collections []string, localField, foreignField, asField string) JoinConfig

NewJoinConfig creates a new join configuration

func NewSingleJoin ΒΆ

func NewSingleJoin(collection, localField, foreignField, asField string) JoinConfig

NewSingleJoin creates a join with a single collection

func (JoinConfig) ToMap ΒΆ

func (j JoinConfig) ToMap() map[string]interface{}

ToMap converts JoinConfig to a map for use in queries

type ListSessionsQuery ΒΆ

type ListSessionsQuery struct {
	Limit *int    `json:"limit,omitempty"`
	Skip  *int    `json:"skip,omitempty"`
	Sort  *string `json:"sort,omitempty"`
}

ListSessionsQuery represents query parameters for listing sessions

type ListSessionsResponse ΒΆ

type ListSessionsResponse struct {
	Sessions []ChatSession `json:"sessions"`
	Total    int           `json:"total"`
	Returned int           `json:"returned"`
}

ListSessionsResponse represents a response containing list of sessions

type MergeSessionsRequest ΒΆ

type MergeSessionsRequest struct {
	SourceChatIDs []string      `json:"source_chat_ids"`
	TargetChatID  string        `json:"target_chat_id"`
	MergeStrategy MergeStrategy `json:"merge_strategy"`
}

MergeSessionsRequest represents a request to merge multiple chat sessions

type MergeStrategy ΒΆ

type MergeStrategy string

MergeStrategy represents how to merge chat sessions

const (
	MergeStrategyChronological MergeStrategy = "Chronological"
	MergeStrategySummarized    MergeStrategy = "Summarized"
	MergeStrategyLatestOnly    MergeStrategy = "LatestOnly"
)

type ParameterDefinition ΒΆ added in v0.4.0

type ParameterDefinition struct {
	Required    bool        `json:"required"`
	Default     interface{} `json:"default,omitempty"`
	Description string      `json:"description,omitempty"`
}

ParameterDefinition for function parameters

type Query ΒΆ

type Query struct {
	Limit  *int                   `json:"limit,omitempty"`
	Offset *int                   `json:"offset,omitempty"`
	Filter map[string]interface{} `json:"filter,omitempty"`
}

Query represents a query for finding records

type QueryBuilder ΒΆ

type QueryBuilder struct {
	// contains filtered or unexported fields
}

QueryBuilder provides a fluent API for building complex queries

func NewQueryBuilder ΒΆ

func NewQueryBuilder() *QueryBuilder

NewQueryBuilder creates a new QueryBuilder

func (*QueryBuilder) And ΒΆ

func (qb *QueryBuilder) And(conditions []map[string]interface{}) *QueryBuilder

And combines filters with AND logic

func (*QueryBuilder) Build ΒΆ

func (qb *QueryBuilder) Build() map[string]interface{}

Build builds the final query map

func (*QueryBuilder) BuildJSON ΒΆ

func (qb *QueryBuilder) BuildJSON() ([]byte, error)

BuildJSON builds the final query as JSON bytes

func (*QueryBuilder) BypassCache ΒΆ

func (qb *QueryBuilder) BypassCache(bypass bool) *QueryBuilder

BypassCache bypasses cache for this query

func (*QueryBuilder) BypassRipple ΒΆ

func (qb *QueryBuilder) BypassRipple(bypass bool) *QueryBuilder

BypassRipple bypasses ripple for this query

func (*QueryBuilder) Contains ΒΆ

func (qb *QueryBuilder) Contains(field string, substring string) *QueryBuilder

Contains adds a contains filter (substring match)

func (*QueryBuilder) EndsWith ΒΆ

func (qb *QueryBuilder) EndsWith(field string, suffix string) *QueryBuilder

EndsWith adds an ends-with filter

func (*QueryBuilder) Eq ΒΆ

func (qb *QueryBuilder) Eq(field string, value interface{}) *QueryBuilder

Eq adds an equality filter (Eq operator)

func (*QueryBuilder) ExcludeFields ΒΆ added in v0.9.0

func (qb *QueryBuilder) ExcludeFields(fields ...string) *QueryBuilder

ExcludeFields specifies which fields to exclude from results. All fields except these will be included in results. When used with SelectFields, exclude removes fields from the selected set.

func (*QueryBuilder) Gt ΒΆ

func (qb *QueryBuilder) Gt(field string, value interface{}) *QueryBuilder

Gt adds a greater-than filter (Gt operator)

func (*QueryBuilder) Gte ΒΆ

func (qb *QueryBuilder) Gte(field string, value interface{}) *QueryBuilder

Gte adds a greater-than-or-equal filter (Gte operator)

func (*QueryBuilder) In ΒΆ

func (qb *QueryBuilder) In(field string, values []interface{}) *QueryBuilder

In adds an in-array filter (In operator)

func (*QueryBuilder) Join ΒΆ

func (qb *QueryBuilder) Join(joinConfig map[string]interface{}) *QueryBuilder

Join adds a join configuration

func (*QueryBuilder) Limit ΒΆ

func (qb *QueryBuilder) Limit(limit int) *QueryBuilder

Limit sets the maximum number of results

func (*QueryBuilder) Lt ΒΆ

func (qb *QueryBuilder) Lt(field string, value interface{}) *QueryBuilder

Lt adds a less-than filter (Lt operator)

func (*QueryBuilder) Lte ΒΆ

func (qb *QueryBuilder) Lte(field string, value interface{}) *QueryBuilder

Lte adds a less-than-or-equal filter (Lte operator)

func (*QueryBuilder) Ne ΒΆ

func (qb *QueryBuilder) Ne(field string, value interface{}) *QueryBuilder

Ne adds a not-equal filter (Ne operator)

func (*QueryBuilder) Nin ΒΆ

func (qb *QueryBuilder) Nin(field string, values []interface{}) *QueryBuilder

Nin adds a not-in-array filter (NotIn operator)

func (*QueryBuilder) Not ΒΆ

func (qb *QueryBuilder) Not(condition map[string]interface{}) *QueryBuilder

Not negates a filter

func (*QueryBuilder) Or ΒΆ

func (qb *QueryBuilder) Or(conditions []map[string]interface{}) *QueryBuilder

Or combines filters with OR logic

func (*QueryBuilder) Page ΒΆ

func (qb *QueryBuilder) Page(page, pageSize int) *QueryBuilder

Page sets page number and page size (convenience method)

func (*QueryBuilder) Regex ΒΆ added in v0.1.2

func (qb *QueryBuilder) Regex(field string, pattern string) *QueryBuilder

Regex adds a regex pattern match filter

func (*QueryBuilder) SelectFields ΒΆ added in v0.9.0

func (qb *QueryBuilder) SelectFields(fields ...string) *QueryBuilder

SelectFields specifies which fields to return (projection). Only these fields will be included in results (plus 'id' which is always included). When used with ExcludeFields, select is applied first, then exclude removes fields from the selected set (useful for nested fields like "metadata.internal").

func (*QueryBuilder) Skip ΒΆ

func (qb *QueryBuilder) Skip(skip int) *QueryBuilder

Skip sets the number of results to skip (for pagination)

func (*QueryBuilder) SortAscending ΒΆ

func (qb *QueryBuilder) SortAscending(field string) *QueryBuilder

SortAscending adds a sort field in ascending order

func (*QueryBuilder) SortDescending ΒΆ

func (qb *QueryBuilder) SortDescending(field string) *QueryBuilder

SortDescending adds a sort field in descending order

func (*QueryBuilder) StartsWith ΒΆ

func (qb *QueryBuilder) StartsWith(field string, prefix string) *QueryBuilder

StartsWith adds a starts-with filter

type RateLimitError ΒΆ

type RateLimitError struct {
	RetryAfterSecs int
	Message        string
}

RateLimitError represents a rate limit error

func (*RateLimitError) Error ΒΆ

func (e *RateLimitError) Error() string

type RateLimitInfo ΒΆ

type RateLimitInfo struct {
	Limit     int   // Maximum requests allowed per window
	Remaining int   // Requests remaining in current window
	Reset     int64 // Unix timestamp when the rate limit resets
}

RateLimitInfo contains rate limit information from the server

func (*RateLimitInfo) IsExceeded ΒΆ

func (r *RateLimitInfo) IsExceeded() bool

IsExceeded checks if the rate limit has been exceeded

func (*RateLimitInfo) IsNearLimit ΒΆ

func (r *RateLimitInfo) IsNearLimit() bool

IsNearLimit checks if approaching rate limit (less than 10% remaining)

func (*RateLimitInfo) RemainingPercentage ΒΆ

func (r *RateLimitInfo) RemainingPercentage() float64

RemainingPercentage returns the percentage of requests remaining

type Record ΒΆ

type Record map[string]interface{}

Record represents a document in ekoDB

type Schema ΒΆ

type Schema struct {
	Fields       map[string]FieldTypeSchema `json:"fields"`
	Version      *int                       `json:"version,omitempty"`
	CreatedAt    *string                    `json:"created_at,omitempty"`
	LastModified *string                    `json:"last_modified,omitempty"`
	BypassRipple *bool                      `json:"bypass_ripple,omitempty"`
}

Schema represents a collection schema

type SchemaBuilder ΒΆ

type SchemaBuilder struct {
	// contains filtered or unexported fields
}

SchemaBuilder provides a fluent API for building collection schemas

func NewSchemaBuilder ΒΆ

func NewSchemaBuilder() *SchemaBuilder

NewSchemaBuilder creates a new SchemaBuilder

func (*SchemaBuilder) AddField ΒΆ

func (sb *SchemaBuilder) AddField(name string, field FieldTypeSchema) *SchemaBuilder

AddField adds a field to the schema

func (*SchemaBuilder) Build ΒΆ

func (sb *SchemaBuilder) Build() Schema

Build builds the final Schema

func (*SchemaBuilder) BypassRipple ΒΆ

func (sb *SchemaBuilder) BypassRipple(bypass bool) *SchemaBuilder

BypassRipple sets bypass_ripple flag

func (*SchemaBuilder) Version ΒΆ

func (sb *SchemaBuilder) Version(version int) *SchemaBuilder

Version sets schema version

type Script ΒΆ added in v0.4.0

type Script struct {
	Label       string                         `json:"label"`
	Name        string                         `json:"name"`
	Description *string                        `json:"description,omitempty"`
	Version     *string                        `json:"version,omitempty"`
	Parameters  map[string]ParameterDefinition `json:"parameters"`
	Functions   []FunctionStageConfig          `json:"functions"`
	Tags        []string                       `json:"tags,omitempty"`
	ID          *string                        `json:"id,omitempty"`
	CreatedAt   *time.Time                     `json:"created_at,omitempty"`
	UpdatedAt   *time.Time                     `json:"updated_at,omitempty"`
}

Script represents a server-side data processing script

type ScriptCondition ΒΆ added in v0.6.0

type ScriptCondition struct {
	Type       string            // Condition type (HasRecords, FieldEquals, CountEquals, And, Or, Not, etc.)
	Field      string            // Field name for field-based conditions
	FieldValue interface{}       // Expected value for comparison conditions (FieldEquals)
	Count      int               // Count threshold for count-based conditions
	Conditions []ScriptCondition // Child conditions for And/Or operators
	Condition  *ScriptCondition  // Single child condition for Not operator
}

ScriptCondition represents a conditional expression for If stages in Scripts. Conditions are evaluated against the current pipeline state (records, counts, field values) and can be composed using logical operators (And, Or, Not).

Example usage:

cond := ConditionAnd([]ScriptCondition{
	ConditionHasRecords(),
	ConditionCountGreaterThan(5),
})
StageIf(cond, thenFunctions, elseFunctions)

func ConditionAnd ΒΆ added in v0.6.0

func ConditionAnd(conditions []ScriptCondition) ScriptCondition

ConditionAnd creates a condition that requires all of the provided child conditions to be satisfied (logical AND). All conditions are evaluated and must pass.

func ConditionCountEquals ΒΆ added in v0.6.0

func ConditionCountEquals(count int) ScriptCondition

ConditionCountEquals creates a condition that is satisfied when the number of records in the current pipeline stage exactly equals the provided count.

func ConditionCountGreaterThan ΒΆ added in v0.6.0

func ConditionCountGreaterThan(count int) ScriptCondition

ConditionCountGreaterThan creates a condition that is satisfied when the number of records in the current pipeline stage is strictly greater than the provided count.

func ConditionCountLessThan ΒΆ added in v0.6.0

func ConditionCountLessThan(count int) ScriptCondition

ConditionCountLessThan creates a condition that is satisfied when the number of records in the current pipeline stage is strictly less than the provided count.

func ConditionFieldEquals ΒΆ added in v0.6.0

func ConditionFieldEquals(field string, value interface{}) ScriptCondition

ConditionFieldEquals creates a condition that is satisfied when the specified field in the current record(s) equals the provided value. Field comparison is type-aware.

func ConditionFieldExists ΒΆ added in v0.6.0

func ConditionFieldExists(field string) ScriptCondition

ConditionFieldExists creates a condition that is satisfied when the specified field exists in the current record(s), regardless of its value (including null).

func ConditionHasRecords ΒΆ added in v0.6.0

func ConditionHasRecords() ScriptCondition

ConditionHasRecords creates a condition that is satisfied when the current pipeline stage has one or more records. Useful for checking if a query returned any results.

func ConditionNot ΒΆ added in v0.6.0

func ConditionNot(condition ScriptCondition) ScriptCondition

ConditionNot creates a condition that inverts the result of the provided child condition (logical NOT). Returns true when the child condition is false.

func ConditionOr ΒΆ added in v0.6.0

func ConditionOr(conditions []ScriptCondition) ScriptCondition

ConditionOr creates a condition that is satisfied when at least one of the provided child conditions is satisfied (logical OR). Evaluation may short-circuit.

func (ScriptCondition) MarshalJSON ΒΆ added in v0.9.0

func (c ScriptCondition) MarshalJSON() ([]byte, error)

MarshalJSON implements adjacently-tagged serialization for ScriptCondition. Format: { "type": "...", "value": { ...data } } for variants with data Unit variants like HasRecords have no value field.

type SearchQuery ΒΆ

type SearchQuery struct {
	Query string `json:"query"`

	// Full-text search parameters
	Language        *string  `json:"language,omitempty"`
	CaseSensitive   *bool    `json:"case_sensitive,omitempty"`
	Fuzzy           *bool    `json:"fuzzy,omitempty"`
	MinScore        *float64 `json:"min_score,omitempty"`
	Fields          *string  `json:"fields,omitempty"`
	Weights         *string  `json:"weights,omitempty"`
	EnableStemming  *bool    `json:"enable_stemming,omitempty"`
	BoostExact      *bool    `json:"boost_exact,omitempty"`
	MaxEditDistance *int     `json:"max_edit_distance,omitempty"`

	// Vector search parameters
	Vector          []float64 `json:"vector,omitempty"`
	VectorField     *string   `json:"vector_field,omitempty"`
	VectorMetric    *string   `json:"vector_metric,omitempty"`
	VectorK         *int      `json:"vector_k,omitempty"`
	VectorThreshold *float64  `json:"vector_threshold,omitempty"`

	// Hybrid search parameters
	TextWeight   *float64 `json:"text_weight,omitempty"`
	VectorWeight *float64 `json:"vector_weight,omitempty"`

	// Performance flags
	BypassRipple *bool `json:"bypass_ripple,omitempty"`
	BypassCache  *bool `json:"bypass_cache,omitempty"`
	Limit        *int  `json:"limit,omitempty"`

	// Field projection
	SelectFields  []string `json:"select_fields,omitempty"`
	ExcludeFields []string `json:"exclude_fields,omitempty"`
}

SearchQuery represents a search query for full-text and vector search

type SearchQueryBuilder ΒΆ

type SearchQueryBuilder struct {
	// contains filtered or unexported fields
}

SearchQueryBuilder provides a fluent API for building search queries

func NewSearchQueryBuilder ΒΆ

func NewSearchQueryBuilder(queryString string) *SearchQueryBuilder

NewSearchQueryBuilder creates a new SearchQueryBuilder

func (*SearchQueryBuilder) BoostExact ΒΆ

func (sb *SearchQueryBuilder) BoostExact(enabled bool) *SearchQueryBuilder

BoostExact boosts exact matches

func (*SearchQueryBuilder) Build ΒΆ

func (sb *SearchQueryBuilder) Build() SearchQuery

Build builds the final SearchQuery

func (*SearchQueryBuilder) BypassCache ΒΆ

func (sb *SearchQueryBuilder) BypassCache(bypass bool) *SearchQueryBuilder

BypassCache bypasses cache

func (*SearchQueryBuilder) BypassRipple ΒΆ

func (sb *SearchQueryBuilder) BypassRipple(bypass bool) *SearchQueryBuilder

BypassRipple bypasses ripple cache

func (*SearchQueryBuilder) CaseSensitive ΒΆ

func (sb *SearchQueryBuilder) CaseSensitive(enabled bool) *SearchQueryBuilder

CaseSensitive enables case-sensitive search

func (*SearchQueryBuilder) EnableStemming ΒΆ

func (sb *SearchQueryBuilder) EnableStemming(enabled bool) *SearchQueryBuilder

EnableStemming enables stemming

func (*SearchQueryBuilder) ExcludeFields ΒΆ added in v0.8.0

func (sb *SearchQueryBuilder) ExcludeFields(fields []string) *SearchQueryBuilder

ExcludeFields excludes specific fields from results

func (*SearchQueryBuilder) Fields ΒΆ

func (sb *SearchQueryBuilder) Fields(fields string) *SearchQueryBuilder

Fields sets fields to search in (comma-separated)

func (*SearchQueryBuilder) Fuzzy ΒΆ

func (sb *SearchQueryBuilder) Fuzzy(enabled bool) *SearchQueryBuilder

Fuzzy enables fuzzy matching

func (*SearchQueryBuilder) Language ΒΆ

func (sb *SearchQueryBuilder) Language(language string) *SearchQueryBuilder

Language sets the language for stemming

func (*SearchQueryBuilder) Limit ΒΆ

func (sb *SearchQueryBuilder) Limit(limit int) *SearchQueryBuilder

Limit sets maximum number of results to return

func (*SearchQueryBuilder) MaxEditDistance ΒΆ

func (sb *SearchQueryBuilder) MaxEditDistance(distance int) *SearchQueryBuilder

MaxEditDistance sets maximum edit distance for fuzzy matching

func (*SearchQueryBuilder) MinScore ΒΆ

func (sb *SearchQueryBuilder) MinScore(score float64) *SearchQueryBuilder

MinScore sets minimum score threshold

func (*SearchQueryBuilder) SelectFields ΒΆ added in v0.8.0

func (sb *SearchQueryBuilder) SelectFields(fields []string) *SearchQueryBuilder

SelectFields selects specific fields to return

func (*SearchQueryBuilder) TextWeight ΒΆ

func (sb *SearchQueryBuilder) TextWeight(weight float64) *SearchQueryBuilder

TextWeight sets text search weight for hybrid search

func (*SearchQueryBuilder) Vector ΒΆ

func (sb *SearchQueryBuilder) Vector(vector []float64) *SearchQueryBuilder

Vector sets query vector for semantic search

func (*SearchQueryBuilder) VectorField ΒΆ

func (sb *SearchQueryBuilder) VectorField(field string) *SearchQueryBuilder

VectorField sets vector field name

func (*SearchQueryBuilder) VectorK ΒΆ

func (sb *SearchQueryBuilder) VectorK(k int) *SearchQueryBuilder

VectorK sets number of vector results (k-nearest neighbors)

func (*SearchQueryBuilder) VectorMetric ΒΆ

func (sb *SearchQueryBuilder) VectorMetric(metric string) *SearchQueryBuilder

VectorMetric sets vector similarity metric

func (*SearchQueryBuilder) VectorThreshold ΒΆ

func (sb *SearchQueryBuilder) VectorThreshold(threshold float64) *SearchQueryBuilder

VectorThreshold sets minimum similarity threshold

func (*SearchQueryBuilder) VectorWeight ΒΆ

func (sb *SearchQueryBuilder) VectorWeight(weight float64) *SearchQueryBuilder

VectorWeight sets vector search weight for hybrid search

func (*SearchQueryBuilder) Weights ΒΆ

func (sb *SearchQueryBuilder) Weights(weights string) *SearchQueryBuilder

Weights sets field weights (format: "field1:2.0,field2:1.5")

type SearchResponse ΒΆ

type SearchResponse struct {
	Results []SearchResult `json:"results"`
	Total   int            `json:"total"`
	TookMs  *int           `json:"took_ms,omitempty"`
}

SearchResponse represents the response from a search query

type SearchResult ΒΆ

type SearchResult struct {
	Record        map[string]interface{} `json:"record"`
	Score         float64                `json:"score"`
	MatchedFields []string               `json:"matched_fields"`
}

SearchResult represents a single search result

type SerializationFormat ΒΆ added in v0.2.0

type SerializationFormat int

SerializationFormat represents the serialization format for client-server communication

const (
	// MessagePack format (binary, 2-3x faster) - DEFAULT for best performance
	MessagePack SerializationFormat = iota
	// JSON format (human-readable, opt-in for debugging)
	JSON
)

type SortFieldConfig ΒΆ added in v0.4.0

type SortFieldConfig struct {
	Field     string `json:"field"`
	Ascending bool   `json:"ascending"`
}

SortFieldConfig for Sort stage

type SortOrder ΒΆ

type SortOrder string

SortOrder represents the sort direction

const (
	// SortAsc represents ascending sort order
	SortAsc SortOrder = "asc"
	// SortDesc represents descending sort order
	SortDesc SortOrder = "desc"
)

type StageStats ΒΆ added in v0.4.0

type StageStats struct {
	Stage           string `json:"stage"`
	InputCount      int    `json:"input_count"`
	OutputCount     int    `json:"output_count"`
	ExecutionTimeMs int64  `json:"execution_time_ms"`
}

StageStats contains statistics for a single stage

type TokenUsage ΒΆ

type TokenUsage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

TokenUsage represents token usage statistics

type UpdateAction ΒΆ added in v0.6.0

type UpdateAction string

UpdateAction represents valid actions for StageUpdateWithAction

const (
	// UpdateActionPush appends a value to an array field
	UpdateActionPush UpdateAction = "push"
	// UpdateActionPop removes the last element from an array field
	UpdateActionPop UpdateAction = "pop"
	// UpdateActionIncrement adds a numeric value to a field
	UpdateActionIncrement UpdateAction = "increment"
	// UpdateActionDecrement subtracts a numeric value from a field
	UpdateActionDecrement UpdateAction = "decrement"
	// UpdateActionRemove removes a specific value from an array field
	UpdateActionRemove UpdateAction = "remove"
)

type UpdateOptions ΒΆ added in v0.8.0

type UpdateOptions struct {
	BypassRipple  *bool
	TransactionId *string
	BypassCache   *bool
	SelectFields  []string
	ExcludeFields []string
}

UpdateOptions contains optional parameters for Update

type UpdateSessionRequest ΒΆ

type UpdateSessionRequest struct {
	SystemPrompt *string            `json:"system_prompt,omitempty"`
	LLMModel     *string            `json:"llm_model,omitempty"`
	Collections  []CollectionConfig `json:"collections,omitempty"`
	Title        *string            `json:"title,omitempty"`
}

UpdateSessionRequest represents a request to update session metadata

type UpsertOptions ΒΆ added in v0.8.0

type UpsertOptions struct {
	TTL           string
	BypassRipple  *bool
	TransactionId *string
	BypassCache   *bool
}

UpsertOptions contains optional parameters for Upsert

type VectorIndexAlgorithm ΒΆ

type VectorIndexAlgorithm string

VectorIndexAlgorithm represents the vector index algorithm

const (
	// VectorIndexFlat represents simple flat index (brute force)
	VectorIndexFlat VectorIndexAlgorithm = "flat"
	// VectorIndexHNSW represents Hierarchical Navigable Small World
	VectorIndexHNSW VectorIndexAlgorithm = "hnsw"
	// VectorIndexIVF represents Inverted File Index
	VectorIndexIVF VectorIndexAlgorithm = "ivf"
)

type WebSocketClient ΒΆ

type WebSocketClient struct {
	// contains filtered or unexported fields
}

WebSocketClient represents a WebSocket connection to ekoDB

func (*WebSocketClient) Close ΒΆ

func (ws *WebSocketClient) Close() error

Close closes the WebSocket connection

func (*WebSocketClient) FindAll ΒΆ

func (ws *WebSocketClient) FindAll(collection string) ([]Record, error)

FindAll finds all records in a collection via WebSocket

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL