Read
Jump to the Code block for a combined complete example.
Create a document record
The following example demonstrates reading a document record with a JSON helper library. In Aerospike, JSON documents are handled as a Collection Data Type (CDT). A JSON object is equivalent to a map, and a JSON array is equivalent to a list.
In this example, we create the following JSON document:
employees = [{"id": "09", "name": "Nitin", "department": "Finance"}, {"id": "10", "name": "Jonathan", "department": "Human Resources"}, {"id": "11", "name": "Caitlin", "department": "Engineering"}]
The JSON document is added to a bin called employees
which is of data
type list. There are some advantages
to holding an entire document in a single bin, rather than spreading out the document’s
fields over multiple bins. There is less metadata overhead when namespaces
contain fewer, larger bins.
Setup
Import the necessary helpers, create a client connection, and create a key.
import { readFile } from "node:fs/promises";
const Aerospike = await import("aerospike");const maps = Aerospike.maps;
// Set hosts to your server's address and portconst config = { hosts: "YOUR_HOST_ADDRESS:YOUR_PORT" };
// Create a keyconst key = new Aerospike.Key("test", "demo", 5001);
// Establishes a connection to the serverconst client = await Aerospike.connect(config);
Read
Read the name
field from the third record in the map list.
// Get 'name' field from 3rd employee recordconst ops = [ maps .getByKey("employees", "name") .withContext((ctx) => ctx.addListIndex(2)) .andReturn(maps.returnType.VALUE),];
const result = await client.operate(key, ops);console.info("Name of 3rd employee: ", result.bins.employees);
Code block
Expand this section for a single code block to read a document record.
const Aerospike = await import("aerospike");
import { readFile } from "node:fs/promises";
const maps = Aerospike.maps;
// Set hosts to your server's address and portconst config = { hosts: "YOUR_HOST_ADDRESS:YOUR_PORT" };
// Create a keyconst key = new Aerospike.Key("test", "demo", 5001);
// Establishes a connection to the serverconst client = await Aerospike.connect(config);
// Get 'name' field from 3rd employee recordconst ops = [ maps .getByKey("employees", "name") .withContext((ctx) => ctx.addListIndex(2)) .andReturn(maps.returnType.VALUE),];
const result = await client.operate(key, ops);console.info("Name of 3rd employee: ", result.bins.employees);
await client.close();