Is it possible to query several fields containing a list of string values (Realm Java)

Viewed 1824

I am trying to query several fields at the same time that contains a list of string values in Realm. Lets say that I have the following Object:

public class Article extends RealmObject implements Serializable{
    @PrimaryKey
    @Required
    private String aID = UUID.randomUUID().toString();

    private String title;
    private String description;
    private String authors;
    private RealmList<Tag> tags;
}

I would like to query all the articles what title, or description, or tags contain the list of strings.

I know that the predicate "in" can be used to match a list of values to a field as follows:

realm.where(Article.class)
    .in("title", listOfValues,Case.INSENSITIVE)
    .or()
    .in("description", listOfValues, Case.INSENSITIVE)
    .or()
    .in("tags.tag",listOfValues, Case.INSENSITIVE)
    .findAll();

This will only return "matching" values, but I am looking for "containing" values. There is also the "contains" predicate, but I think it can only be compared to one value.

Is there anyway to do this?

2 Answers

A work around to solve this question is as @EpicPandaForce suggested in his comment, iterate and use contains. Here is the code for doing this:

 RealmResults<Article> newResults;
 RealmQuery<Article> where = r.where(Article.class).beginGroup();
 for (String keyword : keywords) {
     where = where.contains("name", keyword, Case.INSENSITIVE)
             .or()
             .contains("description", keyword, Case.INSENSITIVE)
             .or()
             .equalTo("tags.tag", keyword, Case.INSENSITIVE);
 }

 newResults = where.endGroup().findAll();

A simpler answer is to directly use .contains (sadly it's not explained in realm-java doc).

realm.where(Article.class) 
    .contains("title", listOfValues, Case.INSENSITIVE)
    .or()
    .contains("description", listOfValues, Case.INSENSITIVE)
    .or()
    .contains("tags.tag",listOfValues, Case.INSENSITIVE)
    .findAll();

From Realm-Java code you can find 2 methods :

public RealmQuery<E> contains(String fieldName, String value);
public RealmQuery<E> contains(String fieldName, String value, Case casing);
Related