Home > Software engineering >  Best way to update single field in Aerospike
Best way to update single field in Aerospike

Time:08-09

I have an Aerospike cache consists of list of data with value of json like structure.

example value: {"name": "John", "count": 10}

I wanted to scan for all records and reset count to zero. What would be a good option to handle this problem?

CodePudding user response:

I think the best way to do this would be to leverage the background operations... I just tried the following code on the Aerospike sandbox and it did update all the 'shape' entries in the 'report' map to updated shape. (Disclaimer: I am not a developer so there may be really bad ways of doing things in Java in general but this hopefully shows how to do a background operation scan in Aerospike)

Run the 'setup' tab and then copy paste this in the create tab (or in the blank tab) and run:

import com.aerospike.client.task.ExecuteTask;
import com.aerospike.client.task.Task;
import com.aerospike.client.query.Statement;
import com.aerospike.client.query.Filter;
import com.aerospike.client.Operation;
import com.aerospike.client.exp.Exp;

AerospikeClient client = new AerospikeClient("127.0.0.1", 3000);

try {
    WritePolicy writePolicy = new WritePolicy();
    MapPolicy mapPolicy = new MapPolicy();
    String mapBinName = "report";
    String mapKeyName = "shape";

    Statement stmt = new Statement();
    stmt.setNamespace("sandbox");
    stmt.setSetName("ufodata");

    ExecuteTask task = client.execute(
      writePolicy, stmt, MapOperation.put(mapPolicy, mapBinName, 
                                          Value.get(mapKeyName), Value.get("updated shape")));

    if(task != null) {
        System.out.format("Task ID: %s\nTask Status: %s", 
            task.getTaskId(), task.queryStatus());    
    }
    else {
        System.out.format("Task seems null!");
    }
}

catch (AerospikeException ae) {
    System.out.format("Error: %s", ae.getMessage());
}

You can change this to a secondary index query (if defined) or add further filters on the map bin itself...

Here are a couple of tutorials that may help:

  • Related