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
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
const config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    apply : new Aerospike.ApplyPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

var key = new Aerospike.Key('test', 'demo', 'value')

var udfArgs = {
  module: 'my_udf_module',
  funcname: 'my_udf_function',
  args: ['abc', 123, 4.5]
}

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

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

batchApply(records, udf [, batchPolicy] [, batchApplyPolicy] [, callback])

Apply UDF (user defined function) on multiple keys.

This method allows multiple sub-commands for each key in the batch. This method requires server >= 6.0.0.

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

Record List of batch sub-commands to perform.

records[].type number

Record#type Batch type.

records[].key Key

Record Key.

udf Array.<object>

Server UDF module/function and argList to apply.

batchPolicy BatchPolicy <optional>

The Batch Policy to use for this operation.

batchApplyPolicy BatchApplyPolicy <optional>

UDF policy configuration parameters.

callback batchRecordsCallback <optional>

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

Since:
  • v5.0.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')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
const config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    batchApply : new Aerospike.BatchApplyPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

const batchType = Aerospike.batchType
var batchRecords = [
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key1'),
    bins: ['i', 's'] },
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key2'),
    readAllBins: true },
  { type: batchType.BATCH_APPLY,
    key: new Aerospike.Key('test', 'demo', 'key4'),
    policy: new Aerospike.BatchApplyPolicy({
        filterExpression: exp.eq(exp.binInt('i'), exp.int(37)),
        key: Aerospike.policy.key.SEND,
        commitLevel: Aerospike.policy.commitLevel.ALL,
        durableDelete: true
      }),
    udf: {
         module: 'udf',
         funcname: 'function1',
         args: [[1, 2, 3]]
         }
  },
  { type: batchType.BATCH_APPLY,
    key: new Aerospike.Key('test', 'demo', 'key5'),
    policy: new Aerospike.BatchApplyPolicy({
        filterExpression: exp.eq(exp.binInt('i'), exp.int(37)),
        key: Aerospike.policy.key.SEND,
        commitLevel: Aerospike.policy.commitLevel.ALL,
        durableDelete: true
      }),
    udf: {
         module: 'udf',
         funcname: 'function2',
         args: [[1, 2, 3]]
         }
   }
]
Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.batchApply(batchRecords, (error, results) => {
    if (error) throw error
    results.forEach(function (result) {
      console.log(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
const Aerospike = require('aerospike')
const Key = Aerospike.Key

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

var keys = [
  new Key('test', 'demo', 'key1'),
  new Key('test', 'demo', 'key2'),
  new Key('test', 'demo', 'key3')
]

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.batchExists(keys, (error, results) => {
    if (error) throw error
    results.forEach((result) => {
      switch (result.status) {
        case Aerospike.status.OK:
          console.log("Record found")
          break
        case Aerospike.status.ERR_RECORD_NOT_FOUND:
          console.log("Record not found")
          break
        default:
          // error while reading record
          console.log("Other error")
          break
      }
    })
    client.close()
  })
})

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
const Aerospike = require('aerospike')
const Key = Aerospike.Key

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

var keys = [
  new Key('test', 'demo', 'key1'),
  new Key('test', 'demo', 'key2'),
  new Key('test', 'demo', 'key3')
]

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.batchGet(keys, (error, results) => {
    if (error) throw error
    results.forEach((result) => {
      switch (result.status) {
        case Aerospike.status.OK:
          console.log("Record found")
          break
        case Aerospike.status.ERR_RECORD_NOT_FOUND:
          console.log("Record not found")
          break
        default:
          // error while reading record
          console.log("Other error")
          break
      }
    })
    client.close()
  })
})

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 server >= 3.6.0.

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

Record List of keys and bins to retrieve.

records[].type number

Record#type Batch type.

records[].key Key

Record Key.

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

List of bins to retrieve.

records[].readAllBins 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')
const batchType = Aerospike.batchType
const op = Aerospike.operations

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

var batchRecords = [
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key1'), bins: ['i', 's'] },
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key2'), readAllBins: true },
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key3'),
    ops:[
         op.read('blob-bin')
        ]}
]
Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.batchRead(batchRecords, (error, results) => {
    if (error) throw error
    results.forEach((result) => {
      switch (result.status) {
        case Aerospike.status.OK:
          console.log("Record found")
          break
        case Aerospike.status.ERR_RECORD_NOT_FOUND:
          console.log("Record not found")
          break
        default:
          // error while reading record
          console.log("Other error")
          break
      }
    })
    client.close()
  })
})

batchRemove(keys [, batchPolicy] [, batchRemovePolicy] [, callback])

Remove multiple records.

This method removes the specified records from the database. This method requires server >= 6.0.0.

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

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

batchPolicy BatchPolicy <optional>

The Batch Policy to use for this operation.

batchRemovePolicy BatchRemovePolicy <optional>

Remove policy configuration parameters.

callback batchRecordsCallback <optional>

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

Since:
  • v5.0.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')
const batchType = Aerospike.batchType
const exp = Aerospike.exp

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}
var batchRecords = [
  { type: batchType.BATCH_REMOVE,
    key: new Aerospike.Key('test', 'demo', 'key5'),
    policy: new Aerospike.BatchRemovePolicy({
        filterExpression: exp.eq(exp.binInt('i'), exp.int(37)),
        key: Aerospike.policy.key.SEND,
        commitLevel: Aerospike.policy.commitLevel.ALL,
        gen: Aerospike.policy.gen.EQ,
        durableDelete: true
      }),
   },
  { type: batchType.BATCH_REMOVE,
    key: new Aerospike.Key('test', 'demo', 'key6'),
    policy: new Aerospike.BatchRemovePolicy({
        filterExpression: exp.eq(exp.binInt('i'), exp.int(37)),
        key: Aerospike.policy.key.SEND,
        commitLevel: Aerospike.policy.commitLevel.ALL,
        gen: Aerospike.policy.gen.EQ,
        durableDelete: true
      }),
   }
]

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.batchRemove(batchRecords, (error, results) => {
    if (error) throw error
    results.forEach((result) => {
      switch (result.status) {
        case Aerospike.status.OK:
          console.log("Record found")
          break
        case Aerospike.status.ERR_RECORD_NOT_FOUND:
          console.log("Record not found")
          break
        default:
          // error while reading record
          console.log("Other error")
          break
      }
    })
    client.close()
  })
})

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
const Aerospike = require('aerospike')
const Key = Aerospike.Key

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

var keys = [
  new Key('test', 'demo', 'key1'),
  new Key('test', 'demo', 'key2'),
  new Key('test', 'demo', 'key3')
]

var bins = ['s', 'i']

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.batchSelect(keys, bins, (error, results) => {
    if (error) throw error
    results.forEach((result) => {
      switch (result.status) {
        case Aerospike.status.OK:
          console.log("Record found")
          break
        case Aerospike.status.ERR_RECORD_NOT_FOUND:
          console.log("Record not found")
          break
        default:
          // error while reading record
          console.log("Other error")
          break
      }
    })
    client.close()
  })
})

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

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

This method allows different sub-commands for each key in the batch. This method requires server >= 6.0.0.

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

Record List of batch sub-commands to perform.

records[].type number

Record#type Batch type.

records[].key Key

Record Key.

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:
  • v5.0.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')
const batchType = Aerospike.batchType
const op = Aerospike.operations
const GeoJSON = Aerospike.GeoJSON
const exp = Aerospike.exp

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

var batchRecords = [
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key1'),
    bins: ['i', 's'] },
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key2'),
    readAllBins: true },
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key3'),
    ops:[
         op.read('blob')
        ]},
  { type: batchType.BATCH_WRITE,
    key: new Aerospike.Key('test', 'demo', 'key4'),
    ops:[
         op.write('geo', new GeoJSON({ type: 'Point', coordinates: [123.456, 1.308] })),
         op.write('blob', Buffer.from('bar'))
        ],
    policy: new Aerospike.BatchWritePolicy({
        filterExpression: exp.eq(exp.binInt('i'), exp.int(37)),
        key: Aerospike.policy.key.SEND,
        commitLevel: Aerospike.policy.commitLevel.ALL,
        gen: Aerospike.policy.gen.EQ,
        exists: Aerospike.policy.exists.CREATE,
        durableDelete: true
      }),
  { type: batchType.BATCH_REMOVE,
    key: new Aerospike.Key('test', 'demo', 'key5'),
    policy: new Aerospike.BatchRemovePolicy({
        filterExpression: exp.eq(exp.binInt('i'), exp.int(37)),
        key: Aerospike.policy.key.SEND,
        commitLevel: Aerospike.policy.commitLevel.ALL,
        gen: Aerospike.policy.gen.EQ,
        durableDelete: true
      }),
   }
]

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.batchWrite(batchRecords, (error, results) => {
    if (error) throw error
    results.forEach((result) => {
      switch (result.status) {
        case Aerospike.status.OK:
          console.log("Record found")
          break
        case Aerospike.status.ERR_RECORD_NOT_FOUND:
          console.log("Record not found")
          break
        default:
          // error while reading record
          console.log("Other error")
          break
      }
    })
    client.close()
  })
})

close( [releaseEventLoop])

