forked from timshannon/badgerhold
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
91 lines (75 loc) · 1.61 KB
/
example_test.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
// Copyright 2019 Tim Shannon. All rights reserved.
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.
package badgerhold_test
import (
"fmt"
"log"
"os"
"time"
"github.com/dgraph-io/badger/v3"
"github.com/timshannon/badgerhold/v4"
)
type Item struct {
ID int
Category string `badgerholdIndex:"Category"`
Created time.Time
}
func Example() {
data := []Item{
{
ID: 0,
Category: "blue",
Created: time.Now().Add(-4 * time.Hour),
},
{
ID: 1,
Category: "red",
Created: time.Now().Add(-3 * time.Hour),
},
{
ID: 2,
Category: "blue",
Created: time.Now().Add(-2 * time.Hour),
},
{
ID: 3,
Category: "blue",
Created: time.Now().Add(-20 * time.Minute),
},
}
dir := tempdir()
defer os.RemoveAll(dir)
options := badgerhold.DefaultOptions
options.Dir = dir
options.ValueDir = dir
store, err := badgerhold.Open(options)
defer store.Close()
if err != nil {
// handle error
log.Fatal(err)
}
// insert the data in one transaction
err = store.Badger().Update(func(tx *badger.Txn) error {
for i := range data {
err := store.TxInsert(tx, data[i].ID, data[i])
if err != nil {
return err
}
}
return nil
})
if err != nil {
// handle error
log.Fatal(err)
}
// Find all items in the blue category that have been created in the past hour
var result []Item
err = store.Find(&result, badgerhold.Where("Category").Eq("blue").And("Created").Ge(time.Now().Add(-1*time.Hour)))
if err != nil {
// handle error
log.Fatal(err)
}
fmt.Println(result[0].ID)
// Output: 3
}