Skip to content

Latest commit

 

History

History
745 lines (542 loc) · 22.8 KB

client.md

File metadata and controls

745 lines (542 loc) · 22.8 KB

Client Class

The Client class provides operations which can be performed on an Aerospike database cluster. In order to get an instance of the Client class, you need to call NewClient():

  client, err := as.NewClient("127.0.0.1", 3000)

To customize a Client with a ClientPolicy:

  clientPolicy := as.NewClientPolicy()
  clientPolicy.ConnectionQueueSize = 64
  clientPolicy.LimitConnectionsToQueueSize = true
  clientPolicy.Timeout = 50 * time.Millisecond

  client, err := as.NewClientWithPolicy(clientPolicy, "127.0.0.1", 3000)

Notice: Examples in the section are only intended to illuminate simple use cases without too much distraction. Always follow good coding practices in production. Always check for errors.

With a new client, you can use any of the methods specified below. You need only ONE client object. This object is goroutine-friendly, and pools its resources internally.

Methods

Add(policy *WritePolicy, key *Key, bins BinMap) error

Using the provided key, adds values to the mentioned bins. Bin value types should be of type integer for the command to have any effect.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.
  • bins – A BinMap used for specifying the fields and value.

Example:

  key := NewKey("test", "demo", 123)

  bins = BinMap {
    "e": 2,
    "pi": 3,
  }

  err := client.Add(nil, key, bins)

Append(policy *WritePolicy, key *Key, bins BinMap) error

Using the provided key, appends provided values to the mentioned bins. Bin value types should be of type string or []byte for the command to have any effect.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.
  • bins – A BinMap used for specifying the fields and value.

Example:

  key := NewKey("test", "demo", 123)

  bins = BinMap {
    "story": ", and lived happily ever after...",
  }

  err := client.Append(nil, key, bins)

Close()

Closes the client connection to the cluster.

Example:

  client.Close()

Delete(policy *WritePoicy, key *Key) (existed bool, err error)

Removes a record with the specified key from the database cluster.

Parameters:

returned values:

  • existed – Boolean value that indicates if the Key existed.

Example:

  key := NewKey("test", "demo", 123)

  if existed, err := client.Delete(nil, key); existed {
    // do something
  }

Exists(policy *BasePolicy, key *Key) (bool, error)

Using the key provided, checks for the existence of a record in the database cluster .

Parameters:

  • policy – (optional) The BasePolicy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.

Example:

  key := NewKey("test", "demo", 123)

  if exists, err := client.Exists(nil, key) {
    // do something
  }

BatchExists(policy *BasePolicy, keys []*Key) ([]bool, error)

Using the keys provided, checks for the existence of records in the database cluster in one request.

Parameters:

  • policy – (optional) The BasePolicy object to use for this operation. Pass nil for default values.
  • keys – A Key array, used to locate the records in the cluster.

Example:

  key1 := NewKey("test", "demo", 123)
  key2 := NewKey("test", "demo", 42)

  existanceArray, err := client.Exists(nil, []*Key{key1, key2}) {
    // do something
  }

Get(policy *BasePolicy, key *Key, bins ...string) (*Record, error)

Using the key provided, reads a record from the database cluster .

Parameters:

  • policy – (optional) The BasePolicy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.
  • bins – (optional) Bins to retrieve. Will retrieve all bins if not provided.

Example:

  key := NewKey("test", "demo", 123)

  rec, err := client.Get(nil, key) // reads all the bins

GetHeader(policy *BasePolicy, key *Key) (*Record, error)

Using the key provided, reads ONLY record metadata from the database cluster. Record metadata includes record generation and Expiration (TTL from the moment of retrieval, in seconds)

record.Bins will always be empty in resulting record.

Parameters:

  • policy – (optional) The BasePolicy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.

Example:

  key := NewKey("test", "demo", 123)

  rec, err := client.GetHeader(nil, key) // No bins will be retrieved

BatchGet(policy *BasePolicy, keys *[]Key, bins ...string) ([]*Record, error)

Using the keys provided, reads all relevant records from the database cluster in a single request.

Parameters:

  • policy – (optional) The BasePolicy object to use for this operation. Pass nil for default values.
  • keys – A Key array, used to locate the record in the cluster.
  • bins – (optional) Bins to retrieve. Will retrieve all bins if not provided.

