Client

Client

Aerospike client

Constructor

new Client(config)

Construct a new Aerospike client instance.

Source:
Parameters:
Name Type Description
config Config

Configuration used to initialize the client.

Members

captureStackTraces :boolean

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

Description:
  • 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).

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

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

config :Config

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

Source:
Type:

Methods

addSeedHost(hostname, portopt)

Adds a seed host to the cluster.

Source:
Since:
  • v2.6.0
Parameters:
Name Type Attributes Default Description
hostname String

Hostname/IP address of the new seed host

port Number <optional>
3000

Port number; defaults to Config#port or 3000.

apply(key, udfArgs, policyopt, callbackopt) → (nullable) {Promise}

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

Description:
  • 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.

Source:
Since:
  • v2.0
See:
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)
  })
})
Parameters:
Name Type Attributes 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.

Returns:

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

Type
Promise

batchApply(keys, udf, batchPolicyopt, batchApplyPolicyopt, callbackopt) → (nullable) {Promise}

Apply UDF (user defined function) on multiple keys.

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

Source:
Since:
  • v5.0.0
Examples

Simple batchApply example

const Aerospike = require('aerospike')
var path = require('path');

// 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: {
    batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
  }
}

// This must be a path to a UDF file
const scriptLocation = path.join(__dirname, 'udf-list.lua')

;(async () => {
    // Establishes a connection to the server
    let client = await Aerospike.connect(config);

    // Place some records for demonstration
    await client.put(new Aerospike.Key('test', 'demo', 'key1'), {example: 30})
    await client.put(new Aerospike.Key('test', 'demo', 'key2'), {example: 35})
    await client.udfRegister(scriptLocation)

    // Execute the UDF
    let batchResult = await client.batchApply([new Aerospike.Key('test', 'demo', 'key1'), new Aerospike.Key('test', 'demo', 'key2')],
        {
            module: 'udf-list',
            funcname: 'updateRecord',
            args: ['example', 45]
        }
    );

    // Access the records
    batchResult.forEach(result => {
        // Do something
        console.info("New value of example bin is %o \n", result.record.bins.SUCCESS);
    });

    //Additional verfication
    let result = await client.get(new Aerospike.Key('test', 'demo', 'key1'))
    console.log(result.bins) // { example: 45 }
    result = await client.get(new Aerospike.Key('test', 'demo', 'key2'))
    console.log(result.bins) // { example: 45 }

    // Close the connection to the server
    await client.close();
})(); *

Simple lua script to be used in example above

function updateRecord(rec, binName, binValue)
  rec[binName] = binValue
  aerospike:update(rec)
  return binValue
end
Parameters:
Name Type Attributes Description
keys Array.<Key>

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

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.

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

batchExists(keys, policyopt, callbackopt) → (nullable) {Promise}

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

Source:
Deprecated:
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')
]

;(async () => {
    // Establishes a connection to the server
    let client = await Aerospike.connect(config);

    // Place some records for demonstration
    await client.put(keys[0], {example: 30})
    await client.put(keys[1], {example: 35})
    await client.put(keys[2], {example: 40})

    let results = await client.batchExists(keys)
    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
        }
    })

    // Close the connection to the server
    await client.close();
})();
Parameters:
Name Type Attributes 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.

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

batchGet(keys, policyopt, callbackopt) → (nullable) {Promise}

Reads a batch of records from the database cluster.

Source:
Deprecated:
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')
]

;(async () => {
    // Establishes a connection to the server
    let client = await Aerospike.connect(config);

    // Place some records for demonstration
    await client.put(keys[0], {example: 30})
    await client.put(keys[1], {example: 35})
    await client.put(keys[2], {example: 40})

    let results = await client.batchGet(keys)
    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
        }
    })

    // Close the connection to the server
    await client.close();
})();
Parameters:
Name Type Attributes 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.

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

batchRead(records, policyopt, callbackopt) → (nullable) {Promise}

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

Description:
  • This method allows different namespaces/bins to be requested for each key in the batch. This method requires server >= 3.6.0.

Source:
Since:
  • v2.0
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: ['example'] },
  { 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('example')
        ]},
  { type: batchType.BATCH_READ,
    key: new Aerospike.Key('test', 'demo', 'key4')}
]


;(async () => {
    // Establishes a connection to the server
    let client = await Aerospike.connect(config);

    // Place some records for demonstration
    await client.put(batchRecords[0].key, {example: 30})
    await client.put(batchRecords[1].key, {example: 35})
    await client.put(batchRecords[2].key, {example: 40})
    await client.put(batchRecords[3].key, {example: 45})

    let results = await client.batchRead(batchRecords)
    results.forEach((result) => {

        switch (result.status) {
            case Aerospike.status.OK:
                console.log("Record found")
                // Since the fourth record didn't specify bins to read,
                // the fourth record will return no bins, eventhough the batchRead succeeded.
                console.log(result.record.bins)
                break
            case Aerospike.status.ERR_RECORD_NOT_FOUND:
                console.log("Record not found")
                break
            default:
                // error while reading record
                console.log("Other error")
                break
        }
    })
    // Close the connection to the server
    await client.close();
})();
Parameters:
Name Type Attributes Description
records Array.<object>

Record List of keys and bins to retrieve.

Properties
Name Type Attributes Description
type number

Record#type Batch type.

key Key

Record Key.

bins Array.<string> <optional>

List of bins to retrieve.

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

ops Array.<Object> <optional>

List of operations

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.

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

batchRemove(keys, batchPolicyopt, batchRemovePolicyopt, callbackopt) → (nullable) {Promise}

Remove multiple records.

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

Source:
Since:
  • v5.0.0
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 keys = [
    new Aerospike.Key('test', 'demo', 'key1'),
    new Aerospike.Key('test', 'demo', 'key2'),
    new Aerospike.Key('test', 'demo', 'key3')
]


;(async () => {
    // Establishes a connection to the server
    let client = await Aerospike.connect(config);

    // Place some records for demonstration
    await client.put(keys[0], {example: 30})
    await client.put(keys[1], {example: 35})

    let results = await client.batchRemove(keys)
    results.forEach((result) => {
        switch (result.status) {
            case Aerospike.status.OK:
                console.log("Record deleted")
                break
            case Aerospike.status.ERR_RECORD_NOT_FOUND:
                console.log("Record not found")
                break
            default:
                // error while reading record
                console.log("Other error")
                break
        }
    })
    // Close the connection to the server
    await client.close();
})();
Parameters:
Name Type Attributes 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.

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

batchSelect(keys, bins, policyopt, callbackopt) → (nullable) {Promise}

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

Source:
Deprecated:
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 keys = [
    new Aerospike.Key('test', 'demo', 'key1'),
    new Aerospike.Key('test', 'demo', 'key2'),
    new Aerospike.Key('test', 'demo', 'key3')
]

var bins = ['example', 'user']

;(async () => {
    // Establishes a connection to the server
    let client = await Aerospike.connect(config);

    // Place some records for demonstration
    await client.put(keys[0], {example: 30, user: 'Doug', extra: 'unused'})
    await client.put(keys[1], {example: 35})

    let results = await client.batchSelect(keys, bins)
    results.forEach((result) => {
        switch (result.status) {
            case Aerospike.status.OK:
                console.log("Record found")
                // Since the fourth record didn't specify bins to read,
                // the fourth record will return no bins, eventhough the batchRead succeeded.
                console.log(result.record.bins)
                break
            case Aerospike.status.ERR_RECORD_NOT_FOUND:
                console.log("Record not found")
                break
            default:
                // error while reading record
                console.log("Other error")
                break
        }
    })
    // Close the connection to the server
    await client.close();
})();
Parameters:
Name Type Attributes 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.

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

batchWrite(records, policyopt, callbackopt) → (nullable) {Promise}

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

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

Source:
Since:
  • v5.0.0
Example
const Aerospike = require('aerospike')
const batchType = Aerospike.batchType
const Key = Aerospike.Key
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}),
  }
}

const batchRecords = [
    {
        type: batchType.BATCH_REMOVE,
        key: new Key("test", "demo", 'key1')
    },
    {
        type: batchType.BATCH_WRITE,
        key: new Key("test", "demo", 'key2'),
        ops: [
            op.write('example', 30),
            op.write('blob', Buffer.from('foo'))
        ],
        policy: new Aerospike.BatchWritePolicy({
            exists: Aerospike.policy.exists.IGNORE
        })
    },
    {
        type: batchType.BATCH_WRITE,
        key: new Key("test", "demo", 'key3'),
        ops: [
            op.write('example', 35),
            op.write('blob', Buffer.from('bar'))
        ],
        policy: new Aerospike.BatchWritePolicy({
            exists: Aerospike.policy.exists.IGNORE
        })
    }
]

const batchReadRecords = [
    {
        type: batchType.BATCH_READ,
        key: new Key("test", "demo", 'key1'),
        readAllBins: true
    },
    {
        type: batchType.BATCH_READ,
        key: new Key("test", "demo", 'key2'),
        readAllBins: true
    },
    {
        type: batchType.BATCH_READ,
        key: new Key("test", "demo", 'key3'),
        readAllBins: true
    }
]

;(async () => {
    // Establishes a connection to the server
    let client = await Aerospike.connect(config);

    // Place a record for demonstration
    await client.put(new Key("test", "demo", 'key1'), {example: 30, user: 'Doug', extra: 'unused'})

    let results = await client.batchWrite(batchRecords)
    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
        }
    })

    results = await client.batchWrite(batchRecords)
    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
        }
    })
    // Close the connection to the server
    await client.close();
})();
Parameters:
Name Type Attributes Description
records Array.<object>

Record List of batch sub-commands to perform.

Properties
Name Type Description
type number

Record#type Batch type.

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.

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

changePassword(user, password, policy)

Change a user's password.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    // User must be created before password is changed. See Client#createUser for an example.
    client.changePassword("khob", "TryTiger7!", ["Engineer"])
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
user String

User name for the password change.

password String

User password in clear-text format.

policy Object

Optional AdminPolicy.

close(releaseEventLoopopt)

Closes the client connection to the cluster.

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)
  })
Parameters:
Name Type Attributes Default Description
releaseEventLoop boolean <optional>
false

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

connect(callbackopt) → (nullable) {Promise}

Establishes the connection to the cluster.

Description:
  • 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.

Source:
See:
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()
  }
})
Parameters:
Name Type Attributes Description
callback connectCallback <optional>

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

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

contextFromBase64(serializedContext) → {CdtContext}

Returns a deserialized CDT Context

Source:
Since:
  • v5.6.0
Parameters:
Name Type Description
serializedContext String

base64 serialized CdtContext

Returns:

Deserialized CDT Context

Type
CdtContext

contextToBase64(context) → {String}

Returns a serialized CDT Context

Source:
Since:
  • v5.6.0
Example

How to use CDT context serialization

const Aerospike = require('aerospike');
const Context = Aerospike.cdt.Context
// Define host configuration
let config = {
  hosts: '192.168.33.10:3000',
  policies: {
    operate : new Aerospike.OperatePolicy({socketTimeout : 0, totalTimeout : 0}),
    write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
    read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0})
  }
}


Aerospike.connect(config, async (error, client) => {
  // Create a context
  let context = new Context().addMapKey('nested')

  // Create keys for records to be written
  let recordKey = new Aerospike.Key('test', 'demo', 'record')
  let contextKey = new Aerospike.Key('test', 'demo', 'context')

  // Put record with a CDT
  await client.put(recordKey, {exampleBin: {nested: {food: 'blueberry', drink: 'koolaid'}}})

  // Test the context with client.operate()
  var ops = [
    Aerospike.maps.getByKey('exampleBin', 'food', Aerospike.maps.returnType.KEY_VALUE).withContext(context)
  ]
  let results = await client.operate(recordKey, ops)
  console.log(results.bins.exampleBin) // [ 'food', 'blueberry' ]

  // Serialize CDT Context
  let serializedContext = client.contextToBase64(context)

  // Put record with bin containing the serialized record
  await client.put(contextKey, {context: serializedContext})

  // Get context when needed for operation
  let contextRecord = await client.get(contextKey)

  // Deserialize CDT Context
  context = client.contextFromBase64(contextRecord.bins.context)

  // Test the context with client.operate()
  ops = [
    Aerospike.maps.getByKey('exampleBin', 'food', Aerospike.maps.returnType.KEY_VALUE).withContext(context)
  ]
  results = await client.operate(recordKey, ops)
  console.log(results.bins.exampleBin) // [ 'food', 'blueberry' ]

  // Close the client
  client.close()
})
Parameters:
Name Type Description
context Object

CdtContext

Returns:

serialized context - base64 representation of the CDT Context

Type
String

createBlobIndex(options, policyopt, callbackopt) → (nullable) {Promise}

Creates a blob secondary index index.

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

Source:
See:
  • Client#indexCreate
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.createBlobIndex(options, function (error) {
    if (error) throw error
    console.info('SI %s on %s was created successfully', indexName, binName)
    client.close()
  })
})
Parameters:
Name Type Attributes Description
options Object

Options for creating the index.

Properties
Name Type Attributes 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.

Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise

createGeo2DSphereIndex(options, policyopt, callbackopt) → (nullable) {Promise}

Creates a geospatial secondary secondary index.

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

Source:
See:
  • Client#indexCreate
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()
  })
})
Parameters:
Name Type Attributes Description
options Object

Options for creating the index.

Properties
Name Type Attributes 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.

Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise

createIndex(options, policyopt, callbackopt) → (nullable) {Promise}

Creates a secondary index (SI).

Description:
  • 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.

Source:
Since:
  • v2.0
See:
Example
const Aerospike = require('aerospike')
const Context = Aerospike.cdt.Context

// 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 context = new Context().addListIndex(0)
  let options = { ns: namespace,
                  set: set,
                  bin: binName,
                  index: indexName,
                  type: indexType,
                  datatype: dataType,
                  context: context }

  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()
    })
  })
})
Parameters:
Name Type Attributes Description
options Object

Options for creating the index.

Properties
Name Type Attributes 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.

context Object

The CdtContext on which the index is to be created.

policy InfoPolicy <optional>

The Info Policy to use for this operation.

callback jobCallback <optional>

The function to call when the operation completes.

Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise

createIntegerIndex(options, policyopt, callbackopt) → (nullable) {Promise}

Creates a SI of type Integer.

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

Source:
See:
  • Client#indexCreate
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()
  })
})
Parameters:
Name Type Attributes Description
options Object

Options for creating the index.

Properties
Name Type Attributes 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.

Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise

createRole(roleName, privileges, policy, whitelist, readQuota, writeQuota)

Create user defined role with optional privileges, whitelist and read/write quotas. Quotas require server security configuration "enable-quotas" to be set to true.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configs can be used.
        user: 'admin',
        password: 'admin'
    })

    client.createRole("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.READ_WRITE), new Aerospike.admin.Privilege(Aerospike.privilegeCode.TRUNCATE)], null)
    // Must wait a short length of time of the role to be fully created.
    await wait(5)
    const role = await client.queryRole("Engineer", null)
    console.log(role)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
roleName String

role name

privileges Array.<Privilege>

List of privileges assigned to a role.

policy Object

Optional AdminPolicy.

whitelist Array.<String>

Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).

readQuota Number

Optional maximum reads per second limit, pass in zero for no limit.

writeQuota Number

Optional maximum writes per second limit, pass in zero for no limit.

createStringIndex(options, policyopt, callbackopt) → (nullable) {Promise}

Creates a SI of type String.

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

Source:
See:
  • Client#indexCreate
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()
  })
})
Parameters:
Name Type Attributes Description
options Object

Options for creating the index.

Properties
Name Type Attributes 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.

Returns:
  • If no callback function is passed, the function returns a Promise that will resolve to an IndexJob instance.
Type
Promise

createUser(user, password, roles, policy)

Create user with password and roles. Clear-text password will be hashed using bcrypt before sending to server.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    client.createUser("khob", "MightyMice55!", ["Engineer"])
    // Must wait a short length of time of the user to be fully created.
    await wait(5)
    const user = await client.queryUser("khob", null)
    console.log(user)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
user String

User name for the new user.

password String

User password in clear-text format.

roles Array.<String>

Optional array of role names. For more information on roles, see Role.

policy Object

Optional AdminPolicy.

dropRole(roleName, policy)

Drop user defined role.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    // A role must be created before a role can be dropped. See Client#createRole for an example.
    client.dropRole("Engineer")
    // Must wait a short length of time of the role to be fully dropped.
    await wait(5)
    let roles = await client.queryRoles()
    // 'Engineer' should no longer appear in the logged list of roles
    console.log(roles)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
roleName String

role name

policy Object

Optional AdminPolicy.

dropUser(user, policy)

Remove a User from cluster

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    // A user must be created before a user can be dropped. See Client#createUser for an example.
    client.dropUser("khob")
    // Must wait a short length of time of the role to be fully dropped.
    await wait(5)
    let users = await client.queryUsers()
    // 'khob' should no longer appear in the logged list of roles
    console.log(users)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
user String

User name to be dropped.

policy Object

Optional AdminPolicy.

exists(key, policyopt, callbackopt) → (nullable) {Promise}

Checks the existance of a record in the database cluster.

Source:
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)
  })
Parameters:
Name Type Attributes 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.

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

get(key, policyopt, callbackopt) → (nullable) {Promise}

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

Source:
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()
  })
})
Parameters:
Name Type Attributes 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.

Returns:

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

Type
Promise

getNodes() → {Array.<{name: string, address: string}>}

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

Source:
Since:
  • v2.6.0
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()
})
Returns:

List of node objects

Type
Array.<{name: string, address: string}>

grantPrivileges(roleName, privileges, policy)

Grant privileges to an user defined role.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    // A role must be created before privileges can be granted. See Client#createUser for an example.
    client.grantPrivileges("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.SINDEX_ADMIN)])
    // Must wait a short length of time for the privilege to be granted.
    await wait(5)
    let role = await client.queryRole("Engineer")
    console.log(role)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
roleName String

role name

privileges Array.<Privilege>

list of privileges assigned to a role.

policy Object

Optional AdminPolicy.

grantRoles(user, roles, policy)

Drop user defined role.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    // A user must be created before roles can be granted. See Client#createUser for an example.
    client.grantRoles("khob", ["Engineer"])
    // Must wait a short length of time for the role to be granted
    await wait(5)
    let user = await client.queryUser("khob")
    console.log(user)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
user String

User name for granted roles

roles Array.<String>

Optional array of role names. For more information on roles, see Role.

policy Object

Optional AdminPolicy.

incr(key, bins, metadataopt, policyopt, callbackopt) → (nullable) {Promise}

Alias for Client#add.

Source:
Parameters:
Name Type Attributes 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.

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, policyopt, callbackopt) → (nullable) {Promise}

Removes the specified index.

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) => {
  client.indexRemove('location', 'locationIndex', (error) => {
    if (error) throw error
    client.close()
  })
})
Parameters:
Name Type Attributes 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.

Returns:

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

Type
Promise

info(requestnullable, host, policyopt, callbackopt)

Sends an info query to a specific cluster node.

Description:
  • 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.

Source:
Deprecated:
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()
  })
})
Parameters:
Name Type Attributes 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 Attributes 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.

infoAll(requestopt, policyopt, callbackopt)

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

Description:
  • The request parameter is a string representing an info request. If it is not specified, a default set of info values will be returned.

Source:
Since:
  • v2.3.0
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()
  })
})
Parameters:
Name Type Attributes 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.

infoAny(requestopt, policyopt, callbackopt)

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

Description:
  • The request parameter is a string representing an info request. If it is not specified, a default set of info values will be returned.

Source:
Since:
  • v2.4.0
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()
  })
})
Parameters:
Name Type Attributes 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.

infoNode(requestnullable, node, policyopt, callbackopt)

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

Description:
  • The request parameter is a string representing an info request. If it is not specified, a default set of info values will be returned.

Source:
Since:
  • v3.11.0
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()
  })
})
Parameters:
Name Type Attributes 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.

isConnected(checkTenderErrorsopt) → {boolean}

Is client connected to any server nodes.

Source:
Since:
  • v2.0
Parameters:
Name Type Attributes Default Description
checkTenderErrors boolean <optional>
true

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

Returns:

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

Type
boolean

operate(key, operations, metadataopt, policyopt, callbackopt)

Performs multiple operations on a single record.

Description:
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()
    })
  })
})
Parameters:
Name Type Attributes 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.

put(key, bins, metaopt, policyopt, callbackopt)

Writes a record to the database cluster.

Description:
  • 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.

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()
    })
  })
})
Parameters:
Name Type Attributes 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.

query(ns, set, optionsopt)

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

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()
Parameters:
Name Type Attributes 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.

queryRole(roleName, policy) → {Role}

Retrieves an Role from the database.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    // A role must be created before a role can be queried. See Client#createRole for an example.
    let role = await client.queryRole("Engineer")
    console.log(role)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
roleName String

role name filter.

policy Object

Optional AdminPolicy.

Returns:
  • For more information on roles, see Role.
Type
Role

queryRoles(policy) → {Array.<Role>}

Retrieve all roles and role information from the database.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    let roles = await client.queryRoles()
    console.log(roles)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
policy Object

Optional AdminPolicy.

Returns:
  • For more information on roles, see Role.
Type
Array.<Role>

queryUser(user, policy) → {User}

Retrieves an User from the database.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    // A user must be created before a user can be queried. See Client#createUser for an example.
    let user = await client.queryUser("khob")
    console.log(user)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
user String

User name filter.

policy Object

Optional AdminPolicy.

Returns:
  • For more information on users, see User.
Type
User

queryUsers(policy) → {Array.<User>}

Retrieves All user and user information from the database.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })

    let users = await client.queryUsers()
    console.log(users)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
policy Object

Optional AdminPolicy.

Returns:
  • For more information on users, see User.
Type
Array.<User>

remove(key, policyopt, callbackopt)

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

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()
    })
  })
})
Parameters:
Name Type Attributes 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.

removeSeedHost(hostname, portopt)

Removes a seed host from the cluster.

Source:
Since:
  • v2.6.0
Parameters:
Name Type Attributes Default Description
hostname String

Hostname/IP address of the seed host

port Number <optional>
3000

Port number; defaults to Config#port or 3000.

revokePrivileges(roleName, privileges, policy)

