Skip to content
Visit booth 3171 at Google Cloud Next to see how to unlock real-time decisions at scaleMore info

Transactions

Jump to the Code block for a combined complete example.

CRUD operations

The following example demonstrates create, update, read, and delete (CRUD) operations within a transaction. For the purposes of this example, the following records are held in a bin named sightings:

"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 example writes the records to the database, then updates the city field of the first record as part of a transaction.

Setup

Import the necessary helpers, create a client connection, and create a key.

using System;
using System.Collections.Generic;
using Aerospike.Client;
AerospikeClient client = new("localhost", 3000);
// Aerospike namespace, set, and keyId to be used for the Aerospike key
string ns = "sandbox";
string set = "ufodata";
string binName = "sighting";
int keyId = 5001;
// Define Aerospike key
Key key = new(ns, set, keyId);

Prepare the data to be sent to Aerospike.

// Data structure
List<Dictionary<string, object>> sightingMaps = new()
{
new()
{
["sighting"] = new Dictionary<string, object>()
{
["occurred"] = "20200912",
["reported"] = "20200916",
["posted"] = "20201105",
["report"] = new Dictionary<string, object>()
{
["city"] = "Kirkland",
["duration"] = "~30 minutes",
["shape"] = new List<string>()
{
"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"] = new Dictionary<string, object>()
{
["type"] = "Point",
["coordinates"] = "-122.1966441,47.69328259"
}
}
},
new()
{
["sighting"] = new Dictionary<string, object>()
{
["occurred"] = "20200322",
["reported"] = "20200322",
["posted"] = "20200515",
["report"] = new Dictionary<string, object>()
{
["city"] = "Pismo Beach",
["duration"] = "5 minutes",
["shape"] = new List<string>()
{
"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"] = new Dictionary<string, object>()
{
["type"] = "Point",
["coordinates"] = "-120.6595,35.1546"
}
}
},
new()
{
["sighting"] = new Dictionary<string, object>()
{
["occurred"] = "20200530",
["reported"] = "20200531",
["posted"] = "20200625",
["report"] = new Dictionary<string, object>()
{
["city"] = "New York Staten Island",
["duration"] = "2 minutes",
["shape"] = new List<string>()
{
"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."
},
}
}
};
// Set an Aerospike bin with the bin name "sightings" and put the JSON document in as a map
Bin bin = new Bin(binName, sightingMaps);

Write

Write the document to Aerospike.

// Writing record to Aerospike
try
{
client.Delete(null, key);
client.Put(writePolicy, key, bin);
Record record = client.Get(null, key);
object value = record.bins[binName];
Console.WriteLine($"Create succeeded \nKey: {key.userKey.ToString()} \nRecord: {value.ToString()}");
} // Write failed
catch (AerospikeException ae)
{
Console.WriteLine("Create failed\nError: " + ae.Message);
}

Update

Update the newly created document.

// Start transaction
Txn transaction = new();
// Create the update policy
WritePolicy updatePolicy = client.WritePolicyDefault.Clone();
updatePolicy.recordExistsAction = RecordExistsAction.UPDATE;
updatePolicy.Txn = transaction;
try
{
// Update the sighting city in the first record in list of "sightings" from "Kirkland" to "Seattle"
client.Operate(updatePolicy, key,
MapOperation.Put(
new MapPolicy(MapOrder.KEY_VALUE_ORDERED, MapWriteMode.UPDATE),
binName, // Bin to be updated
Value.Get("city"), // Key to be updated
Value.Get("Seattle"), // Update value
CTX.MapKey(Value.Get("sighting")), CTX.MapKey(Value.Get("report")))
);
}
catch (AerospikeException ae)
{
// Abort transaction on failure
client.Abort(transaction);
Console.WriteLine("Read failed \nError: " + ae.Message);
}
// Commit transaction
client.Commit(transaction);

Read

Read the updated document.

// Read updated record
Record updatedRecord = client.Get(null, key);
object updatedValue = updatedRecord.bins[binName];
Console.WriteLine($"Read succeeded \nKey: {key.userKey.ToString()} \nRecord: {updatedValue.ToString()}");

Delete

Delete the first two records by key.

// Taking the first two ids to remove
List<int> keyIdsToRemove = keyIds.Take(2).ToList();
Txn transaction = new();
WritePolicy deletePolicy = client.WritePolicyDefault.Clone();
deletePolicy.Txn = transaction;
deletePolicy.durableDelete = true; // Required when deleting recorord as part of MRT
// Deleting records
foreach (int keyId in keyIdsToRemove)
{
try
{
Key key = new(ns, set, keyId);
client.Delete(deletePolicy, key);
} // Read failed
catch (AerospikeException ae)
{
Console.WriteLine("Read failed \nError: " + ae.Message);
}
}
Console.WriteLine("Delete succeeded\n");
// Commit transaction
client.Commit(transaction);
// Close the client
client.Close();

Code block

Expand this section for a single code block to update a document record.
using System;
using System.Collections.Generic;
using Aerospike.Client;
AerospikeClient client = new("localhost", 3000);
// Aerospike namespace, set, and keyId to be used for the Aerospike key
string ns = "sandbox";
string set = "ufodata";
string binName = "sighting";
int keyId = 5001;
// Define Aerospike key
Key key = new(ns, set, keyId);
// Data structure
List<Dictionary<string, object>> sightingMaps = new()
{
new()
{
["sighting"] = new Dictionary<string, object>()
{
["occurred"] = "20200912",
["reported"] = "20200916",
["posted"] = "20201105",
["report"] = new Dictionary<string, object>()
{
["city"] = "Kirkland",
["duration"] = "~30 minutes",
["shape"] = new List<string>()
{
"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"] = new Dictionary<string, object>()
{
["type"] = "Point",
["coordinates"] = "-122.1966441,47.69328259"
}
}
},
new()
{
["sighting"] = new Dictionary<string, object>()
{
["occurred"] = "20200322",
["reported"] = "20200322",
["posted"] = "20200515",
["report"] = new Dictionary<string, object>()
{
["city"] = "Pismo Beach",
["duration"] = "5 minutes",
["shape"] = new List<string>()
{
"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"] = new Dictionary<string, object>()
{
["type"] = "Point",
["coordinates"] = "-120.6595,35.1546"
}
}
},
new()
{
["sighting"] = new Dictionary<string, object>()
{
["occurred"] = "20200530",
["reported"] = "20200531",
["posted"] = "20200625",
["report"] = new Dictionary<string, object>()
{
["city"] = "New York Staten Island",
["duration"] = "2 minutes",
["shape"] = new List<string>()
{
"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."
},
}
}
};
// Set an Aerospike bin with the bin name "sightings" and put the JSON document in as a map
Bin bin = new Bin(binName, sightingMaps);
// Create the write policy
WritePolicy writePolicy = client.WritePolicyDefault.Clone();
writePolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
// Writing record to Aerospike
try
{
client.Delete(null, key);
client.Put(writePolicy, key, bin);
Record record = client.Get(null, key);
object value = record.bins[binName];
Console.WriteLine($"Create succeeded \nKey: {key.userKey.ToString()} \nRecord: {value.ToString()}");
} // Write failed
catch (AerospikeException ae)
{
Console.WriteLine("Create failed\nError: " + ae.Message);
}
// Starting multi record transaction
Txn transaction = new();
// Create the update policy
WritePolicy updatePolicy = client.WritePolicyDefault.Clone();
updatePolicy.recordExistsAction = RecordExistsAction.UPDATE;
updatePolicy.Txn = transaction;
try
{
// Update the sighting city in the first record in list of "sightings" from "Kirkland" to "Seattle"
client.Operate(updatePolicy, key,
MapOperation.Put(
new MapPolicy(MapOrder.KEY_VALUE_ORDERED, MapWriteMode.UPDATE),
binName, // Bin to be updated
Value.Get("city"), // Key to be updated
Value.Get("Seattle"), // Update value
CTX.MapKey(Value.Get("sighting")), CTX.MapKey(Value.Get("report")))
);
}
catch (AerospikeException ae)
{
// Abort transaction on failure
client.Abort(transaction);
Console.WriteLine("Read failed \nError: " + ae.Message);
}
// Commit transaction
client.Commit(transaction);
// Read updated record
Record updatedRecord = client.Get(null, key);
object updatedValue = updatedRecord.bins[binName];
Console.WriteLine($"Read succeeded \nKey: {key.userKey.ToString()} \nRecord: {updatedValue.ToString()}");
// Delete first two records
// Taking the first two ids to remove
List<int> keyIdsToRemove = keyIds.Take(2).ToList();
Txn transaction = new();
WritePolicy deletePolicy = client.WritePolicyDefault.Clone();
deletePolicy.Txn = transaction;
deletePolicy.durableDelete = true; // Required when deleting recorord as part of MRT
// Deleting records
foreach (int keyId in keyIdsToRemove)
{
try
{
Key key = new(ns, set, keyId);
client.Delete(deletePolicy, key);
} // Read failed
catch (AerospikeException ae)
{
Console.WriteLine("Read failed \nError: " + ae.Message);
}
}
Console.WriteLine("Delete succeeded\n");
// Commit transaction
client.Commit(transaction);
// Close the client
client.Close();
Feedback

Was this page helpful?

What type of feedback are you giving?

What would you like us to know?

+Capture screenshot

Can we reach out to you?