Example:

  key1 := NewKey("test", "demo", 123)
  key2 := NewKey("test", "demo", 42)

  recs, err := client.BatchGet(nil, []*Key{key1, key2}) // reads all the bins

BatchGetHeader(policy *BasePolicy, keys *[]Key) ([]*Record, error)

Using the keys provided, reads all relevant record metadata from the database cluster in a single request.

record.Bins will always be empty in resulting record.

Parameters:

  • policy – (optional) The BasePolicy object to use for this operation. Pass nil for default values.
  • keys – A Key array, used to locate the record in the cluster.

Example:

  key1 := NewKey("test", "demo", 123)
  key2 := NewKey("test", "demo", 42)

  recs, err := client.BatchGetHeader(nil, []*Key{key1, key2}) // reads all the bins

IsConnected() bool

Checks if the client is connected to the cluster.

Prepend(policy *WritePolicy, key *Key, bins BinMap) error

Using the provided key, prepends provided values to the mentioned bins. Bin value types should be of type string or []byte for the command to have any effect.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.
  • bins – A BinMap used for specifying the fields and value.

Example:

  key := NewKey("test", "demo", 123)

  bins = BinMap {
    "story": "Long ago, in a galaxy far far away, ",
  }

  err := client.Prepend(nil, key, bins)

Put(policy *WritePolicy, key *Key, bins BinMap) error

Writes a record to the database cluster. If the record exists, it modifies the record with bins provided. To remove a bin, set its value to nil.

Node: Under the hood, Put converts BinMap to []Bins and uses PutBins. Use PutBins to avoid unnecessary memory allocation and iteration.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.
  • bins – A BinMap map used for specifying the fields to store.

Example:

  key := NewKey("test", "demo", 123)

  bins := BinMap {
    "a": "Lack of skill dictates economy of style.",
    "b": 123,
    "c": []int{1, 2, 3},
    "d": map[string]interface{}{"a": 42, "b": "An elephant is mouse with an operating system."},
  }

  err := client.Put(nil, key, bins)

PutBins(policy *WritePolicy, key *Key, bins ...*Bin) error

Writes a record to the database cluster. If the record exists, it modifies the record with bins provided. To remove a bin, set its value to nil.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.
  • bins – A Bin array used for specifying the fields to store.

Example:

  key := NewKey("test", "demo", 123)

  bin1 := NewBin("a", "Lack of skill dictates economy of style.")
  bin2 := NewBin("b", 123)
  bin3 := NewBin("c", []int{1, 2, 3})
  bin4 := NewBin("d", map[string]interface{}{"a": 42, "b": "An elephant is mouse with an operating system."})

  err := client.PutBins(nil, key, bin1, bin2, bin3, bin4)

Touch(policy *WritePolicy, key *Key) error

Create record if it does not already exist. If the record exists, the record's time to expiration will be reset to the policy's expiration.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • key – A Key object, used to locate the record in the cluster.

Example:

  key := NewKey("test", "demo", 123)

  err := client.Touch(NewWritePolicy(0, 5), key)

ScanAll(policy *ScanPolicy, namespace string, setName string, binNames ...string) (*Recordset, error)

Performs a full Scan on all nodes in the cluster, and returns the results in a Recordset object

Parameters:

  • policy – (optional) A Scan Policy object to use for this operation. Pass nil for default values.
  • namespace – Namespace to perform the scan on.
  • setName – Name of the Set to perform the scan on.
  • binNames – Name of bins to retrieve. If not passed, all bins will be retrieved.

Refer to Recordset object documentation for details on how to retrieve the data.

Example:

  // scan the whole cluster
  recordset, err := client.ScanAll(nil, "test", "demo")

  for res := range recordset.Results() {
    if res.Err != nil {
      // handle error; or close the recordset and break
    }
    
  // process record
  fmt.Println(res.Record)
  }

ScanNode(policy *ScanPolicy, node *Node, namespace string, setName string, binNames ...string) (*Recordset, error)

Performs a full Scan on a specific node in the cluster, and returns the results in a Recordset object

It works the same as ScanAll() method.

CreateIndex(policy *WritePolicy, namespace string, setName string, indexName string, binName string, indexType IndexType) (*IndexTask, error)

Creates a secondary index. IndexTask will return a IndexTask object which can be used to determine if the operation is completed.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • namespace – Namespace
  • setName – Name of the Set
  • indexName – Name of index
  • binName – Bin name to create the index on
  • indexType – STRING or NUMERIC

Example:

  idxTask, err := client.CreateIndex(nil, "test", "demo", "indexName", "binName", NUMERIC)
  panicOnErr(err)

  // wait until index is created.
  // OnComplete() channel will return nil on success and an error on errors
  err = <- idxTask.OnComplete()
  if err != nil {
    panic(err)
  }

DropIndex( policy *WritePolicy, namespace string, setName string, indexName string) error

Drops an index.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • namespace – Namespace
  • setName – Name of the Set.
  • indexName – Name of index
  err := client.DropIndex(nil, "test", "demo", "indexName")

RegisterUDF(policy *WritePolicy, udfBody []byte, serverPath string, language Language) (*RegisterTask, error)

Registers the given UDF on the server.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • udfBody – UDF source code
  • serverPath – Path on which the UDF should be put on the server-side
  • language – Only 'LUA' is currently supported

Example:

  const udfBody = `function testFunc1(rec)
     local ret = map()                     -- Initialize the return value (a map)

     local x = rec['bin1']               -- Get the value from record bin named "bin1"

     rec['bin2'] = (x / 2)               -- Set the value in record bin named "bin2"

     aerospike:update(rec)                -- Update the main record

     ret['status'] = 'OK'                   -- Populate the return status
     return ret                             -- Return the Return value and/or status
  end`

  regTask, err := client.RegisterUDF(nil, []byte(udfBody), "udf1.lua", LUA)
  panicOnErr(err)

  // wait until UDF is created
  err = <-regTask.OnComplete()
  if err != nil {
    panic(err)
  }

RegisterUDFFromFile(policy *WritePolicy, clientPath string, serverPath string, language Language) (*RegisterTask, error)

Read the UDF source code from a file and registers it on the server.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • clientPath – full file path for UDF source code
  • serverPath – Path on which the UDF should be put on the server-side
  • language – Only 'LUA' is currently supported

Example:

  regTask, err := client.RegisterUDFFromFile(nil, "/path/udf.lua", "udf1.lua", LUA)
  panicOnErr(err)

  // wait until UDF is created
  err = <- regTask.OnComplete()
  if err != nil {
    panic(err)
  }

Execute(policy *WritePolicy, key *Key, packageName string, functionName string, args ...Value) (interface{}, error)

Executes a UDF on a record with the given key, and returns the results.

Parameters:

  • policy – (optional) A Write Policy object to use for this operation. Pass nil for default values.
  • packageName – server path to the UDF
  • functionName – UDF name
  • args – (optional) UDF arguments

Example:

Considering the UDF registered in RegisterUDF example above:

    res, err := client.Execute(nil, key, "udf1", "testFunc1")

    // res will be a: map[interface{}]interface{}{"status": "OK"}

ExecuteUDF(policy *QueryPolicy, statement *Statement, packageName string, functionName string, functionArgs ...Value) (*ExecuteTask, error)

Executes a UDF on all records which satisfy filters set in the statement. If there are filters, it will run on all records in the database.

Parameters:

  • policy – (optional) A Query Policy object to use for this operation. Pass nil for default values.
  • statementStatement object to narrow down records.
  • packageName – server path to the UDF
  • functionName – UDF name
  • functionArgs – (optional) UDF arguments

Example:

Considering the UDF registered in RegisterUDF example above:

  statement := NewStatement("namespace", "set")
  exTask, err := client.ExecuteUDF(nil, statement, "udf1", "testFunc1")
  panicOnErr(err)

  // wait until UDF is run on all records
  err = <- exTask.OnComplete()
  if err != nil {
    panic(err)
  }

Query(policy *QueryPolicy, statement *Statement) (*Recordset, error)

Performs a query on the cluster, and returns the results in a Recordset object

Parameters:

Refer to Recordset object documentation for details on how to retrieve the data.

Example:

  stm := NewStatement("namespace", "set")
  stm.Addfilter(NewRangeFilter("binName", value1, value2))

  recordset, err := client.Query(nil, stm)

  // consume recordset and check errors
  for res := recordset.Results() {
    if res.Err != nil {
      // handle error, or close the recordset and break
    }

    // process record
    fmt.Println(res.Record)
  }