Closes the client connection to the cluster.

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

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

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

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}
Aerospike.connect(config)
  .then(client => {
    // client is ready to accept commands
    console.log("Connected. Now Closing Connection.")
    client.close()
  })
  .catch(error => {
   client.close()
    console.error('Failed to connect to cluster: %s', error.message)
  })

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

A connection established using callback function.

const Aerospike = require('aerospike')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
  if (error) {
    console.error('Failed to connect to cluster: %s', error.message)
    process.exit()
  } else {
    // client is ready to accept commands
    console.log("Connected. Now closing connection.")
    client.close()
  }
})

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')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (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('SI %s on %s was created successfully', indexName, binName)
    client.close()
  })
})

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

Creates a secondary index (SI).

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')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (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({ timeout: 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('SI %s on %s was created successfully', indexName, binName)
      client.close()
    })
  })
})

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

Creates a SI 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')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (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('SI %s on %s was created successfully', indexName, binName)
    client.close()
  })
})

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

Creates a SI 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')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (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('SI %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')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  policies: {
    read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

let key = new Aerospike.Key('test', 'demo', 'key1')
Aerospike.connect(config)
  .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
const Aerospike = require('aerospike')
var key = new Aerospike.Key('test', 'demo', 'key1')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  policies: {
    read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.get(key, (error, record) => {
    if (error) throw error
    console.log(record)
    client.close()
  })
})

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')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  console.log(client.getNodes()) // [ { name: 'SAMPLEADDRESS', address: 'SAMPLENAME' }, ...]
  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
const Aerospike = require('aerospike')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
  client.indexRemove('location', 'locationIndex', (error) => {
    if (error) throw error
    client.close()
  })
})

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 it is not specified, a default set of info values will be returned.

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

const Aerospike = require('aerospike')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.info('statistics', {addr: '192.168.33.10', port: 3000}, (error, response) => {
    if (error) throw error
    console.log(response)
    client.close()
  })
})

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, a default set of info values will be returned.

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

const Aerospike = require('aerospike')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.infoAll('statistics', (error, response) => {
    if (error) throw error
    console.log(response)
    client.close()
  })
})

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, a default set of info values will be returned.

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

const Aerospike = require('aerospike')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.infoAny('statistics', (error, response) => {
    if (error) throw error
    console.log(response)
    client.close()
  })
})

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, a default set of info values will be returned.

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 Aerospike = require('aerospike')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  const node = client.getNodes().pop()
  client.infoNode('statistics', node, (error, response) => {
    if (error) throw error
    console.log(response)
    client.close()
  })
})

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
const key = new Aerospike.Key('test', 'demo', 'mykey1')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    operate : new Aerospike.OperatePolicy({socketTimeout : 0, totalTimeout : 0}),
    write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}
var ops = [
  op.append('a', 'xyz'),
  op.incr('b', 10),
  op.read('b')
]

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.put(key, { a: 'abc', b: 42 }, (error) => {
    if (error) throw error
    client.operate(key, ops, (error, record) => {
      if (error) throw error
      console.log(record.bins) // => { b: 52 }
      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 <optional>

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

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

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
    write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

const Key = Aerospike.Key

var key = new Key('test', 'demo', 'key1')
var bins = {
  a: 'xyz',
  b: 123
}
Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.put(key, bins, (error) => {
    if (error) throw error
    client.get(key, (error, record) => {
      if (error) throw error
      console.log(record)
      client.close()
    })
  })
})

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 <optional>

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

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

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    remove : new Aerospike.RemovePolicy({socketTimeout : 0, totalTimeout : 0}),
    write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

const Key = Aerospike.Key

var key = new Key('test', 'demo', 'key1')
var bins = {
  a: 'xyz',
  b: 123
}
Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.put(key, bins, (error) => {
    if (error) throw error
    client.remove(key, (error) => {
      if (error) throw error
      console.log("Record removed")
      client.close()
    })
  })
})

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
const Aerospike = require('aerospike')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
  // Timeouts disabled, latency dependent on server location. Configure as needed.
  policies: {
    read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
    write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

const Key = Aerospike.Key

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

var bins = {
  a: 'xyz',
  b: 123
}

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  client.put(key, bins, (error) => {
    if (error) throw error
    client.select(key, ['a', 'b'], (error, record) => {
      if (error) throw error
      console.log(record)
      client.close()
    })
  })
})

stats()

Returns runtime stats about the client instance.

Since:
  • v3.8.0
Source:
Returns:

client stats

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

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

Aerospike.connect(config, (error, client) => {
  if (error) throw error
  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 server 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 <optional>

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 <optional>

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 <optional>

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')

// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
  hosts: '192.168.33.10:3000',
}

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

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

  // client is now ready to accept commands, e.g. get/put/...
  client.close()
})

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.log(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/...
  client.close()
})

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: