如果在aerospike中不存在,则设置默认bin值



假设我在aeropike集合中有两个箱子

数量
  1. (关键)2。timeLeft

我想要得到一个timleft数值从aerospike。但是如果特定的记录不存在那么我想创建记录并将默认值6000设置为timleft然后在单个事务中获取值。

public Record someMethod(String num) {
WritePolicy writePolicy = aerospikeRepo.getWritePolicy(null, ttl, true);
return aerospikeRepo.operate(writePolicy, namespace, set, num, Operation.get());
}

就我个人而言,我认为aerospike客户端的。operate()方法将以某种方式使用,但没有找到相关的操作来设置默认值,如果不存在。

您可以使用表达式来实现。下面是示例代码:

import com.aerospike.client.AerospikeClient;
import com.aerospike.client.policy.WritePolicy;
import com.aerospike.client.Bin;
import com.aerospike.client.Key;
import com.aerospike.client.Record;
import com.aerospike.client.Value;
import com.aerospike.client.policy.RecordExistsAction;
import com.aerospike.client.AerospikeException;
import com.aerospike.client.ResultCode;
import com.aerospike.client.Operation;
import com.aerospike.client.exp.Exp;
import com.aerospike.client.exp.ExpOperation;
import com.aerospike.client.exp.ExpWriteFlags;
import com.aerospike.client.exp.Expression;
System.out.println("Client modules imported.");
AerospikeClient client = new AerospikeClient("localhost", 3000);
WritePolicy wP = new WritePolicy();
wP.respondAllOps = true;
int iNumber = 11;
int iTimeLeft = 6000;
for(int i=0; i<5; i++){
Key key = new Key ("test", "testset", iNumber);
Expression tlExp = Exp.build(Exp.val(iTimeLeft));
Record record = client.operate(wP, key, 
ExpOperation.write("timeLeft", tlExp, ExpWriteFlags.CREATE_ONLY | ExpWriteFlags.POLICY_NO_FAIL),
//ExpOperation.write("timeLeft", tlExp, ExpWriteFlags.DEFAULT),                          
Operation.get("timeLeft"));   

List<?> list = record.getList("timeLeft");
System.out.println(list.get(1));  
iTimeLeft = iTimeLeft - 1000; //should not alter record value
}

输出如下:

Client modules imported.
6000
6000
6000
6000
6000

但是,如果我使用DEFAULT,每次输出都会被修改。(你不想要的,与上面的正确标志(CREATE_ONLY|POLICY_NO_FAIL,即,如果你只想在bin不存在的情况下更新记录,则静默地继续下一个操作)。

Client modules imported.
6000
5000
4000
3000
2000

相关内容

  • 没有找到相关文章

最新更新