concurrentmap

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2025 License: MIT Imports: 7 Imported by: 2

README

gopher_doing_multiple_things_strong

ConcurrentOrderedMap

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

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) for machine learning
  • Agents creation with zero dependency
  • Objects Pool

Thread-safety:

All operations are safe for concurrent use by multiple goroutines.

ConcurrentOrderedMap API Documentation

Methods

GetOrderedV2

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

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

Constructors

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}]

NewConcurrentOrderedMapWithCapacity

Creates a new ConcurrentOrderedMap with the given key and value types and initial capacity. 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}]

Query Methods

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

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

Modification Methods

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

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

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

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

Utility Methods

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

Author: Dsouza

License: MIT


Similarity & Search Extensions

This library now includes a rich set of string similarity and vector similarity order/filter helpers that work on top of ConcurrentOrderedMap. These helpers keep the core guarantees (thread-safety + deterministic/stable ordering) while letting you rank results by how close they are to a target query.

The features are provided as non-breaking additions—use only what you need.

Quick Summary

String-based (for V == string):

  • Levenshtein
    • OrderedByLevenshteinDistance(target string, caseInsensitive bool)
    • OrderedByLevenshteinDistanceFiltered(target string, caseInsensitive bool, filter string)
  • Damerau–Levenshtein (OSA; adjacent transpositions)
    • OrderedByDamerauLevenshteinDistance(target string, caseInsensitive bool)
    • OrderedByDamerauLevenshteinDistanceFiltered(target string, caseInsensitive bool, filter string)
  • Jaro–Winkler (similarity in [0,1], higher is better)
    • OrderedByJaroWinklerSimilarity(target string, caseInsensitive bool)
    • OrderedByJaroWinklerSimilarityFiltered(target string, caseInsensitive bool, filter string)
  • Cosine (TF–IDF) over tokens
    • OrderedByCosineTFIDF(target string, caseInsensitive bool)
    • OrderedByCosineTFIDFFiltered(target string, caseInsensitive bool, filter string)
  • Soundex (phonetic similarity)
    • OrderedBySoundex(target string, caseInsensitive bool)
    • OrderedBySoundexFiltered(target string, caseInsensitive bool, filter string)
  • N-grams with Jaccard (default n=3; score in [0,1])
    • OrderedByJaccardNGrams(target string, caseInsensitive bool)
    • OrderedByJaccardNGramsFiltered(target string, caseInsensitive bool, filter string)

Blended text similarity:

  • Combine the above metrics for stronger ranking:
    • OrderedByCombinedSimilarity(target string, caseInsensitive bool)
    • OrderedByCombinedSimilarityFiltered(target string, caseInsensitive bool, filter string)

Vector + Text blended (supports 1024-dim embeddings like BGE-M3 and OpenAI text-embedding-3-large 1024):

  • Highly configurable blend between vector cosine and all string metrics:
    • OrderedByVectorCombinedSimilarity(target string, caseInsensitive bool, queryVec []float64, dims int, extract VectorTextExtractor[V], weights *VectorBlendWeights)
    • OrderedByVectorCombinedSimilarityFiltered(target string, caseInsensitive bool, filter string, queryVec []float64, dims int, extract VectorTextExtractor[V], weights *VectorBlendWeights)
  • Pure vector-only ordering (helpful for baseline comparisons):
    • OrderedByVectorOnlyFiltered(caseInsensitive bool, filter string, queryVec []float64, dims int, extract VectorTextExtractor[V])
Notes
  • All string similarity functions require V to be string.
  • The filtered variants include only entries whose value’s text contains the filter substring (respects caseInsensitive) before ranking.
  • Ordering is stable: ties preserve insertion order.

Usage — String Similarities

package main

import (
    "fmt"
    co "github.com/Dsouza10082/ConcurrentOrderedMap"
)

func main() {
    m := co.NewConcurrentOrderedMap[string, string]()
    m.Set("a", "developer")
    m.Set("b", "deliver")
    m.Set("c", "delta")
    m.Set("d", "programmer")

    // Levenshtein (ascending distance -> implemented as descending similarity)
    pairs, _ := m.OrderedByLevenshteinDistance("developer", true)
    fmt.Println("Levenshtein:", pairs)

    // Filter to keep only values containing "dev"
    pairsF, _ := m.OrderedByLevenshteinDistanceFiltered("developer", true, "dev")
    fmt.Println("Levenshtein + filter(\"dev\"):", pairsF)

    // Jaro–Winkler
    jw, _ := m.OrderedByJaroWinklerSimilarity("developer", true)
    fmt.Println("Jaro–Winkler:", jw)

    // Cosine TF–IDF (token based)
    tfidf, _ := m.OrderedByCosineTFIDF("python developer", true)
    fmt.Println("TF–IDF:", tfidf)

    // Soundex (phonetic)
    sdx, _ := m.OrderedBySoundex("Robert", true)
    fmt.Println("Soundex:", sdx)

    // Jaccard n-grams (default n=3)
    jac, _ := m.OrderedByJaccardNGrams("developer", true)
    fmt.Println("Jaccard trigrams:", jac)

    // Combined blend
    cmb, _ := m.OrderedByCombinedSimilarity("developer python", true)
    fmt.Println("Combined:", cmb)
}

Usage — Vector + Text Blend (1024-dim)

Typical value shape: map[string]interface{}{"text": string, "vector": []float64}

package main

import (
    "fmt"
    "math/rand"
    co "github.com/Dsouza10082/ConcurrentOrderedMap"
)

func main() {
    dims := 1024
    // Example query embedding (replace with your real 1024-dim vector)
    queryVec := make([]float64, dims)
    for i := range queryVec { queryVec[i] = rand.Float64() }

    m := co.NewConcurrentOrderedMap[float64, map[string]interface{}]()
    m.Set(1.0, map[string]interface{}{"text": "python developer", "vector": queryVec})
    m.Set(2.0, map[string]interface{}{"text": "developer", "vector": randomUnit(dims)})
    m.Set(3.0, map[string]interface{}{"text": "unrelated text", "vector": randomUnit(dims)})

    w := co.DefaultVectorBlendWeights() // tune if needed (e.g., w.WVec = 4, w.WCos = 2)

    // Blend vectors + all string similarities (no substring filter)
    pairs, err := m.OrderedByVectorCombinedSimilarity(
        "developer python",
        true,
        queryVec,
        dims,
        co.MapExtractor, // reads "text" and "vector" from value
        &w,
    )
    if err != nil { panic(err) }
    fmt.Println("Vector+Text:", pairs)

    // With substring filter over TEXT (case-insensitive)
    pairsF, _ := m.OrderedByVectorCombinedSimilarityFiltered(
        "developer python",
        true,
        "dev",
        queryVec,
        dims,
        co.MapExtractor,
        &w,
    )
    fmt.Println("Vector+Text filtered:", pairsF)

    // Vector-only baseline with filter
    vo, _ := m.OrderedByVectorOnlyFiltered(true, "dev", queryVec, dims, co.MapExtractor)
    fmt.Println("Vector-only filtered:", vo)
}

// randomUnit is pseudo; use your actual embeddings in production.
func randomUnit(d int) []float64 {
    v := make([]float64, d)
    var s float64
    for i := 0; i < d; i++ {
        v[i] = rand.NormFloat64()
        s += v[i] * v[i]
    }
    n := 1.0
    if s > 0 { n = 1.0 / (sqrt(s)) } // inline sqrt if you prefer; or math.Sqrt
    for i := range v { v[i] *= n }
    return v
}

Extractor helpers

If your values are structs, create a custom extractor:

type Item struct {
    ID     int
    Name   string
    Vector []float64
}

func ItemExtractor(v Item) (string, []float64, bool) {
    if len(v.Vector) == 0 { return "", nil, false }
    return v.Name, v.Vector, true
}

For map[string]interface{} values, use the ready-made:

// MapExtractor(value) -> (text, vector, ok)
co.MapExtractor

Weights

w := co.DefaultVectorBlendWeights()
w.WVec = 4.0  // emphasize vectors
w.WCos = 2.0  // emphasize token coverage
// tweak WLev, WDL, WJW, WJac, WSdx as needed

API Reference (New Methods)

Levenshtein
  • OrderedByLevenshteinDistance(target string, caseInsensitive bool)
  • OrderedByLevenshteinDistanceFiltered(target string, caseInsensitive bool, filter string)
Damerau–Levenshtein (OSA)
  • OrderedByDamerauLevenshteinDistance(target string, caseInsensitive bool)
  • OrderedByDamerauLevenshteinDistanceFiltered(target string, caseInsensitive bool, filter string)
Jaro–Winkler
  • OrderedByJaroWinklerSimilarity(target string, caseInsensitive bool)
  • OrderedByJaroWinklerSimilarityFiltered(target string, caseInsensitive bool, filter string)
Cosine TF–IDF
  • OrderedByCosineTFIDF(target string, caseInsensitive bool)
  • OrderedByCosineTFIDFFiltered(target string, caseInsensitive bool, filter string)
Soundex
  • OrderedBySoundex(target string, caseInsensitive bool)
  • OrderedBySoundexFiltered(target string, caseInsensitive bool, filter string)
Jaccard N-grams (n=3 by default)
  • OrderedByJaccardNGrams(target string, caseInsensitive bool)
  • OrderedByJaccardNGramsFiltered(target string, caseInsensitive bool, filter string)
Combined (text metrics blend)
  • OrderedByCombinedSimilarity(target string, caseInsensitive bool)
  • OrderedByCombinedSimilarityFiltered(target string, caseInsensitive bool, filter string)
Vector + Text Combined
  • OrderedByVectorCombinedSimilarity(target string, caseInsensitive bool, queryVec []float64, dims int, extract VectorTextExtractor[V], weights *VectorBlendWeights)
  • OrderedByVectorCombinedSimilarityFiltered(target string, caseInsensitive bool, filter string, queryVec []float64, dims int, extract VectorTextExtractor[V], weights *VectorBlendWeights)
  • OrderedByVectorOnlyFiltered(caseInsensitive bool, filter string, queryVec []float64, dims int, extract VectorTextExtractor[V])

Running Tests & Benchmarks

Requirements
  • Go 1.20+ (generics supported; 1.18+ works, 1.20+ recommended).
Run unit tests
go test ./...
Benchmarks — string similarities

Use env var SIM_BENCH_ITEMS to control dataset size (default: 10000).

# default size
go test -bench=Filtered_ -benchmem ./...

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

Use env var SIM_BENCH_VEC_ITEMS to control dataset size (default: 10000).

# default vector size
go test -bench=Vector -benchmem ./...

# larger dataset (warning: heavy)
SIM_BENCH_VEC_ITEMS=200000 go test -bench=Vector -benchmem ./...

Tip: Start with 10k–50k locally and scale up. The Combined and Vector+Text variants do more work per item and will be the slowest but most accurate.

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 added in v1.1.0

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 added in v1.1.0

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 added in v1.1.0

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

Public: Cosine TF-IDF

func (*ConcurrentOrderedMap[K, V]) OrderedByCosineTFIDFFiltered added in v1.1.0

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

func (*ConcurrentOrderedMap[K, V]) OrderedByDamerauLevenshteinDistance added in v1.1.0

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 added in v1.1.0

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 added in v1.1.0

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 added in v1.1.0

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

func (*ConcurrentOrderedMap[K, V]) OrderedByJaroWinklerSimilarity added in v1.1.0

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 added in v1.1.0

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

func (*ConcurrentOrderedMap[K, V]) OrderedByLevenshteinDistance added in v1.1.0

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

Public: Levenshtein (no filter)

func (*ConcurrentOrderedMap[K, V]) OrderedByLevenshteinDistanceFiltered added in v1.1.0

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 added in v1.1.0

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 added in v1.1.0

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

func (*ConcurrentOrderedMap[K, V]) OrderedByVectorCombinedSimilarity added in v1.1.0

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 added in v1.1.0

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 added in v1.1.0

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 added in v1.1.0

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 added in v1.1.0

func DefaultVectorBlendWeights() VectorBlendWeights

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

type VectorTextExtractor added in v1.1.0

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

Jump to

Keyboard shortcuts

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