How to fetch primary key in Aerospike Node.js Client


#1

I’m trying to fetch all records along with Primary key from Aerospike. I tried using client.query functionality as below

var query = client.query(aerospikeDBParams.dbName,“testRecords”);

var stream = query.execute();

with this I’m getting all the fields except the Primary key.How can i get Primary key along with the other fields?

Thanks in advance!!


#2

Hi @Radhika_Hs, since you posted the identical question on Stack Overflow as well, let me just copy @rbotzer’s answer here for the benefit of other users of this forum.

You first need to actually store the primary key with the record. The client and server locate the record using its digest, which the client hashes using the (namespace, set, primary-key) information. The default value for the key write policy is Aerospike.policy.key.DIGEST. You will need to explicitly set that to Aerospike.policy.key.SEND instead.

See the Aerospike:module documentation. It contains this example:

// global policy, applied to all commands that do not override it
var config = {
  policies: {
    timeout: 100,
    retry: Aerospike.policy.retry.ONCE
  }
}

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

  var key = new Aerospike.Key('test', 'demo', 'k1')
  var record = {i: 1234}

  // override policy for put command
  var policy = {
    exists: Aerospike.policy.exists.CREATE,
    key: Aerospike.policy.key.SEND
  }

  client.put(key, record, {}, policy, (error) => {
    if (error && error.code === Aerospike.status.AEROSPIKE_ERR_RECORD_EXISTS) {
      console.info('record already exists')
    } else if (error) {
      throw error
    }
    client.close()
  })
})

When the keys are stored with the record a query will return them.

If you are still using the v1 client, you are all set. The data event on the record stream returned by the query will include the key object, including the primary key:

stream.on('data', (record) => {
  var key = record.key
  console.log('primary key returned: %s', key.key)
})

Unfortunately v2 contains a regression in the query functionality and does not currently (as of v2.0.3) return the record key. I will fix this in the next patch release and include the missing key object in the event:

stream.on('data', (bins, meta, key) => {
  console.log('primary key returned: %s', key.key)
})

Note the difference in the parameters of the data event handler in v1 vs v2!