简体   繁体   中英

How to query two fields in same Realm query?

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?

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM