Class: Client

Client

Aerospike client


new Client(config)

Construct a new Aerospike client instance.

Parameters:
Name Type Description
config Config

Configuration used to initialize the client.

Source:

Members


captureStackTraces :boolean

Set to true to enable capturing of debug stacktraces for every database command.

The client will capture a stacktrace before each database command is executed, instead of capturing the stacktrace only when an error is raised. This generally results in much more useful stacktraces that include stackframes from the calling application issuing the database command.

Note: Enabling this feature incurs a significant performance overhead for every database command. It is recommended to leave this feature disabled in production environments.

By default, the client will set this flag to true, if the AEROSPIKE_DEBUG_STACKTRACES environment variable is set (to any value).

Type:
  • boolean
Default Value:
  • true, if process.env.AEROSPIKE_DEBUG_STACKTRACES is set; false otherwise.
Source:

config :Config

A copy of the configuration with which the client was initialized.

Type:
Source:

Methods


addSeedHost(hostname [, port])

Adds a seed host to the cluster.

Parameters:
Name Type Argument Default Description
hostname String

Hostname/IP address of the new seed host

port Number <optional>
3000

Port number; defaults to Config#port or 3000.

Since:
  • v2.6.0
Source:

apply(key, udfArgs [, policy] [, callback])

Applies a User Defined Function (UDF) on a record in the database.

Use this function to apply a ⇑Record UDF on a single record and return the result of the UDF function call. Record UDFs can be used to augment both read and write behavior.

For additional information please refer to the section on ⇑Developing Record UDFs in the Aerospike technical documentation.

Parameters:
Name Type Argument Description
key Key

The key, used to locate the record in the cluster.

udfArgs Object

Parameters used to specify which UDF function to execute.

Properties
Name Type Description
module string

The name of the UDF module that was registered with the cluster.

funcname string

The name of the UDF function within the module.

args Array.<(number|string)>

List of arguments to pass to the UDF function.

policy ApplyPolicy <optional>

The Apply Policy to use for this operation.

callback valueCallback <optional>

This function will be called with the result returned by the Record UDF function call.

Since:
  • v2.0
Source:
See:
Returns:

If no callback function is passed, the function returns a Promise that resolves to the value returned by the UDF.

Type
Promise
Example
var key = new Key('test', 'demo', value')
var udfArgs = {
  module: 'my_udf_module',
  funcname: 'my_udf_function',
  args: ['abc', 123, 4.5]
}

client.apply(key, udfArgs, (error, result) => {
  if (error) throw error

  console.log('Result of calling my_udf_function:', result)
})

batchExists(keys [, policy] [, callback])

Checks the existence of a batch of records from the database cluster.

Parameters:
Name Type Argument Description
keys Array.<Key>

An array of Keys used to locate the records in the cluster.

policy BatchPolicy <optional>

The Batch Policy to use for this operation.

callback batchRecordsCallback <optional>

The function to call when the operation completes, with the results of the batch operation.

Deprecated:
Source:
Returns:
  • If no callback function is passed, the function returns a Promise that resolves to the results of the batch operation.
Type
Promise
Example
var keys = [
  new Key('test', 'demo', 'key1'),
  new Key('test', 'demo', 'key2'),
  new Key('test', 'demo', 'key3')
]

client.batchExists(keys, function (error, results) {
  if (error) {
    // handle failure
  } else {
    results.forEach(function (result) {
      switch (result.status) {
        case status.OK:
          // record found
          break
        case status.ERR_RECORD_NOT_FOUND:
          // record not found
          break
        default:
          // error while reading record
          break
      }
    })
  }
})

batchGet(keys [, policy] [, callback])

Reads a batch of records from the database cluster.

Parameters:
Name Type Argument Description
keys Array.<Key>

An array of keys, used to locate the records in the cluster.

policy BatchPolicy <optional>

The Batch Policy to use for this operation.

callback batchRecordsCallback <optional>

The function to call when the operation completes, with the results of the batch operation.

Deprecated:
Source:
Returns:
  • If no callback function is passed, the function returns a Promise that resolves to the results of the batch operation.
Type
Promise
Example
var keys = [
  new Key('test', 'demo', 'key1'),
  new Key('test', 'demo', 'key2'),
  new Key('test', 'demo', 'key3')
]

client.batchGet(keys, function (error, results) {
  if (error) {
    // handle failure
  } else {
    results.forEach(function (result) {
      switch (result.status) {
        case status.OK:
          // record found - bin values are available in result.record
          break
        case status.ERR_RECORD_NOT_FOUND:
          // record not found
          break
        default:
          // error while reading record
          break
      }
    })
  }
})

batchRead(records [, policy] [, callback])

Read multiple records for specified batch keys in one batch call.

This method allows different namespaces/bins to be requested for each key in the batch. This method requires Aerospike Server version >= 3.6.0.

Parameters:
Name Type Argument Description
records Array.<object>

List of keys and bins to retrieve.

records[].key Key

Key to retrieve.

records[].bins Array.<string> <optional>

List of bins to retrieve.

records[].read_all_bins boolean <optional>

Whether to retrieve all bins or just the meta data of the record. If true, ignore bins and read all bins; if false and bins is specified, read specified bins; if false and bins is not specified, read only record meta data (generation, expiration, etc.)

policy BatchPolicy <optional>

The Batch Policy to use for this operation.

callback batchRecordsCallback <optional>

The function to call when the operation completes, with the results of the batch operation.

Since:
  • v2.0
Source:
Returns:
  • If no callback function is passed, the function returns a Promise that resolves to the results of the batch operation.
Type
Promise
Example
const Aerospike = require('aerospike')
var batchRecords = [
  { key: new Aerospike.Key('test', 'demo', 'key1'), bins: ['i', 's'] },
  { key: new Aerospike.Key('test', 'demo', 'key2'), read_all_bins: true },
  { key: new Aerospike.Key('test', 'demo', 'key3') }
]
Aerospike.connect(function (error, client) {
  if (error) throw error
  client.batchRead(batchRecords, function (error, results) {
    if (error) throw error
    results.forEach(function (result) {
      console.log(result)
    })
  })
})

batchSelect(keys, bins [, policy] [, callback])

Reads a subset of bins for a batch of records from the database cluster.

Parameters:
Name Type Argument Description
keys Array.<Key>

An array of keys, used to locate the records in the cluster.

bins Array.<string>

An array of bin names for the bins to be returned for the given keys.

policy BatchPolicy <optional>

The Batch Policy to use for this operation.

callback batchRecordsCallback <optional>

The function to call when the operation completes, with the results of the batch operation.

Deprecated:
Source:
Returns:
  • If no callback function is passed, the function returns a Promise that resolves to the results of the batch operation.
Type
Promise
Example
var keys = [
  new Key('test', 'demo', 'key1'),
  new Key('test', 'demo', 'key2'),
  new Key('test', 'demo', 'key3')
]
var bins = ['s', 'i']

client.batchSelect(keys, bins, function (error, results) {
  if (error) {
    // handle failure
  } else {
    results.forEach(function (result) {
      switch (result.status) {
        case status.OK:
          // record found - selected bins are available in result.record.
          break
        case status.ERR_RECORD_NOT_FOUND:
          // record not found
          break
        default:
          // error while reading record
          break
      }
    })
  }
})

close( [releaseEventLoop])

Closes the client connection to the cluster.

Parameters:
Name Type Argument Default Description
releaseEventLoop boolean <optional>
true

Whether to release the event loop handle after the client is closed.

Source:
See:
Example
const Aerospike = require('aerospike')
Aerospike.connect(function (error, client) {
  if (error) throw error
  // client ready to receive commands
  client.close()
})

connect( [callback])

Establishes the connection to the cluster.

Once the client is connected to at least one server node, it will start polling each cluster node regularly to discover the current cluster status. As new nodes are added to the cluster, or existing nodes are removed, the client will establish or close down connections to these nodes. If the client gets disconnected from the cluster, it will keep polling the last known server endpoints, and will reconnect automatically if the connection is reestablished.

Parameters:
Name Type Argument Description
callback connectCallback <optional>

The function to call once the client connection has been established successfully and the client is ready to accept commands.

Source:
See:
Throws:

if event loop resources have already been released.

Type
AerospikeError
Returns:

If no callback function is passed, the function returns a Promise resolving to the connected client.

Type
Promise
Example

Using callback function

const Aerospike = require('aerospike')

var config = { ... }
var client = Aerospike.client(config)
client.connect((error) => {
  if (error) {
    console.error('Failed to connect to cluster: %s', error.message)
    process.exit()
  } else {
    // client is ready to accept commands
  }
})

createGeo2DSphereIndex(options [, policy] [, callback])

Creates a secondary, geospatial index.

This is a short-hand for calling Client#createIndex with the datatype option set to Aerospike.indexDataType.GEO2DSPHERE.

Parameters:
Name Type Argument Description
options Object

Options for creating the index.

Properties
Name Type Argument Description
ns string

The namespace on which the index is to be created.

set string

The set on which the index is to be created.

bin string

The name of the bin which values are to be indexed.

index string

The name of the index to be created.

type module:aerospike.indexType <optional>

Type of index to be created based on the type of values stored in the bin. This option needs to be specified if the bin to be indexed contains list or map values and the individual entries of the list or keys/values of the map should be indexed.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback jobCallback <optional>

The function to call when the operation completes.

Source:
See:
  • Client#indexCreate
Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise
Example
const Aerospike = require('aerospike')
Aerospike.connect((error, client) => {
  if (error) throw error

  var binName = 'location'
  var indexName = 'locationIndex'
  var options = { ns: 'test',
                  set: 'demo',
                  bin: binName,
                  index: indexName }

  client.createGeo2DSphereIndex(options, function (error) {
    if (error) throw error
    console.info('secondary index %s on %s was created successfully', indexName, binName)
    client.close()
  })
})

createIndex(options [, policy] [, callback])

Creates a secondary index.

Calling the createIndex method issues an index create command to the Aerospike cluster and returns immediately. To verify that the index has been created and populated with all the data use the IndexJob instance returned by the callback.

Aerospike currently supports indexing of strings, integers and geospatial information in GeoJSON format.

String Indexes

A string index allows for equality lookups. An equality lookup means that if you query for an indexed bin with value "abc", then only records containing bins with "abc" will be returned.

Integer Indexes

An integer index allows for either equality or range lookups. An equality lookup means that if you query for an indexed bin with value 123, then only records containing bins with the value 123 will be returned. A range lookup means that if you can query bins within a range. So, if your range is (1...100), then all records containing a value in that range will be returned.

Geo 2D Sphere Indexes

A geo 2d sphere index allows either "contains" or "within" lookups. A "contains" lookup means that if you query for an indexed bin with GeoJSON point element, then only records containing bins with a GeoJSON element containing that point will be returned. A "within" lookup means that if you query for an indexed bin with a GeoJSON polygon element, then all records containing bins with a GeoJSON element wholly contained within that polygon will be returned.

Parameters:
Name Type Argument Description
options Object

Options for creating the index.

Properties
Name Type Argument Description
ns string

The namespace on which the index is to be created.

set string

The set on which the index is to be created.

bin string

The name of the bin which values are to be indexed.

index string

The name of the index to be created.

type module:aerospike.indexType <optional>

Type of index to be created based on the type of values stored in the bin. This option needs to be specified if the bin to be indexed contains list or map values and the individual entries of the list or keys/values of the map should be indexed.

datatype module:aerospike.indexDataType

The data type of the index to be created, e.g. Numeric, String or Geo.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback jobCallback <optional>

The function to call when the operation completes.

Since:
  • v2.0
Source:
See:
Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise
Example
const Aerospike = require('aerospike')
Aerospike.connect((error, client) => {
  if (error) throw error

  // create index over user's recent locations
  let namespace = 'test'
  let set = 'demo'
  let binName = 'rloc' // recent locations
  let indexName = 'recentLocationsIdx'
  let indexType = Aerospike.indexType.LIST
  let dataType = Aerospike.indexDataType.GEO2DSPHERE
  let options = { ns: namespace,
                  set: set,
                  bin: binName,
                  index: indexName,
                  type: indexType,
                  datatype: dataType }
  let policy = new Aerospike.InfoPolicy({ totalTimeout: 100 })

  client.createIndex(options, policy, (error, job) => {
    if (error) throw error

    // wait for index creation to complete
    var pollInterval = 100
    job.waitUntilDone(pollInterval, (error) => {
      if (error) throw error
      console.info('secondary index %s on %s was created successfully', indexName, binName)
      client.close()
    })
  })
})

createIntegerIndex(options [, policy] [, callback])

Creates a secondary index of type Integer.

This is a short-hand for calling Client#createIndex with the datatype option set to Aerospike.indexDataType.NUMERIC.

Parameters:
Name Type Argument Description
options Object

Options for creating the index.

Properties
Name Type Argument Description
ns string

The namespace on which the index is to be created.

set string

The set on which the index is to be created.

bin string

The name of the bin which values are to be indexed.

index string

The name of the index to be created.

type module:aerospike.indexType <optional>

Type of index to be created based on the type of values stored in the bin. This option needs to be specified if the bin to be indexed contains list or map values and the individual entries of the list or keys/values of the map should be indexed.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback jobCallback <optional>

The function to call when the operation completes.

Source:
See:
  • Client#indexCreate
Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise
Example
const Aerospike = require('aerospike')
Aerospike.connect((error, client) => {
  if (error) throw error

  var binName = 'age'
  var indexName = 'ageIndex'
  var options = { ns: 'test',
                  set: 'demo',
                  bin: binName,
                  index: indexName }

  client.createIntegerIndex(options, function (error) {
    if (error) throw error
    console.info('secondary index %s on %s was created successfully', indexName, binName)
    client.close()
  })
})

createStringIndex(options [, policy] [, callback])

Creates a secondary index of type String.

This is a short-hand for calling Client#createIndex with the datatype option set to Aerospike.indexDataType.STRING.

Parameters:
Name Type Argument Description
options Object

Options for creating the index.

Properties
Name Type Argument Description
ns string

The namespace on which the index is to be created.

set string

The set on which the index is to be created.

bin string

The name of the bin which values are to be indexed.

index string

The name of the index to be created.

type module:aerospike.indexType <optional>

Type of index to be created based on the type of values stored in the bin. This option needs to be specified if the bin to be indexed contains list or map values and the individual entries of the list or keys/values of the map should be indexed.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback jobCallback <optional>

The function to call when the operation completes.

Source:
See:
  • Client#indexCreate
Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise
Example
const Aerospike = require('aerospike')
Aerospike.connect((error, client) => {
  if (error) throw error

  var binName = 'name'
  var indexName = 'nameIndex'
  var options = { ns: 'test',
                  set: 'demo',
                  bin: binName,
                  index: indexName }

  client.createStringIndex(options, function (error) {
    if (error) throw error
    console.info('secondary index %s on %s was created successfully', indexName, binName)
    client.close()
  })
})

exists(key [, policy] [, callback])

Checks the existance of a record in the database cluster.

Parameters:
Name Type Argument Description
key Key

The key of the record to check for existance.

policy ReadPolicy <optional>

The Read Policy to use for this operation.

callback valueCallback <optional>

The function to call when the operation completes; the passed value is true if the record exists or false otherwise.

Source:
Returns:

If no callback function is passed, the function returns a Promise that resolves to true if the record exists or false otherwise.

Type
Promise
Example
const Aerospike = require('aerospike')

let key = new Aerospike.Key('test', 'demo', 'key1')
Aerospike.connect()
  .then(client => {
    return client.exists(key)
      .then(exists => console.info('Key "%s" exists: %s', key.key, exists))
      .then(() => client.close())
      .catch(error => {
        console.error('Error checking existance of key:', error)
        client.close()
      })
  })
  .catch(error => {
    console.error('Error connecting to cluster:', error)
  })

get(key [, policy] [, callback])

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

Parameters:
Name Type Argument Description
key Key

The key used to locate the record in the cluster.

policy ReadPolicy <optional>

The Read Policy to use for this operation.

callback recordCallback <optional>

The function to call when the operation completes with the results of the operation; if no callback function is provided, the method returns a Promise instead.

Source:
Returns:

If no callback function is passed, the function returns a Promise that resolves to a Record.

Type
Promise
Example
var key = new Key('test', 'demo', 'key1')

client.get(key, (error, record) => {
  if (error) {
    // handle failure
  } else {
    // handle success
  }
})

getNodes()

Returns a list of all cluster nodes known to the client.

Since:
  • v2.6.0
Source:
Returns:

List of node objects

Type
Array.<{name: string, address: string}>
Example
const Aerospike = require('aerospike')
Aerospike.connect((error, client) => {
  if (err) throw err
  console.log(client.getNodes()) // [ { name: 'BB9EB63B2005452', address: '127.0.0.1:3000' },
                                 //   { name: 'C1DEB63B2005452', address: '127.0.0.1:3100' } ]
  client.close()
})

incr(key, bins [, metadata] [, policy] [, callback])

Alias for Client#add.

Parameters:
Name Type Argument Description
key Key

The key of the record.

bins Array.<Object>

The key-value mapping of bin names and the corresponding values to use to increment the bin values with.

metadata Object <optional>

Meta data.

policy OperatePolicy <optional>

The Operate Policy to use for this operation.

callback recordCallback <optional>

The function to call when the operation completes with the results of the operation.

Source:
Returns:
  • If no callback function is passed, the function returns a Promise that resolves to the results of the opertion.
Type
Promise

indexRemove(namespace, index [, policy] [, callback])

Removes the specified index.

Parameters:
Name Type Argument Description
namespace string

The namespace on which the index was created.

index string

The name of the index.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback doneCallback <optional>

The function to call when the operation completes with the result of the operation.

Source:
Returns:

If no callback function is passed, the function returns a Promise that resolves once the operation completes.

Type
Promise
Example
client.indexRemove('test', 'index', function (error) {
  if (error) {
    // handle failure
  } else {
    // handle success
  }
});

info(request, host [, policy] [, callback])

Sends an info query to a specific cluster node.

The request parameter is a string representing an info request. If null, the cluster host will send all available info.

Please refer to the Info Command Reference for a list of all available info commands.

Parameters:
Name Type Argument Description
request String <nullable>

The info request to send.

host Object

The address of the cluster host to send the request to.

Properties
Name Type Argument Default Description
addr string

The IP address or host name of the host.

port number <optional>
3000

The port of the host.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback infoCallback <optional>

The function to call when an info response from a cluster host is received.

Deprecated:
Source:
See:
Example

Sending a 'statistics' info query to a single host

client.info('statistics', {addr: '127.0.0.1', port: 3000}, function (error, response) {
  if (error) {
    // handle failure
  } else {
    // handle success
  }
})

infoAll( [request] [, policy] [, callback])

Sends an info query to all nodes in the cluster and collects the results.

The request parameter is a string representing an info request. If it is not specified, the cluster hosts will send all available info.

Parameters:
Name Type Argument Description
request string <optional>

The info request to send.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback infoCallback <optional>

The function to call once all nodes have returned a response to the info command; if no callback function is provided, the method returns a Promise instead.

Since:
  • v2.3.0
Source:
See:
Example

Sending info command to whole cluster

client.infoAll('statistics', function (error, responses) {
  if (error) {
    // handle failure
  } else {
    responses.forEach((function (info) {
      // handle response
    })
  }
})

infoAny( [request] [, policy] [, callback])

Sends an info query to a single, randomly selected cluster node.

The request parameter is a string representing an info request. If it is not specified, the cluster host(s) will send all available info.

Parameters:
Name Type Argument Description
request string <optional>

The info request to send.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback infoCallback <optional>

The function to call once the node returns the response to the info command; if no callback function is provided, the method returns a Promise instead.

Since:
  • v2.4.0
Source:
See:
Example

Sending 'statistics' info command to random cluster node

client.infoAny('statistics', function (error, response) {
  if (error) {
    // handle failure
  } else {
    // handle success
  }
})

infoNode(request, node [, policy] [, callback])

Sends an info query to a single node in the cluster.

The request parameter is a string representing an info request. If it is not specified, the cluster host(s) will send all available info.

Parameters:
Name Type Argument Description
request string <nullable>

The info request to send.

node object

The node to send the request to.

Properties
Name Type Description
name string

The node name.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback infoCallback <optional>

The function to call once the node returns the response to the info command; if no callback function is provided, the method returns a Promise instead.

Since:
  • v3.11.0
Source:
See:
Example

Sending 'statistics' info command to specific cluster node

const node = client.getNodes().pop()
client.infoNode('statistics', node).then(info => {
  // process info
})

isConnected( [checkTenderErrors])

Is client connected to any server nodes.

Parameters:
Name Type Argument Default Description
checkTenderErrors boolean <optional>
true

Whether to consider a server node connection that has had 5 consecutive info request failures during cluster tender.

Since:
  • v2.0
Source:
Returns:

true if the client is currently connected to any server nodes.

Type
boolean

operate(key, operations [, metadata] [, policy] [, callback])

Performs multiple operations on a single record.

Operations can be created using the methods in one of the following modules:

Parameters:
Name Type Argument Description
key Key

The key of the record.

operations Array.<module:aerospike/operations~Operation>

List of operations to perform on the record.

metadata Object <optional>

Meta data.

policy OperatePolicy <optional>

The Operate Policy to use for this operation.

callback recordCallback <optional>

The function to call when the operation completes with the results of the operation; if no callback function is provided, the method returns a Promise instead.

Source:
Example
const Aerospike = require('aerospike')
const op = Aerospike.operations

var key = new Aerospike.Key('test', 'demo', 'mykey1')
var ops = [
  op.append('a', 'xyz'),
  op.incr('b', 10),
  op.read('b')
]

Aerospike.connect(function (error, client) {
  client.operate(key, ops, function (error, record) {
    if (error) {
      // handle failure
    } else {
      console.log('b', record.bins['b']) // value of 'b' returned by the `read` operation
    }
  })
  client.close()
})

put(key, bins [, meta] [, policy], callback)

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 null.

Note: The client does not perform any automatic data type conversions. Attempting to write an unsupported data type (e.g. boolean) into a record bin will cause an error to be returned. Setting an undefined value will also cause an error.

Parameters:
Name Type Argument Description
key Key

The key of the record.

bins object

A record object used for specifying the fields to store.

meta object <optional>

Meta data.

policy WritePolicy <optional>

The Write Policy to use for this operation.

callback writeCallback

The function to call when the operation completes with the result of the operation.

Source:
Example
const Key = Aerospike.Key

var key = new Key('test', 'demo', 'key1')
var rec = {
  a: 'xyz',
  b: 123
}

client.put(key, rec, function (error, key) {
  if (error) {
    // handle failure
  } else {
    // handle success
  }
})

query(ns, set [, options])

Creates a new Query instance, which is used to define query in the database.

Parameters:
Name Type Argument Description
ns string

The namespace to be queried.

set string

The set on which the query is to be executed.

options object <optional>

Query parameters. See Query constructor for details.

Source:
See:
Example
const filter = Aerospike.filter

var statement = {}
statment.filters: [filter.equal('color', 'blue')]

var query = client.query(ns, set, statment)
var stream = query.execute()

remove(key [, policy], callback)

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

Parameters:
Name Type Argument Description
key Key

The key of the record.

policy RemovePolicy <optional>

The Remove Policy to use for this operation.

callback writeCallback

The function to call when the operation completes with the results of the operation.

Source:
Example
const Key = Aerospike.Key
client.remove(new Key('test', 'demo', 'key1'), function (error, key) {
  if (error) {
    // handle failure
  } else {
    // handle success
  }
})

removeSeedHost(hostname [, port])

Removes a seed host from the cluster.

Parameters:
Name Type Argument Default Description
hostname String

Hostname/IP address of the seed host

port Number <optional>
3000

Port number; defaults to Config#port or 3000.

Since:
  • v2.6.0
Source:

scan(ns, set [, options])

Creates a new Scan instance in order to execute a database scan using the Scan API.

Parameters:
Name Type Argument Description
ns string

The namescape.

set string

The name of a set.

options object <optional>

Scan parameters. See Scan constructor for details.

Since:
  • v2.0
Source:
See:
  • Scan constructor for options that can be used to initialize a new instance.

select(key, bins [, policy] [, callback])

Retrieves selected bins for a record of given key from the database cluster.

Parameters:
Name Type Argument Description
key Key

The key of the record.

bins Array.<string>

A list of bin names for the bins to be returned.

policy ReadPolicy <optional>

The Read Policy to use for this operation.

callback recordCallback <optional>

The function to call when the operation completes with the results of the operation; if no callback function is provided, the method returns a Promise instead.

Source:
Example
var key = new Key('test', 'demo', 'key1')

client.select(key, ['name', 'age'], (error, record) => {
  if (error) {
    // handle failure
  } else {
    // handle success
  }
})

stats()

Returns runtime stats about the client instance.

Since:
  • v3.8.0
Source:
Returns:

client stats

Type
ClientStats
Example
require('aerospike').connect().then(client => {
  const stats = client.stats()
  console.info(stats) // => { commands: { inFlight: 0, queued: 0 },
                      //      nodes:
                      //       [ { name: 'BB94DC08D270008',
                      //           syncConnections: { inPool: 1, inUse: 0 },
                      //           asyncConnections: { inPool: 0, inUse: 0 } },
                      //         { name: 'C1D4DC08D270008',
                      //           syncConnections: { inPool: 0, inUse: 0 },
                      //           asyncConnections: { inPool: 0, inUse: 0 } } ] }
  client.close()
})

truncate(ns, set, before_nanos [, policy], callback)

Removes records in specified namespace/set efficiently.

This method is many orders of magnitude faster than deleting records one at a time. It requires Aerospike Server version 3.12 or later.

Parameters:
Name Type Argument Description
ns string

Required namespace.

set string

Optional set name. Set to null to delete all sets in namespace.

before_nanos number

Optionally delete records before given last update time. Units are in nanoseconds since unix epoch (1970-01-01). If specified, the value must be before the current time. Pass in 0 to delete all records in namespace/set regardless of last udpate time.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback doneCallback

The function to call when the operation completes with the result of the operation.

Source:
See:

udfRegister(path [, udfType] [, policy], callback)

Registers a UDF module with the database cluster.

This method loads a Lua script from the local filesystem into the Aerospike database cluster and registers it for use as a UDF module. The client uploads the module to a single cluster node. It then gets distributed within the whole cluster automatically. The callback function is called once the initial upload into the cluster has completed (or if an error occurred during the upload). One of the callback parameters is a UdfJob instance that can be used to verify that the module has been registered successfully on the entire cluster.

Parameters:
Name Type Argument Description
path string

The file path to the Lua script to load into the server.

udfType number <optional>

Language of the UDF script. Lua is the default and only supported scripting language for UDF modules at the moment; ref. module:aerospike.language.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback jobCallback

The function to call when the operation completes with the result of the operation.

Source:
Example
const Aerospike = require('aerospike')

Aerospike.connect((error, client) => {
  if (error) throw error

  var path = './udf/my_module.lua'
  client.udfRegister(path, (error, job) => {
    if (error) throw error

    job.waitUntilDone(100, (error) => {
      if (error) throw error

      // UDF module was successfully registered on all cluster nodes

      client.close()
    })
  })
})

udfRemove(udfModule [, policy], callback)

Removes a UDF module from the cluster.

The info command to deregister the UDF module is sent to a single cluster node by the client. It then gets distributed within the whole cluster automatically. The callback function is called once the initial info command has succeeded (or if an error occurred). One of the callback parameters is a UdfJob instance that can be used to verify that the module has been removed successfully from the entire cluster.

For server versions 4.5.0 and before, trying to delete an UDF module that does not exist on the server, will return an error. Starting with server version 4.5.1, the server no longer returns an error and the command will succeed.

Parameters:
Name Type Argument Description
udfModule string

The basename of the UDF module, without the local pathname but including the file extension (".lua").

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback jobCallback

The function to call when the operation completes which the result of the operation.

Source:
Example
const Aerospike = require('aerospike')

Aerospike.connect((error, client) => {
  if (error) throw error

  var module = 'my_module.lua'
  client.udfRemove(module, (error, job) => {
    if (error) throw error

    job.waitUntilDone(100, (error) => {
      if (error) throw error

      // UDF module was successfully removed from all cluster nodes

      client.close()
    })
  })
})

Events


disconnected

Since:
  • v2.7.0
Source:
Example
const Aerospike = require('aerospike')

Aerospike.connect((error, client) => {
  if (error) throw error

  client.on('disconnected', () => {
    console.warn('Client got disconnected from cluster')
  })

 // client is now ready to accept commands, e.g. get/put/...

})

event

Instead of adding listeners for the nodeAdded, nodeRemoved and disconnected events, applications can also subscribe to the event event to receive callbacks for any kind of cluster event.

Type: object
Properties:
Name Type Argument Description
name string

Name of the event.

nodeName string <optional>

Name of the cluster node that triggered this event.

nodeAddress string <optional>

IP address & port of the cluster node that triggered this event.

Since:
  • v2.7.0
Source:
Example
const Aerospike = require('aerospike')

Aerospike.connect((error, client) => {
  if (error) throw error

  client.on('event', (event) => {
    var now = new Date().toUTCString()
    console.info(now, event.name, event.nodeName)  // Example output:
                 // Thu, 13 Jul 2017 06:47:35 GMT nodeAdded BB94DC07D270009
                 // Thu, 13 Jul 2017 06:47:35 GMT nodeAdded C1D4DC0AD270002
                 // Thu, 13 Jul 2017 06:48:52 GMT nodeRemoved C1D4DC0AD270002
                 // Thu, 13 Jul 2017 06:49:08 GMT nodeRemoved BB94DC07D270009
                 // Thu, 13 Jul 2017 06:49:08 GMT disconnected
  })

 // client is now ready to accept commands, e.g. get/put/...

})

nodeAdded

Type: object
Properties:
Name Type Description
nodeName string

Name of the cluster node that triggered this event.

nodeAddress string

IP address & port of the cluster node that triggered this event.

Since:
  • v2.7.0
Source:

nodeRemoved

Type: object
Properties:
Name Type Description
nodeName string

Name of the cluster node that triggered this event.

nodeAddress string

IP address & port of the cluster node that triggered this event.

Since:
  • v2.7.0
Source: