Reputation: 2707
I need to find customers from Realm Db based on first and last name. Currently, I have a query like this:
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);
This does not work properly since I have OR between first and last name.
So, if I want to find user named John Doe, it wont find it, but if I type only John it will find it.
How I can solve this?
Upvotes: 4
Views: 1516
Reputation: 2096
You need to use group : 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);
Upvotes: 0
Reputation: 81539
Why not split across white space?
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);
Upvotes: 2