我有一个以类为键的IMap。这个键有两个属性:
static class MapKey implements Serializable{
String uid;
String service;
public MapKey() {
}
public MapKey(String uid, String service) {
this.uid = uid;
this.service = service;
}
public String getUid() {
return uid;
}
...
}我只用两个简单的值初始化了map:
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
final IMap<MapKey, String> map = hz.getMap("testmap");
map.addIndex("__key#uid", false);
map.put(new MapKey("uid1","service1"),"value1");
map.put(new MapKey("uid1","service2"),"value2");然后我将使用ands构建一个谓词:
static Predicate<MapKey, String> buildPredicate(MapKey key){
final EntryObject entryObject = new PredicateBuilder().getEntryObject().key();
final List<Predicate<MapKey, String>> predicateList = new ArrayList<>();
predicateList.add(entryObject.get("uid").equal(key.getUid()));
predicateList.add(entryObject.get("service").equal(key.getService()));
final com.hazelcast.query.Predicate predicate = Predicates.and(predicateList.toArray(new Predicate[predicateList.size()]));
return predicate;
}当我使用这个谓词时,它只返回按uid过滤的键,这意味着集合值的大小为2,而不是预期的大小。
Predicate<MapKey, String> predicate = buildPredicate(new MapKey("uid1","service1"));
Collection<MapKey> values = map.keySet(predicate);有人能解释这种行为吗?我错过了什么?
发布于 2020-03-19 19:30:34
问题是,你在entryObject上的操作是如果它是一个不可变的对象,但它不是不可变的。它实际上是一个构建器,操作entryObject.get("uid").equal(key.getUid())更改其状态并记录谓词条件。这就是为什么要在两个完全相等的谓词上执行Predicates.and()的原因。
尝试以下操作,它将实现您想要实现的目标。
static Predicate<MapKey, String> buildPredicate(MapKey key){
final List<Predicate<MapKey, String>> predicateList = new ArrayList<>();
predicateList.add(new PredicateBuilder().getEntryObject().key().get("uid").equal(key.getUid()));
predicateList.add(new PredicateBuilder().getEntryObject().key().get("service").equal(key.getService()));
final com.hazelcast.query.Predicate predicate = Predicates.and(predicateList.toArray(new Predicate[predicateList.size()]));
return predicate;
}https://stackoverflow.com/questions/60724968
复制相似问题