-
Notifications
You must be signed in to change notification settings - Fork 0
/
upstash.go
121 lines (110 loc) · 2.41 KB
/
upstash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package simcache
import (
"errors"
"github.com/upstash/vector-go"
)
type UpstashOptions struct {
MinProximity float32 `json:"minProximity"`
Index *vector.Index
}
type UpstashSimCache struct {
minProximity float32
index *vector.Index
}
func NewSimCache(config UpstashOptions) *UpstashSimCache {
if config.MinProximity == 0 {
config.MinProximity = 0.8
}
return &UpstashSimCache{
minProximity: config.MinProximity,
index: config.Index,
}
}
func (cache *UpstashSimCache) Get(keyOrKeys interface{}) (interface{}, error) {
switch key := keyOrKeys.(type) {
case string:
return cache.queryKey(key)
case []string:
res := make([]interface{}, len(key))
for i, k := range key {
value, err := cache.queryKey(k)
if err != nil {
return "", err
}
res[i] = value
}
return res, nil
}
return "", errors.New("invalid types or lengths")
}
func (cache *UpstashSimCache) queryKey(key string) (interface{}, error) {
res, err := cache.index.QueryData(vector.QueryData{
Data: key,
TopK: 2,
IncludeVectors: true,
IncludeMetadata: true,
})
if err != nil {
return "", err
}
if len(res) > 0 && res[0].Score > cache.minProximity {
return res[0].Metadata["value"], nil
}
return "", nil
}
func (cache *UpstashSimCache) Set(keyOrKeys interface{}, valueOrValues interface{}) error {
switch key := keyOrKeys.(type) {
case string:
if value, ok := valueOrValues.(string); ok {
err := cache.index.UpsertData(vector.UpsertData{
Id: key,
Data: key,
Metadata: map[string]interface{}{
"value": value,
},
})
if err != nil {
return err
}
return nil
}
case []string:
if values, ok := valueOrValues.([]string); ok {
for i, key := range key {
err := cache.index.UpsertData(vector.UpsertData{
Id: key,
Data: key,
Metadata: map[string]interface{}{
"value": values[i],
},
})
if err != nil {
return err
}
}
return nil
}
}
return errors.New("invalid types or lengths")
}
func (cache *UpstashSimCache) Delete(key string) error {
_, err := cache.index.Delete(key)
if err != nil {
return err
}
return nil
}
func (cache *UpstashSimCache) BulkDelete(keys []string) error {
_, err := cache.index.DeleteMany(keys)
if err != nil {
return err
}
return nil
}
func (cache *UpstashSimCache) Flush() error {
err := cache.index.Reset()
if err != nil {
return err
}
return nil
}