Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 543
user274051 Avatar asked Sep 28 '17 14:09

user274051


1 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();
like image 82
user274051 Avatar answered Oct 14 '22 02:10

user274051