Files
elowdb-go/examples/custom-serializer/main.go
2026-04-07 15:04:38 +06:00

75 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Пример использования KeyOrder в опциях коллекции — встроенная сортировка ключей при сериализации.
package main
import (
"fmt"
"log"
"os"
"time"
"direct-dev.ru/gitea/GiteaAdmin/elowdb-go/pkg/linedb"
)
// Item — структура для вставки (LineDB поддерживает struct и map)
type Item struct {
Name string `json:"name"`
Value int `json:"value"`
Active bool `json:"active"`
Atime string `json:"atime"`
}
func main() {
os.RemoveAll("./data")
// KeyOrder в опциях коллекции — при задании используется кастомная сериализация с порядком ключей
initOptions := &linedb.LineDbInitOptions{
CacheSize: 100,
CacheTTL: time.Minute,
DBFolder: "./data",
Collections: []linedb.JSONLFileOptions{
{
CollectionName: "items",
AllocSize: 256,
KeyOrder: []linedb.KeyOrder{
{Key: "id", Order: 0},
{Key: "atime", Order: -1},
},
},
},
}
db := linedb.NewLineDb(nil)
if err := db.Init(false, initOptions); err != nil {
log.Fatalf("Init failed: %v", err)
}
defer db.Close()
opts := linedb.LineDbAdapterOptions{}
// Инсерты: map и структуры (LineDB принимает оба)
items := []any{
map[string]any{"Value": 42, "Name": "Test", "Active": true, "atime": "2024-01-01"},
map[string]any{"Active": false, "Name": "Alice", "Value": 100, "atime": "2024-01-02"},
map[string]any{"Name": "Bob", "Value": 0, "Active": true, "atime": "2024-01-03"},
Item{Name: "Charlie", Value: 7, Active: true, Atime: "2024-01-04"},
Item{Name: "Diana", Value: 99, Active: false, Atime: "2024-01-05"},
}
if err := db.Insert(items, "items", opts); err != nil {
log.Fatalf("Insert failed: %v", err)
}
// Read
all, err := db.Read("items", opts)
if err != nil {
log.Fatalf("Read failed: %v", err)
}
fmt.Printf("Records: %d\n", len(all))
for _, r := range all {
fmt.Printf(" %+v\n", r)
}
raw, _ := os.ReadFile("./data/items.jsonl")
fmt.Printf("\nRaw file:\n%s\n", string(raw))
}