tidwall / buntdb

BuntDB is an embeddable, in-memory key/value database for Go with custom indexing and geospatial support
MIT License
4.57k stars 289 forks source link

Question: Retrieve by index #18

Closed korjavin closed 7 years ago

korjavin commented 7 years ago

How to select data for condition - json field absent ?

    db.CreateIndex("age", "*", buntdb.IndexJSON("age"))
       tx.Set("5", `{"name":{"first":"Alan"},"age":28}`, nil)
        tx.Set("6", `{"name":{"first":"Dred"}}`, nil)

How to get number key=6 by age == nil?

And second question how to get key=5 by exact value age=28 ?

tidwall commented 7 years ago

Use the AscendGreaterOrEqual to scan an index. The second parameter is a valid json that is used to locate the first matching entry.

tx.Set("3", `{"name":{"first":"Tom"},"age":28}`, nil)
tx.Set("5", `{"name":{"first":"Alan"},"age":28}`, nil)
tx.Set("9", `{"name":{"first":"Jill"},"age":29}`, nil)
tx.Set("6", `{"name":{"first":"Dred"}}`, nil)
tx.Set("2", `{"name":{"first":"Tammy"},"age":null}`, nil)

// look for all keys with ages that equal 28
tx.AscendGreaterOrEqual("age", `{"age":28}`, func(key, value string) bool {
    age := gjson.Get(value, "age").Int()
    if age > 28 {
        return false
    }
    fmt.Printf("key=%s, age=%d\n", key, age)
    return true
})

// look for all keys with non-existent or null ages.
tx.AscendGreaterOrEqual("age", `{}`, func(key, value string) bool {
    if gjson.Get(value, "age").Type != gjson.Null {
        return false
    }
    fmt.Printf("key=%s, age=null\n", key)
    return true
})

output:

key=3, age=28
key=5, age=28
key=6, age=null
key=2, age=null

I recommend using the gjson package because it uses the same logic for finding values as CreateIndex.

korjavin commented 7 years ago

Thank you very much!

tidwall commented 7 years ago

You're welcome :)

korjavin commented 7 years ago

I'm sorry I get into a trouble again. Could you please look at this code: https://gist.github.com/afe35d11165bbf916e279158c55e7537

I expecting to get only records that have Sid=6 element, but I've got all of them.

tidwall commented 7 years ago

@korjavin Wondering if the code that I posted to the Gist helped?

korjavin commented 7 years ago

@tidwall I am happy that you asked, I haven't seen your valuable comment on the gist before!

Thank you a lot! I see that my understanding was wrong, and now I can see how I should do that!

tidwall commented 7 years ago

@korjavin You're welcome and let me know if you have any further questions. Thanks!