我需要根据名字和姓氏从Realm Db查找客户。目前,我有这样的查询:
RealmResults<CustomerModel> results = realm
.where(CustomerModel.class)
.or()
.contains("firstname", input, Case.INSENSITIVE)
.or()
.contains("lastname", input, Case.INSENSITIVE)
.or()
.contains("addresses.street", input, Case.INSENSITIVE)
.or()
.contains("addresses.city", input, Case.INSENSITIVE)
.or()
.contains("addresses.postcode", input, Case.INSENSITIVE)
.findAllSorted("customerLocalId", Sort.DESCENDING);
由于我的名字和姓氏之间有OR,因此无法正常工作。
因此,如果我想找到名为John Doe的用户,它将找不到它,但是如果我只键入John,它将找到它。
我该如何解决?
答案 0 :(得分:1)
为什么不跨空白?
String filter = input.trim().replaceAll("\\s+", " ");
String[] tokens = filter.split(" ");
RealmQuery<CustomerModel> query = realm.where(CustomerModel.class);
for(int i = 0, size = tokens.length; i < size; i++) {
String token = tokens[i];
if(i != 0) {
query.or();
}
query.contains("firstname", token, Case.INSENSITIVE)
.or()
.contains("lastname", token, Case.INSENSITIVE)
.or()
.contains("addresses.street", token, Case.INSENSITIVE)
.or()
.contains("addresses.city", token, Case.INSENSITIVE)
.or()
.contains("addresses.postcode", token, Case.INSENSITIVE)
}
RealmResults<CustomerModel> results = query
.findAllSorted("customerLocalId", Sort.DESCENDING);
答案 1 :(得分:0)
您需要使用组:https://realm.io/docs/java/latest/#logical-operators
RealmResults<CustomerModel> results = realm
.where(CustomerModel.class)
.beginGroup()
.contains("firstname", input, Case.INSENSITIVE)
.contains("lastname", input, Case.INSENSITIVE)
.endGroup()
.or()
.contains("addresses.street", input, Case.INSENSITIVE)
.or()
.contains("addresses.city", input, Case.INSENSITIVE)
.or()
.contains("addresses.postcode", input, Case.INSENSITIVE)
.findAllSorted("customerLocalId", Sort.DESCENDING);