Read
Jump to the Code block for a combined complete example.
Create a document record
The following example demonstrates how to read 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.
This example creates the following JSON document:
"sightings": [{"sighting":{"occurred":20200912,"reported":20200916,"posted":20201105,"report":{"city":"Kirkland","duration":"~30 minutes","shape":["circle"],"state":"WA","summary":"4 rotating orange lights in the Kingsgate area above the Safeway. Around 9pm the power went out in the Kingsgate area. Four lights were spotted rotating above the local Safeway and surrounding streets. They were rotating fast but staying relatively in the same spots. Also described as orange lights. About thirty minutes later they disappeared. The second they disappeared the power was restored. Later a station of police from Woodinville and Kirkland came to guard the street where it happened. They wouldn't let anyone go past the street, putting out search lights and flare signals so people couldn't drive past Safeway. The police also would not let people walk past to go home."},"location":"\"{\"type\":\"Point\",\"coordinates\":[-122.1966441,47.69328259]}\""}},{"sighting":{"occurred":20200322,"reported":20200322,"posted":20200515,"report":{"city":"Pismo Beach","duration":"5 minutes","shape":["light"],"state":"CA","summary":"About 20 solid, bright lights moving at the same altitude, heading and speed. Spaced perfectly apart flying over the ocean headed south."},"location":"\"{\"type\":\"Point\",\"coordinates\":[-120.6595,35.1546]}\""}},{"sighting":{"occurred":20200530,"reported":20200531,"posted":20200625,"report":{"city":"New York Staten Island","duration":"2 minutes","shape":["disk"],"state":"NY","summary":"Round shaped object observed over Staten Island NYC, while sitting in my back yard. My daughter also observed this object . Bright White shaped object moving fast from East to West . Observed over Graniteville, Staten Island towards the Elizabeth NJ area and appears to be fast. We then lost view of it due to the clouds."}}}]
The JSON document is added to a bin called sightings
which is of data
type map. 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 java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
import com.aerospike.client.AerospikeClient;import com.aerospike.client.AerospikeException;import com.aerospike.client.Bin;import com.aerospike.client.Key;import com.aerospike.client.Record;import com.aerospike.client.Value;import com.aerospike.client.cdt.ListOperation;import com.aerospike.client.cdt.ListReturnType;import com.aerospike.client.policy.RecordExistsAction;import com.aerospike.client.policy.WritePolicy;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;
AerospikeClient client = new AerospikeClient("localhost", 3000);
// Aerospike namespace, set, and key_id to be used for the Aerospike keyString namespace = "sandbox";String set = "ufo";int key_id = 5231;String binName = "sigthings";
// Define Aerospike keyKey key = new Key(namespace, set, key_id);
Prepare the JSON document to be sent to Aerospike.
// Example JSON stringString sightings = "[{\"sighting\":{\"occurred\":20200912,\"reported\":20200916,\"posted\":20201105,\"report\":{\"city\":\"Kirkland\",\"duration\":\"~30 minutes\",\"shape\":[\"circle\"],\"state\":\"WA\",\"summary\":\"4 rotating orange lights in the Kingsgate area above the Safeway. Around 9pm the power went out in the Kingsgate area. Four lights were spotted rotating above the local Safeway and surrounding streets. They were rotating fast but staying relatively in the same spots. Also described as orange lights. About thirty minutes later they disappeared. The second they disappeared the power was restored. Later a station of police from Woodinville and Kirkland came to guard the street where it happened. They wouldn't let anyone go past the street, putting out search lights and flare signals so people couldn't drive past Safeway. The police also would not let people walk past to go home.\"},\"location\":\"\\\"{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\":[-122.1966441,47.69328259]}\\\"\"}},\n" + "{\"sighting\":{\"occurred\":20200322,\"reported\":20200322,\"posted\":20200515,\"report\":{\"city\":\"Pismo Beach\",\"duration\":\"5 minutes\",\"shape\":[\"light\"],\"state\":\"CA\",\"summary\":\"About 20 solid, bright lights moving at the same altitude, heading and speed. Spaced perfectly apart flying over the ocean headed south.\"},\"location\":\"\\\"{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\":[-120.6595,35.1546]}\\\"\"}},\n" + "{\"sighting\":{\"occurred\":20200530,\"reported\":20200531,\"posted\":20200625,\"report\":{\"city\":\"New York Staten Island\",\"duration\":\"2 minutes\",\"shape\":[\"disk\"],\"state\":\"NY\",\"summary\":\"Round shaped object observed over Staten Island NYC, while sitting in my back yard. My daughter also observed this object . Bright White shaped object moving fast from East to West . Observed over Graniteville, Staten Island towards the Elizabeth NJ area and appears to be fast. We then lost view of it due to the clouds.\"}}}]";
// Convert string to Java MapList<Map<String, Object>> sightingMap = new Gson().fromJson(sightings, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
// Set an Aerospike bin with the bin name "sigthings" and put the JSON document in as a mapBin bin = new Bin(binName, Value.get(sightingMap));
Write
Write the document to Aerospike.
// Create the write policyWritePolicy writePolicy = new WritePolicy();writePolicy.recordExistsAction = RecordExistsAction.UPDATE;
// Read record from Aerospiketry { // Write record client.put(writePolicy, key, bin);} // Write failedcatch (AerospikeException ae) { System.out.println("Read failed\\nError: " + ae.getMessage());}
Read
Read the last third element in the list.
// Read the last, third, element in the listRecord record = client.operate(writePolicy, key, ListOperation.getByIndex(binName, 1, ListReturnType.VALUE));
// Get the value for `sighting` keyObject value = record.getValue(binName);System.out.printf("Read succeeded \nKey: %d \nRecord: %s", key.userKey.toLong(), new Gson().toJson(value));
// Close the clientclient.close();
Code block
Expand this section for a single code block to read a document record.
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
import com.aerospike.client.AerospikeClient;import com.aerospike.client.AerospikeException;import com.aerospike.client.Bin;import com.aerospike.client.Key;import com.aerospike.client.Record;import com.aerospike.client.Value;import com.aerospike.client.cdt.ListOperation;import com.aerospike.client.cdt.ListReturnType;import com.aerospike.client.policy.RecordExistsAction;import com.aerospike.client.policy.WritePolicy;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;
AerospikeClient client = new AerospikeClient("localhost", 3000);
// Aerospike namespace, set, and key_id to be used for the Aerospike keyString namespace = "sandbox";String set = "ufo";int key_id = 5231;String binName = "sigthings";
// Define Aerospike keyKey key = new Key(namespace, set, key_id);
// Example JSON stringString sightings = "[{\"sighting\":{\"occurred\":20200912,\"reported\":20200916,\"posted\":20201105,\"report\":{\"city\":\"Kirkland\",\"duration\":\"~30 minutes\",\"shape\":[\"circle\"],\"state\":\"WA\",\"summary\":\"4 rotating orange lights in the Kingsgate area above the Safeway. Around 9pm the power went out in the Kingsgate area. Four lights were spotted rotating above the local Safeway and surrounding streets. They were rotating fast but staying relatively in the same spots. Also described as orange lights. About thirty minutes later they disappeared. The second they disappeared the power was restored. Later a station of police from Woodinville and Kirkland came to guard the street where it happened. They wouldn't let anyone go past the street, putting out search lights and flare signals so people couldn't drive past Safeway. The police also would not let people walk past to go home.\"},\"location\":\"\\\"{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\":[-122.1966441,47.69328259]}\\\"\"}},\n" + "{\"sighting\":{\"occurred\":20200322,\"reported\":20200322,\"posted\":20200515,\"report\":{\"city\":\"Pismo Beach\",\"duration\":\"5 minutes\",\"shape\":[\"light\"],\"state\":\"CA\",\"summary\":\"About 20 solid, bright lights moving at the same altitude, heading and speed. Spaced perfectly apart flying over the ocean headed south.\"},\"location\":\"\\\"{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\":[-120.6595,35.1546]}\\\"\"}},\n" + "{\"sighting\":{\"occurred\":20200530,\"reported\":20200531,\"posted\":20200625,\"report\":{\"city\":\"New York Staten Island\",\"duration\":\"2 minutes\",\"shape\":[\"disk\"],\"state\":\"NY\",\"summary\":\"Round shaped object observed over Staten Island NYC, while sitting in my back yard. My daughter also observed this object . Bright White shaped object moving fast from East to West . Observed over Graniteville, Staten Island towards the Elizabeth NJ area and appears to be fast. We then lost view of it due to the clouds.\"}}}]";
// Convert string to Java MapList<Map<String, Object>> sightingMap = new Gson().fromJson(sightings, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
// Set an Aerospike bin with the bin name "sigthings" and put the JSON document in as a mapBin bin = new Bin(binName, Value.get(sightingMap));
// Create the write policyWritePolicy writePolicy = new WritePolicy();writePolicy.recordExistsAction = RecordExistsAction.UPDATE;
// Read record from Aerospiketry { // Write record client.put(writePolicy, key, bin);} // Write failedcatch (AerospikeException ae) { System.out.println("Read failed\\nError: " + ae.getMessage());}
// Read the last, third, element in the listRecord record = client.operate(writePolicy, key, ListOperation.getByIndex(binName, 1, ListReturnType.VALUE));
// Get the value for `sighting` keyObject value = record.getValue(binName);System.out.printf("Read succeeded \nKey: %d \nRecord: %s", key.userKey.toLong(), new Gson().toJson(value));
// Close the clientclient.close();