Last active
January 10, 2018 07:21
-
-
Save c4pt0r/dd5b809b7984ea822fbf101655362aa4 to your computer and use it in GitHub Desktop.
A simple demo of TiKV's prefix seek API
This file contains 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
// A simple demo of TiKV's prefix seek API | |
/* | |
$./benchseek | |
INFO[0000] [pd] create pd client with endpoints [localhost:2379] | |
INFO[0000] [pd] leader switches to: http://127.0.0.1:2379, previous: | |
INFO[0000] [pd] init cluster id 6508961674812833664 | |
hello_1 | |
hello_2 | |
hello_3 | |
hello_4 | |
*/ | |
package main | |
import ( | |
"bytes" | |
"flag" | |
"fmt" | |
"github.com/pingcap/tidb/kv" | |
"github.com/pingcap/tidb/store/tikv" | |
"github.com/pingcap/tidb/terror" | |
goctx "golang.org/x/net/context" | |
) | |
var ( | |
store kv.Storage | |
pdAddr = flag.String("pd", "localhost:2379", "pd address:localhost:2379") | |
) | |
// Init initializes information. | |
func initStore() { | |
driver := tikv.Driver{} | |
var err error | |
store, err = driver.Open(fmt.Sprintf("tikv://%s", *pdAddr)) | |
terror.MustNil(err) | |
} | |
func doSeek() { | |
// insert keys | |
txn, err := store.Begin() | |
terror.MustNil(err) | |
txn.Set(kv.Key("hello_1"), []byte("value")) | |
txn.Set(kv.Key("hello_2"), []byte("value")) | |
txn.Set(kv.Key("hello_3"), []byte("value")) | |
txn.Set(kv.Key("hello_4"), []byte("value")) | |
err = txn.Commit(goctx.Background()) | |
terror.MustNil(err) | |
// using seek API | |
txn, err = store.Begin() | |
terror.MustNil(err) | |
it, err := txn.Seek(kv.Key("hello_")) | |
terror.MustNil(err) | |
// iterate keys and then delete them | |
for it.Valid() && bytes.HasPrefix(it.Key(), []byte("hello_")) { | |
fmt.Println(string(it.Key())) | |
txn.Delete(it.Key()) | |
it.Next() | |
} | |
it.Close() | |
err = txn.Commit(goctx.Background()) | |
terror.MustNil(err) | |
} | |
func main() { | |
flag.Parse() | |
initStore() | |
doSeek() | |
} |
Author
c4pt0r
commented
Jan 10, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment