ekodb

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2025 License: MIT Imports: 10 Imported by: 0

README

ekoDB Go Client

Official Go client library for ekoDB.

Installation

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

Usage

Basic Usage (Backward Compatible)
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 Usage with 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

See the examples directory for complete working examples:

  • client_simple_crud.go - Basic CRUD operations
  • client_query_builder.go - Complex queries with QueryBuilder
  • client_search.go - Full-text search operations
  • client_schema.go - Schema management
  • client_joins.go - Join operations
  • client_batch_operations.go - Batch operations
  • client_kv_operations.go - Key-value operations
  • And more...

License

MIT

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 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 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) (int, error)

BatchDelete deletes multiple documents

func (*Client) BatchInsert

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

BatchInsert inserts multiple documents

func (*Client) BatchUpdate

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

BatchUpdate updates multiple documents

func (*Client) BranchChatSession

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

BranchChatSession branches a chat session

func (*Client) ChatMessage

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

ChatMessage sends a message in an existing chat session

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) 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) Find

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

Find finds documents in a collection

func (*Client) FindByID

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

FindByID finds a document by ID

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) Insert

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

Insert inserts a document into a collection

func (*Client) IsNearRateLimit

func (c *Client) IsNearRateLimit() bool

IsNearRateLimit checks if approaching rate limit

func (*Client) KVDelete

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

KVDelete deletes a key

func (*Client) KVGet

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

KVGet gets a value by key

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) MergeChatSessions

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

MergeChatSessions merges multiple chat sessions into one

func (*Client) RegenerateChatMessage

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

RegenerateChatMessage regenerates an AI response message

func (*Client) Search

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

Search performs a search query on a collection

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) (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) 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)
}

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 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 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 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 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 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)

func (*QueryBuilder) Gt

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

Gt adds a greater-than filter ($gt)

func (*QueryBuilder) Gte

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

Gte adds a greater-than-or-equal filter ($gte)

func (*QueryBuilder) In

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

In adds an in-array filter ($in)

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)

func (*QueryBuilder) Lte

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

Lte adds a less-than-or-equal filter ($lte)

func (*QueryBuilder) Ne

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

Ne adds a not-equal filter ($ne)

func (*QueryBuilder) Nin

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

Nin adds a not-in-array filter ($nin)

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) 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 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"`
}

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) 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) 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 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 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 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 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