Revoke privileges from an user defined role.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })
    // A role must be created before privileges can be revoked. See Client#createRole for an example.
    client.revokePrivileges("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.SINDEX_ADMIN)])
    // Must wait a short length of time for the privilege to be granted.
    await wait(5)
    let users = await client.queryRole("Engineer")
    console.log(users)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
roleName String

role name

privileges Array.<Privilege>

List of privileges assigned to a role.

policy Object

Optional AdminPolicy.

revokeRoles(user, roles, policy)

Remove roles from user's list of roles.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })
    // A user must be created before roles can be revoked. See Client#createUser for an example.
    client.revokeRoles("khob", ["Engineer"])
    // Must wait a short length of time for the privilege to be granted.
    await wait(5)
    let user = await client.queryUser("khob")
    console.log(user)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
user String

User name for revoked roles.

roles Array.<String>

Optional array of role names. For more information on roles, see Role.

policy Object

Optional AdminPolicy.

scan(ns, set, optionsopt)

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

Source:
Since:
  • v2.0
See:
  • Scan constructor for options that can be used to initialize a new instance.
Parameters:
Name Type Attributes Description
ns string

The namescape.

set string

The name of a set.

options object <optional>

Scan parameters. See Scan constructor for details.

select(key, bins, policyopt, callbackopt)

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

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()
    })
  })
})
Parameters:
Name Type Attributes 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.

setQuotas(roleName, readQuota, writeQuota, policy)

Set maximum reads/writes per second limits for a role. If a quota is zero, the limit is removed. Quotas require server security configuration "enable-quotas" to be set to true.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })
    // Quotas must be enabled in the server configurations for quotas to be set.
    client.setQuotas("Engineer", 200, 300)
    // Must wait a short length of time for the privilegee to be granted.
    await wait(5)
    let role = await client.queryRole("Engineer")
    console.log(role)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
roleName String

role name

readQuota Number

maximum reads per second limit, pass in zero for no limit.

writeQuota Number

maximum writes per second limit, pass in zero for no limit.

policy Object

Optional AdminPolicy.

setWhitelist(roleName, whitelist, policy)

Set IP address whitelist for a role. If whitelist is null or empty, remove existing whitelist from role.

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

function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

;(async function () {
  let client
  try {
    client = await Aerospike.connect({
        hosts: '192.168.33.10:3000',
        policies: {
          write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
        },
        // Must have security enabled in server configuration before user and password configurations can be used.
        user: 'admin',
        password: 'admin'
    })
    // Quotas must be enabled in the server configurations for quotas to be set.
    client.setWhitelist("Engineer", ["172.17.0.2"])
    // Must wait a short length of time for the privilegee to be granted.
    await wait(5)
    let role = await client.queryRole("Engineer")
    console.log(role)
  } catch (error) {
    console.error('Error:', error)
    process.exit(1)
  } finally {
    if (client) client.close()
  }
})()
Parameters:
Name Type Description
roleName String

role name

whitelist Array.<String>

Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).

policy Object

Optional AdminPolicy.

stats() → {ClientStats}

Returns runtime stats about the client instance.

Source:
Since:
  • v3.8.0
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()
})
Returns:

client stats

Type
ClientStats

truncate(ns, set, before_nanos, policyopt, callbackopt)

Removes records in specified namespace/set efficiently.

Description:
  • This method is many orders of magnitude faster than deleting records one at a time. It requires server 3.12 or later.

Source:
See:
Parameters:
Name Type Attributes 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.

udfRegister(path, udfTypeopt, policyopt, callbackopt)

Registers a UDF module with the database cluster.

Description:
  • 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.

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()
    })
  })
})
Parameters:
Name Type Attributes 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.

udfRemove(udfModule, policyopt, callbackopt)

Removes a UDF module from the cluster.

Description:
  • 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.

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()
    })
  })
})
Parameters:
Name Type Attributes 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.

Events

disconnected

Source:
Since:
  • v2.7.0
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

Description:
  • 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.

Source:
Since:
  • v2.7.0
Properties:
Name Type Attributes 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.

Type:
  • object
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

Source:
Since:
  • v2.7.0
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.

Type:
  • object

nodeRemoved

Source:
Since:
  • v2.7.0
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.

Type:
  • object