Created
May 14, 2017 18:45
-
-
Save korjavin/e5488c8efd08092673f2553bc83d2e83 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"github.com/tidwall/buntdb" | |
"github.com/tidwall/gjson" | |
"log" | |
"strconv" | |
"time" | |
) | |
type Order struct { | |
Oid int | |
Statuses []Orderstatus | |
} | |
type Orderstatus struct { | |
Sid int | |
Time string // 2017-05-01T00:00:00Z | |
} | |
//compareDates is a special function which extracts dates from status=6 and compare then | |
func compareDates(a, b string) bool { | |
astr := gjson.Get(a, `Statuses.#[Sid=6].Time`).String() | |
bstr := gjson.Get(b, `Statuses.#[Sid=6].Time`).String() | |
start, err := time.Parse("2006-01-02T15:04:05Z", astr) | |
if err != nil { | |
return true | |
} | |
end, err := time.Parse("2006-01-02T15:04:05Z", bstr) | |
if err != nil { | |
return false | |
} | |
// log.Printf("Compared %s %s \n", a, b) | |
return end.After(start) | |
} | |
func main() { | |
// Some data | |
os := []Order{ | |
Order{Oid: 1, Statuses: []Orderstatus{Orderstatus{Sid: 1}, Orderstatus{Sid: 2, Time: "2016-03-17T12:57:51Z"}}}, | |
Order{Oid: 2, Statuses: []Orderstatus{Orderstatus{Sid: 2}, Orderstatus{Sid: 6, Time: "2016-03-17T10:58:03Z"}}}, | |
Order{Oid: 3, Statuses: []Orderstatus{Orderstatus{Sid: 3}, Orderstatus{Sid: 6, Time: "2016-03-17T15:58:03Z"}}}, | |
Order{Oid: 4, Statuses: []Orderstatus{Orderstatus{Sid: 5}, Orderstatus{Sid: 6, Time: "2016-03-17T20:58:03Z"}}}, | |
} | |
db, _ := buntdb.Open(":memory:") | |
//Store them | |
db.Update(func(tx *buntdb.Tx) error { | |
for _, o := range os { | |
buf, _ := json.Marshal(o) | |
tx.Set(strconv.Itoa(o.Oid), string(buf), nil) | |
} | |
return nil | |
}) | |
//Build index with our function | |
db.Update(func(tx *buntdb.Tx) error { | |
err := tx.CreateIndex("sid", "*", compareDates) | |
return err | |
}) | |
db.View(func(tx *buntdb.Tx) error { | |
pivots := []string{ | |
`{"Statuses.#[Sid=6].Time:"2016-03-17T12:58:03Z"}`, | |
`{"2016-03-17T12:58:03Z"}`, | |
`{"Time":"2016-03-17T12:58:03Z"}`, | |
`2016-03-17T12:58:03`, | |
} | |
for _, pivot := range pivots { | |
log.Printf("pivot=%s:\n", pivot) | |
tx.AscendGreaterOrEqual("sid", pivot, func(key, value string) bool { | |
var order Order | |
json.Unmarshal([]byte(value), &order) | |
time := gjson.Get(value, `Statuses.#[Sid=6].Time`) | |
log.Printf("key=%s, sid=%s\n", key, time) | |
return true | |
}) | |
} | |
return nil | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try this pivot
{"Statuses":[{"Sid":6,"Time":"2016-03-17T12:58:03Z"}]}