concurrentmap

package module
v2.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 7 Imported by: 0

README

gopher223

ConcurrentOrderedMap v2.0.3

Go Reference MIT License

ConcurrentOrderedMap provides a thread-safe map implementation that preserves insertion order. It combines the safety of synchronized access with predictable iteration order, making it suitable for concurrent environments where key ordering matters.


Install

go get github.com/Dsouza10082/ConcurrentOrderedMap@v2.0.2

Use cases

  • Concurrent access patterns with deterministic iteration requirements
  • Scenarios requiring both thread-safety and insertion order guarantees
  • Replacing sync.Map when ordered traversal is needed
  • Singleton for database connections
  • String similarity search (direct from the dependency) for machine learning
  • Vector search using BGE-M3 and text-embedding-3-large embedding types (1024 dimensions)
  • Knowledge graphs for autonomous agents and agentic memory systems (new)
  • Persistent durable storage with semantic vector search (new)
  • Agents creation with zero dependency
  • Objects Pool

Contents


ConcurrentOrderedMap API Documentation

Methods
GetOrderedV2

Returns a slice of OrderedPair[K, V] containing the map's key-value pairs in insertion order.

m := NewConcurrentOrderedMap[string, int]()
m.Set("a", 1)
m.Set("b", 2)
pairs := m.GetOrderedV2()
fmt.Println(pairs) // [{a 1} {b 2}]
Constructors
NewConcurrentOrderedMap
m := NewConcurrentOrderedMap[string, int]()
NewConcurrentOrderedMapWithCapacity
m := NewConcurrentOrderedMapWithCapacity[string, int](10)
Query Methods
Exists
exists := m.Exists("a") // true/false
Get
value, exists := m.Get("a")
Modification Methods
Set
m.Set("a", 1)
Update / UpdateWithPointer
m.Update("a", func(v *int) error { *v = 2; return nil })
Delete
m.Delete("b")
Utility Methods
Len
fmt.Println(m.Len()) // 3

Similarity & Search Extensions

String-based (for V == string)
Method Algorithm
OrderedByLevenshteinDistance Edit distance
OrderedByDamerauLevenshteinDistance Edit distance + transpositions
OrderedByJaroWinklerSimilarity Jaro-Winkler (0-1)
OrderedByCosineTFIDF Token cosine (TF-IDF)
OrderedBySoundex Phonetic similarity
OrderedByJaccardNGrams Jaccard trigrams
OrderedByCombinedSimilarity Blend of all above

All methods have a ...Filtered(target, caseInsensitive, filter) variant.

Vector + Text Blend (1024-dim BGE-M3 / OpenAI)
w := co.DefaultVectorBlendWeights()
pairs, err := m.OrderedByVectorCombinedSimilarity(
    "developer python", true, queryVec, 1024, co.MapExtractor, &w,
)

Graph — Knowledge Graph & Agent Memory

The graph package provides a thread-safe, ordered directed/undirected graph built on top of ConcurrentOrderedMap. Each node can carry an arbitrary payload and an optional embedding vector, enabling graph traversal combined with semantic vector search.

This is the core primitive needed for:

  • Autonomous agent memory systems
  • RAG pipelines with relational context
  • Knowledge graphs for reasoning chains
  • Multi-step tool-call history with semantic retrieval
Quick start
import "github.com/Dsouza10082/ConcurrentOrderedMap/graph"

type Memory struct {
    Content   string
    Category  string
}

g := graph.NewDirectedGraph[string, Memory]()

// Add nodes with embedding vectors
g.AddNode("obs-001", Memory{"User asked about Paris", "observation"}, embed("User asked about Paris"))
g.AddNode("obs-002", Memory{"Paris is the capital of France", "fact"}, embed("Paris capital France"))
g.AddNode("act-001", Memory{"Called Wikipedia API", "action"}, embed("Wikipedia API call"))

