This document guides you on how to use Go Client through some simple examples. For more details, please visit client-go wiki.

Try the transactional key-value API

The txnkv package provides a transactional API against TiKV cluster.

Create Client

The topology of a TiKV cluster can be discovered by PD server. After starting a TiKV cluster successfully, we can use PD’s address list to create a client to interact with it.

  1. import "github.com/tikv/client-go/v2/txnkv"
  2. client, err := txnkv.NewClient([]string{"127.0.0.1:2379"})

Closing Client

When you are done with a client, you need to gracefully close the client to finish pending tasks and terminate all background jobs.

  1. // ... create a client as described above ...
  2. // ... do something with the client ...
  3. if err := client.Close(); err != nil {
  4. // ... handle error ...
  5. }

Starting Transaction

When using the transactional API, almost all read and write operations are done within a transaction (or a snapshot). You can use Begin to start a transaction.

  1. txn, err := client.Begin(opts...)
  2. if err != nil {
  3. // ... handle error ...
  4. }

Reads

TxnKV provides Get, BatchGet, Iter and IterReverse methods to query TiKV.

Get retrieves a key-value record from TiKV.

  1. import tikverr "github.com/tikv/client-go/v2/error"
  2. v, err := txn.Get(context.TODO(), []byte("foo"))
  3. if tikverr.IsErrNotFound(err) {
  4. // ... handle not found ...
  5. } else if err != nil {
  6. // ... handle other errors ...
  7. }
  8. // ... handle value v ...

When reading multiple keys from TiKV, BatchGet can be used.

  1. values, err := txn.BatchGet(context.TODO(), keys)
  2. if err != nil {
  3. // ... handle error ...
  4. }
  5. for _, k := range keys {
  6. if v, ok := values[string(k)]; ok {
  7. // ... handle record k:v ...
  8. } else {
  9. // ... k does not exist ...
  10. }
  11. }

All key-value records are logically arranged in sorted order. The iterators allow applications to do range scans on TiKV. The iterator yields records in the range [start, end).

  1. iter, err := txn.Iter(start, end)
  2. if err != nil {
  3. // ... handle error ...
  4. }
  5. defer iter.Close()
  6. for iter.Valid() {
  7. k, v := iter.Key(), iter.Value()
  8. // ... handle record k:v
  9. if err := iter.Next(); err != nil {
  10. // ... handle error ...
  11. }
  12. }

IterReverse also creates an iterator instance, but it iterates in reverse order.

Writes

You can use Set and Delete methods to write data into the transaction.

  1. if err := txn.Set([]byte("foo"), []byte("bar")); err != nil {
  2. // ... handle error ...
  3. }
  4. if err := txn.Delete([]byte("foo")); err != nil {
  5. // ... handle error ...
  6. }

Committing or Rolling Back Transaction

To actually commit the transaction to TiKV, you need to call Commit to trigger the commit process.

If the transaction does not need to commit, for optimistic transactions, you can just discard the transaction instance, for pessimistic transactions you need to actively call the Rollback() method to clean up the data previously sent to TiKV.

  1. if err := txn.Commit(context.TODO()); err != nil {
  2. // ... handle error ...
  3. }
  4. // ... commit success ...

Snapshots (Read-Only Transactions)

If you want to create a read-only transaction, you can use GetSnapshot method to create a snapshot. A Snapshot is more lightweight than a transaction.

  1. ts, err := client.CurrentTimestamp("global")
  2. if err != nil {
  3. // ... handle error ...
  4. }
  5. snapshot := client.GetSnapshot(ts)
  6. v, err := snapshot.Get(context.TODO(), []byte("foo"))
  7. // ... handle Get result ...

Snapshot can also be extracted from an existing transaction.

  1. snapshot := txn.GetSnapshot()
  2. // ... use snapshot ...

Try the Raw key-value API

Create client

After starting a TiKV cluster successfully, we can use PD’s address list to create a client to interact with it.

  1. import (
  2. "github.com/tikv/client-go/v2/rawkv"
  3. )
  4. client, err := rawkv.NewClientWithOpts(context.TODO(), []string{"127.0.0.1:2379"})
  5. if err != nil {
  6. // ... handle error ...
  7. }

Closing Client

When you are done with a client, you need to gracefully close the client to finish pending tasks and terminate all background jobs.

  1. if err := client.Close(); err != nil {
  2. // ... handle error ...
  3. }

Single Key Read/Write

RawKV provides Get, Put and Delete methods to read and write a single key.

  1. v, err := client.Get(context.TODO(), []byte("key"))
  2. if err != nil {
  3. // ... handle error ...
  4. }
  5. if v == nil {
  6. // ... handle not found ...
  7. } else {
  8. // ... handle value v ...
  9. }
  10. err = client.Put(context.TODO(), []byte("key"), []byte("value"))
  11. if err != nil {
  12. // ... handle error ...
  13. }
  14. err = client.Delete(context.TODO(), []byte("key"))
  15. if err != nil {
  16. // ... handle error ...
  17. }

Iterations

Like txnkv, there are also Scan and ReverseScan methods to iterate over a range of keys.

  1. keys, values, err := client.Scan(context.TODO(), []byte("begin"), []byte("end"), 10)
  2. if err != nil {
  3. // ... handle error ...
  4. }
  5. // ... handle keys, values ...
  6. keys, values, err := client.ReverseScan(context.TODO(), []byte("end"), []byte("begin"), 10)
  7. if err != nil {
  8. // ... handle error ...
  9. }
  10. // ... handle keys, values ...

Batch Operations

RawKV also supports batch operations using batch. Note that since RawKV does not provide transaction semantic, we do not guarantee that all writes will succeed or fail at the same time when these keys are distributed across multiple regions.

  1. values, err := client.BatchGet(context.TODO(), [][]byte{[]byte("key1"), []byte("key2")})
  2. if err != nil {
  3. // ... handle error ...
  4. }
  5. // ... handle values ...
  6. err = client.BatchPut(context.TODO(), [][]byte{[]byte("key1"), []byte("key2")}, [][]byte{[]byte("value1"), []byte("value2")})
  7. if err != nil {
  8. // ... handle error ...
  9. }
  10. err = client.BatchDelete(context.TODO(), [][]byte{[]byte("key1"), []byte("key2")})
  11. if err != nil {
  12. // ... handle error ...
  13. }