// Connect related nodes
g.AddEdge("obs-001", "act-001", graph.EdgeData{Label: "triggered", Weight: 1.0})
g.AddEdge("act-001", "obs-002", graph.EdgeData{Label: "produced",  Weight: 1.0})
Vector Search from a Node (context-aware retrieval)
// "What do I know about France, starting from this observation?"
results, err := g.VectorSearchFromNode(
    "obs-001",          // anchor node (start BFS here)
    queryVec,           // embedding of the query
    5,                  // topK results
    3,                  // maxHops (BFS depth limit)
    nil,                // optional filter func(Memory) bool
)
for _, r := range results {
    fmt.Printf("score=%.4f  %q\n", r.Score, r.Node.Data.Content)
}
results, _ := g.VectorSearchGlobal(queryVec, 5, func(m Memory) bool {
    return m.Category == "fact" // only search facts
})
// Expands both forward and backward edges — retrieves parents, children, and siblings
results, _ := g.VectorSearchBidirectional("obs-001", queryVec, 5, 2, nil)
Shortest Path (Dijkstra)
// Find the reasoning chain between two memories
result, err := g.ShortestPath("obs-001", "obs-002")
fmt.Println(result.Nodes)    // ["obs-001", "act-001", "obs-002"]
fmt.Println(result.Distance) // 2.0
BFS / DFS Traversal
// BFS with depth limit — ideal for "context within N hops"
g.BFSWithDepth("obs-001", 2, func(id string, data Memory, depth int) bool {
    fmt.Printf("depth=%d  %s: %q\n", depth, id, data.Content)
    return true // return false to stop early
})

// Standard DFS
g.DFS("obs-001", func(id string, data Memory) bool {
    fmt.Println(id, data.Content)
    return true
})
Connected Components
// Detect isolated sub-graphs (useful for finding orphan memories)
components := g.ConnectedComponents()
fmt.Printf("%d connected components\n", len(components))
Full Graph API
// Nodes
g.AddNode(id, data, vec)
g.UpsertNode(id, data, vec)   // add or replace
g.GetNode(id)                 // (*GraphNode, bool)
g.RemoveNode(id)
g.NodeCount()
g.Nodes()                     // all nodes in insertion order

// Edges
g.AddEdge(from, to, EdgeData{Weight, Label, Metadata})
g.RemoveEdge(from, to)
g.GetNeighbors(id)            // []K in insertion order
g.HasEdge(from, to)

// Traversal
g.BFS(start, visitor)
g.BFSWithDepth(start, maxDepth, visitor)
g.DFS(start, visitor)
g.ShortestPath(from, to)      // PathResult{Nodes, Distance}
g.AllReachable(start)         // []K
g.ConnectedComponents()       // [][]K

// Vector Search
g.VectorSearchGlobal(queryVec, topK, filter)
g.VectorSearchFromNode(start, queryVec, topK, maxHops, filter)
g.VectorSearchBidirectional(start, queryVec, topK, maxHops, filter)
g.SemanticNeighbors(nodeID, queryVec, topK)  // 1-hop only

The persistence package wraps ConcurrentOrderedMap with crash-safe durability using a Write-Ahead Log (WAL) + periodic binary snapshots. It also includes a FlatVectorIndex for in-memory semantic search over persisted values.

Zero external dependencies — 100% Go stdlib (os, encoding/gob, bufio, sync).

How it works
Write path:   Set(key, value) → WAL append (O(1)) → in-memory map update
              Snapshot()      → gob encode all entries → atomic file rename → WAL truncate

Read path:    Open(dir) → load latest snapshot → replay WAL entries after snapshot seq
              Get(key)  → O(1) from in-memory map
              Search()  → cosine similarity over FlatVectorIndex (in-memory, O(n))
Quick start
import "github.com/Dsouza10082/ConcurrentOrderedMap/persistence"

opts := persistence.DefaultOptions()
opts.VectorDims = 1024 // set to your embedding dimensions; 0 = no vector index

store, err := persistence.New[string, MyStruct]("/data/my-agent", opts)
if err != nil { panic(err) }
defer store.Close() // flushes + writes final snapshot

// Store with optional embedding vector
store.SetWithVector("key1", MyStruct{...}, embeddingVector)

// Plain store (no vector)
store.Set("key2", MyStruct{...})

// Retrieve
val, ok := store.Get("key1")

// Semantic search over persisted vectors
results, err := store.VectorSearch(queryVec, 5, nil)
for _, r := range results {
    val, _ := store.Get(r.Key)
    fmt.Printf("score=%.4f  %+v\n", r.Score, val)
}

// Manual snapshot (also happens automatically per SnapshotInterval)
store.Snapshot()
Options
type Options struct {
    SnapshotInterval time.Duration // auto-snapshot period (0 = disable)
    MaxWALEntries    int           // compact after N entries (0 = disable)
    SyncOnWrite      bool          // fdatasync on every write (slower, safer)
    VectorDims       int           // embedding dims; 0 = no vector index
}

// Defaults: 5min snapshot, 100k WAL entries, no fsync, no vector index
opts := persistence.DefaultOptions()
FlatVectorIndex (standalone)

You can also use the vector index directly, independent of the persistent map:

idx := persistence.NewFlatVectorIndex[string](1024)

idx.Upsert("doc-001", vector1)
idx.Upsert("doc-002", vector2)
idx.Delete("doc-001")

results, _ := idx.Search(queryVec, 5, func(key string) bool {
    return strings.HasPrefix(key, "doc-")
})

Agentic Examples

Example 1 — Autonomous Agent with Knowledge Graph Memory

Located at examples/agentic-knowledge-graph/main.go

Demonstrates a MemoryAgent that:

  • Stores observations, actions, and derived facts as graph nodes
  • Auto-links related nodes by semantic similarity
  • Retrieves relevant context before each action (VectorSearchFromNode)
  • Traces reasoning chains between memories (ShortestPath)
  • Detects isolated memory clusters (ConnectedComponents)
cd examples/agentic-knowledge-graph
go run main.go

Key pattern:

agent := NewMemoryAgent(myEmbedFn)

// Agent observes environment
obs1 := agent.Observe("User asked: What is the capital of France?", "user_input", nil)
obs2 := agent.Observe("Wikipedia: Paris is the capital", "wiki_tool", nil)

// Agent acts
agent.Act("Called Wikipedia API", obs1)

// Agent derives a fact
agent.StoreFact("Paris is the capital of France", []string{obs1, obs2})

// Before next action: retrieve context within 3 hops of current node
ctx := agent.QueryContext("France capital city", obs1, topK=5, maxHops=3)
Example 2 — Persistent Memory Agent

Located at examples/agentic-memory-agent/main.go

Demonstrates persistence + graph working together:

  • Every memory is persisted to disk via WAL
  • On restart, the agent loads all memories and rebuilds the graph
  • Vector search works across both in-memory graph and persisted store
cd examples/agentic-memory-agent
go run main.go   # first run: stores memories
go run main.go   # second run: loads from disk, shows they're still there
Example 3 — Basic Persistence

Located at examples/persistence-basic/main.go

Minimal example showing Set, SetWithVector, VectorSearch, and Snapshot.

cd examples/persistence-basic
go run main.go
Connecting to a real embedding provider

Replace the mockEmbed function in examples with a real API call:

// Ollama (local, BGE-M3)
func embed(text string) []float64 {
    body := `{"model":"bge-m3","input":"` + text + `"}`
    resp, _ := http.Post("http://localhost:11434/api/embed", "application/json", strings.NewReader(body))
    var result struct { Embeddings [][]float64 }
    json.NewDecoder(resp.Body).Decode(&result)
    return result.Embeddings[0]
}

// OpenAI text-embedding-3-large (1024 dims)
func embed(text string) []float64 {
    client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
    resp, _ := client.CreateEmbedding(ctx, &openai.EmbeddingRequest{
        Model: "text-embedding-3-large",
        Input: []string{text},
        Dimensions: 1024,
    })
    return resp.Data[0].Embedding
}

Running Tests & Benchmarks

Requirements
  • Go 1.20+ (generics; 1.18+ works, 1.20+ recommended)
Run all tests
go test ./...
Benchmarks — string similarities
# default dataset size (10 000 items)
go test -bench=Filtered_ -benchmem ./...

# larger dataset
SIM_BENCH_ITEMS=200000 go test -bench=Filtered_ -benchmem ./...
Benchmarks — vector similarities (1024-d)
go test -bench=Vector -benchmem ./...

SIM_BENCH_VEC_ITEMS=200000 go test -bench=Vector -benchmem ./...

Author: Dsouza

License: MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConcurrentOrderedMap

type ConcurrentOrderedMap[K comparable, V any] struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewConcurrentOrderedMap

func NewConcurrentOrderedMap[K comparable, V any]() *ConcurrentOrderedMap[K, V]

NewConcurrentOrderedMap creates a new ConcurrentOrderedMap with the given key and value types It initializes the map with empty data and ensures thread-safety for concurrent operations

Returns:

  • A pointer to a new ConcurrentOrderedMap[K, V] instance

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
pairs := map.GetOrderedV2()
fmt.Println(pairs) // Output: [{a 1} {b 2} {c 3}]

func NewConcurrentOrderedMapWithCapacity

func NewConcurrentOrderedMapWithCapacity[K comparable, V any](initialCapacity ...int) *ConcurrentOrderedMap[K, V]

NewConcurrentOrderedMapWithCapacity creates a new ConcurrentOrderedMap with the given key and value types It initializes the map with empty data and ensures thread-safety for concurrent operations

Returns:

  • A pointer to a new ConcurrentOrderedMap[K, V] instance

Example:

map := NewConcurrentOrderedMapWithCapacity[string, int](10)
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
pairs := map.GetOrderedV2()
fmt.Println(pairs) // Output: [{a 1} {b 2} {c 3}]

func (*ConcurrentOrderedMap[K, V]) Clear

func (m *ConcurrentOrderedMap[K, V]) Clear()

Clear removes all key-value pairs from the map

Returns:

  • The map itself

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
map.Clear()
fmt.Println(map) // Output: {}

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) Delete

func (m *ConcurrentOrderedMap[K, V]) Delete(key K)

Delete removes a key-value pair from the map

Returns:

  • The map itself

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
map.Delete("b")
fmt.Println(map) // Output: {a: 1, c: 3}

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) Exists

func (m *ConcurrentOrderedMap[K, V]) Exists(key K) bool

Exists checks if a key exists in the map

Returns:

  • true if the key exists, false otherwise

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
exists := map.Exists("a")
fmt.Println(exists) // Output: true

Note:

  • The map is locked for reading during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) Get

func (m *ConcurrentOrderedMap[K, V]) Get(key K) (V, bool)

Get retrieves a value from the map by key

Returns:

  • The value associated with the key, and a boolean indicating if the key exists
  • The boolean is true if the key exists, false otherwise

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
value, exists := map.Get("a")
fmt.Println(value, exists) // Output: 1 true

Note:

  • The map is locked for reading during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) GetOrdered

func (m *ConcurrentOrderedMap[K, V]) GetOrdered() []struct {
	Key   K
	Value V
}

GetOrdered returns a slice of key-value pairs in the order of insertion

Returns:

  • A slice of key-value pairs in the order of insertion

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
pairs := map.GetOrdered()
fmt.Println(pairs) // Output: [{a 1} {b 2} {c 3}]

Note:

  • The map is locked for reading during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) GetOrderedByField

func (m *ConcurrentOrderedMap[K, V]) GetOrderedByField(orderBy OrderBy) ([]OrderedPair[K, V], error)

GetOrderedByField returns a slice of key-value pairs in the order of insertion

Returns:

  • A slice of key-value pairs in the order of insertion

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
pairs := map.GetOrderedByField(OrderBy{Field: "a", Direction: ASC})
fmt.Println(pairs) // Output: [{a 1} {b 2} {c 3}]

Note:

  • The map is locked for reading during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) GetOrderedByMultiField

func (m *ConcurrentOrderedMap[K, V]) GetOrderedByMultiField(orderBy []OrderBy) ([]OrderedPair[K, V], error)

GetOrderedByMultiField returns a slice of key-value pairs in the order of insertion

Returns:

  • A slice of key-value pairs in the order of insertion

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
pairs := map.GetOrderedByMultiField([]OrderBy{OrderBy{Field: "a", Direction: ASC}, OrderBy{Field: "b", Direction: DESC}})
fmt.Println(pairs) // Output: [{a 1} {b 2} {c 3}]

Note:

  • The map is locked for reading during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) GetOrderedV2

func (m *ConcurrentOrderedMap[K, V]) GetOrderedV2() []OrderedPair[K, V]

GetOrderedV2 is a method that returns a slice of OrderedPair[K, V] It locks the map for reading and returns a copy of the map's data in the order of insertion.

Returns:

  • A slice of OrderedPair[K, V] containing the key-value pairs in insertion order

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
pairs := map.GetOrderedV2()
fmt.Println(pairs) // Output: [{a 1} {b 2} {c 3}]

Note:

  • The returned slice is a copy of the map's data and is safe for concurrent use
  • The map is locked for reading during the operation, ensuring thread-safety
  • The order of the pairs is guaranteed to be the same as the order of insertion

func (*ConcurrentOrderedMap[K, V]) Keys

func (m *ConcurrentOrderedMap[K, V]) Keys() []K

Keys returns a copy of the keys in the map

Returns:

  • A slice of keys in the map

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
keys := map.Keys()
fmt.Println(keys) // Output: [a b c]

Note:

  • The map is locked for reading during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) Len

func (m *ConcurrentOrderedMap[K, V]) Len() int

Len returns the number of key-value pairs in the map

Returns:

  • The number of key-value pairs in the map

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
fmt.Println(map.Len()) // Output: 3

Note:

  • The map is locked for reading during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) OrderedByCombinedSimilarity

func (m *ConcurrentOrderedMap[K, V]) OrderedByCombinedSimilarity(
	target string,
	caseInsensitive bool,
) ([]OrderedPair[K, V], error)

OrderedByCombinedSimilarity orders by a weighted blend of multiple similarity metrics:

  • Levenshtein (normalized as similarity)
  • Damerau–Levenshtein OSA (normalized as similarity)
  • Jaro–Winkler
  • Cosine TF–IDF (computed over target + filtered documents)
  • Soundex (phonetic)
  • Jaccard N-grams (trigrams)

Higher combined score is better. Stable on ties. Requires V == string.

func (*ConcurrentOrderedMap[K, V]) OrderedByCombinedSimilarityFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedByCombinedSimilarityFiltered(
	target string,
	caseInsensitive bool,
	filter string,
) ([]OrderedPair[K, V], error)

OrderedByCombinedSimilarityFiltered: same as above but keeps only values that contain `filter` (respects caseInsensitive) before scoring.

func (*ConcurrentOrderedMap[K, V]) OrderedByCosineTFIDF

func (m *ConcurrentOrderedMap[K, V]) OrderedByCosineTFIDF(
	target string,
	caseInsensitive bool,
) ([]OrderedPair[K, V], error)

Public: Cosine TF-IDF

func (*ConcurrentOrderedMap[K, V]) OrderedByCosineTFIDFFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedByCosineTFIDFFiltered(
	target string,
	caseInsensitive bool,
	filter string,
) ([]OrderedPair[K, V], error)

func (*ConcurrentOrderedMap[K, V]) OrderedByDamerauLevenshteinDistance

func (m *ConcurrentOrderedMap[K, V]) OrderedByDamerauLevenshteinDistance(
	target string,
	caseInsensitive bool,
) ([]OrderedPair[K, V], error)

Public: Damerau–Levenshtein (OSA; adjacent transpositions)

func (*ConcurrentOrderedMap[K, V]) OrderedByDamerauLevenshteinDistanceFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedByDamerauLevenshteinDistanceFiltered(
	target string,
	caseInsensitive bool,
	filter string,
) ([]OrderedPair[K, V], error)

Public: Damerau–Levenshtein with substring filter

func (*ConcurrentOrderedMap[K, V]) OrderedByJaccardNGrams

func (m *ConcurrentOrderedMap[K, V]) OrderedByJaccardNGrams(
	target string,
	caseInsensitive bool,
) ([]OrderedPair[K, V], error)

Public: Jaccard on character trigrams (n=3). Higher is better in [0,1].

func (*ConcurrentOrderedMap[K, V]) OrderedByJaccardNGramsFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedByJaccardNGramsFiltered(
	target string,
	caseInsensitive bool,
	filter string,
) ([]OrderedPair[K, V], error)

func (*ConcurrentOrderedMap[K, V]) OrderedByJaroWinklerSimilarity

func (m *ConcurrentOrderedMap[K, V]) OrderedByJaroWinklerSimilarity(
	target string,
	caseInsensitive bool,
) ([]OrderedPair[K, V], error)

Public: Jaro–Winkler (higher is better)

func (*ConcurrentOrderedMap[K, V]) OrderedByJaroWinklerSimilarityFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedByJaroWinklerSimilarityFiltered(
	target string,
	caseInsensitive bool,
	filter string,
) ([]OrderedPair[K, V], error)

func (*ConcurrentOrderedMap[K, V]) OrderedByLevenshteinDistance

func (m *ConcurrentOrderedMap[K, V]) OrderedByLevenshteinDistance(
	target string,
	caseInsensitive bool,
) ([]OrderedPair[K, V], error)

Public: Levenshtein (no filter)

func (*ConcurrentOrderedMap[K, V]) OrderedByLevenshteinDistanceFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedByLevenshteinDistanceFiltered(
	target string,
	caseInsensitive bool,
	filter string,
) ([]OrderedPair[K, V], error)

Public: Levenshtein with substring filter

func (*ConcurrentOrderedMap[K, V]) OrderedBySoundex

func (m *ConcurrentOrderedMap[K, V]) OrderedBySoundex(
	target string,
	caseInsensitive bool,
) ([]OrderedPair[K, V], error)

Public: Soundex-based ordering (higher is better). Score = 1.0 if Soundex codes equal, else common-prefix(codeA, codeB)/4.0.

func (*ConcurrentOrderedMap[K, V]) OrderedBySoundexFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedBySoundexFiltered(
	target string,
	caseInsensitive bool,
	filter string,
) ([]OrderedPair[K, V], error)

func (*ConcurrentOrderedMap[K, V]) OrderedByVectorCombinedSimilarity

func (m *ConcurrentOrderedMap[K, V]) OrderedByVectorCombinedSimilarity(
	target string,
	caseInsensitive bool,
	queryVec []float64,
	dims int,
	extract VectorTextExtractor[V],
	weights *VectorBlendWeights,
) ([]OrderedPair[K, V], error)

OrderedByVectorCombinedSimilarity ranks by a weighted blend of:

  • cosine(queryVec, itemVec)
  • Levenshtein (norm), Damerau–Levenshtein (norm), Jaro–Winkler,
  • Cosine TF–IDF (over text), Jaccard n-grams, Soundex.

No substring filter.

func (*ConcurrentOrderedMap[K, V]) OrderedByVectorCombinedSimilarityFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedByVectorCombinedSimilarityFiltered(
	target string,
	caseInsensitive bool,
	filter string,
	queryVec []float64,
	dims int,
	extract VectorTextExtractor[V],
	weights *VectorBlendWeights,
) ([]OrderedPair[K, V], error)

OrderedByVectorCombinedSimilarityFiltered same as above but keeps only items whose TEXT contains 'filter' (respects caseInsensitive) before scoring.

func (*ConcurrentOrderedMap[K, V]) OrderedByVectorOnlyFiltered

func (m *ConcurrentOrderedMap[K, V]) OrderedByVectorOnlyFiltered(
	caseInsensitive bool,
	filter string,
	queryVec []float64,
	dims int,
	extract VectorTextExtractor[V],
) ([]OrderedPair[K, V], error)

Pure vector-only ordering (handy for benchmarks/comparison). Filtered.

func (*ConcurrentOrderedMap[K, V]) Set

func (m *ConcurrentOrderedMap[K, V]) Set(key K, value V)

Set adds a new key-value pair to the map

Returns:

  • The map itself

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
fmt.Println(map) // Output: {a: 1, b: 2, c: 3}

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) SetOrUpdate

func (m *ConcurrentOrderedMap[K, V]) SetOrUpdate(key K, value V, updateIfExists func(*V) V)

SetOrUpdate sets a value in the map if the key does not exist, otherwise it updates the value

Returns:

  • The map itself

Example:

map := NewConcurrentOrderedMap[string, int]()
map.SetOrUpdate("a", 1, func(current *int) *int {
  *current = 2
  return current
})
fmt.Println(map) // Output: {a: 2}

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) Update

func (m *ConcurrentOrderedMap[K, V]) Update(key K, updateFunc func(*V) error) error

Update updates a value in the map by key using a function

Returns:

  • An error if the update fails

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
err := map.Update("a", func(v *int) error {
  *v = 2
  return nil
})
fmt.Println(err) // Output: nil

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) UpdateGeneric

func (m *ConcurrentOrderedMap[K, V]) UpdateGeneric(key K, operation UpdateOperation[V]) error

UpdateGeneric updates a value in the map by key using a generic operation

Returns:

  • An error if the update fails

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
err := map.UpdateGeneric("a", DirectUpdate{NewValue: 2})
fmt.Println(err) // Output: nil

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) UpdateWithPointer

func (m *ConcurrentOrderedMap[K, V]) UpdateWithPointer(key K, updatePointerFunc func(*V) error) error

UpdateWithPointer updates a value in the map by key using a pointer function

Returns:

  • An error if the update fails

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
err := map.UpdateWithPointer("a", func(v *int) error {
  *v = 2
  return nil
})
fmt.Println(err) // Output: nil

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (*ConcurrentOrderedMap[K, V]) Values

func (m *ConcurrentOrderedMap[K, V]) Values() []V

Values returns a copy of the values in the map

Returns:

  • A slice of values in the map

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
map.Set("b", 2)
map.Set("c", 3)
values := map.Values()
fmt.Println(values) // Output: [1 2 3]

Note:

  • The map is locked for reading during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

type DirectUpdate

type DirectUpdate[V any] struct {
	NewValue V
}

func (DirectUpdate[V]) Apply

func (u DirectUpdate[V]) Apply(current V) (V, error)

type FieldUpdate

type FieldUpdate[V any] struct {
	Fields map[string]interface{}
}

FieldUpdate is a struct that contains a map of fields to update in the map

Returns:

  • An error if the update fails

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
err := map.UpdateGeneric("a", FieldUpdate{Fields: map[string]interface{}{"a": 2}})
fmt.Println(err) // Output: nil

Note:

  • The map is locked for writing during the operation, ensuring thread-safety

func (FieldUpdate[V]) Apply

func (u FieldUpdate[V]) Apply(current V) (V, error)

Apply is a method that applies the update function to the current value

Returns:

  • The updated value and an error if the update fails

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
updated, err := map.UpdateGeneric("a", FieldUpdate{Fields: map[string]interface{}{"a": 2}})
fmt.Println(updated, err) // Output: 2 nil

Note:

  • The map is locked for writing during the operation, ensuring thread-safety

type FunctionUpdate

type FunctionUpdate[V any] struct {
	UpdateFunc func(current *V) error
}

FunctionUpdate is a struct that contains a function to update a value in the map

Returns:

  • An error if the update fails

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
err := map.UpdateGeneric("a", FunctionUpdate{UpdateFunc: func(current *int) error {
  *current = 2
  return nil
}})
fmt.Println(err) // Output: nil

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

func (FunctionUpdate[V]) Apply

func (u FunctionUpdate[V]) Apply(current V) (V, error)

Apply is a method that applies the update function to the current value

Returns:

  • The updated value and an error if the update fails

Example:

map := NewConcurrentOrderedMap[string, int]()
map.Set("a", 1)
updated, err := map.UpdateGeneric("a", FunctionUpdate{UpdateFunc: func(current *int) error {
  *current = 2
  return nil
}})
fmt.Println(updated, err) // Output: 2 nil

Note:

  • The map is locked for writing during the operation, ensuring thread-safety
  • The operation is thread-safe and can be used concurrently by multiple goroutines

type OrderBy

type OrderBy struct {
	Field     string
	Direction OrderDirection
}

type OrderDirection

type OrderDirection int
const (
	ASC OrderDirection = iota
	DESC
)

type OrderedPair

type OrderedPair[K comparable, V any] struct {
	Key   K
	Value V
}

type UpdateOperation

type UpdateOperation[V any] interface {
	Apply(current V) (V, error)
}

type VectorBlendWeights

type VectorBlendWeights struct {
	WVec   float64 // vector cosine similarity
	WLev   float64 // Levenshtein (normalized)
	WDL    float64 // Damerau–Levenshtein (OSA; normalized)
	WJW    float64 // Jaro–Winkler
	WCos   float64 // Cosine TF-IDF (over text)
	WJac   float64 // Jaccard n-grams (char)
	WSdx   float64 // Soundex score
	NGramN int     // default 3
}

func DefaultVectorBlendWeights

func DefaultVectorBlendWeights() VectorBlendWeights

Defaults tuned to give vectors strong influence while keeping textual checks meaningful.

type VectorTextExtractor

type VectorTextExtractor[V any] func(v V) (text string, vec []float64, ok bool)

Extractor lets you describe where text and vector live inside your value.

Directories

Path Synopsis
examples
agentic-knowledge-graph command
Example: Autonomous Agent with Knowledge Graph Memory
Example: Autonomous Agent with Knowledge Graph Memory
agentic-memory-agent command
Example: Persistent Agent Memory
Example: Persistent Agent Memory
persistence-basic command
Example: Basic Persistent Map
Example: Basic Persistent Map
Package graph provides a thread-safe, ordered directed/undirected graph built on top of ConcurrentOrderedMap.
Package graph provides a thread-safe, ordered directed/undirected graph built on top of ConcurrentOrderedMap.
Package persistence adds durable storage to ConcurrentOrderedMap.
Package persistence adds durable storage to ConcurrentOrderedMap.

Jump to

Keyboard shortcuts

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