5

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?

Maelig
  • 2,046
  • 4
  • 24
  • 49
user274051
  • 325
  • 1
  • 12

2 Answers2

8

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();
user274051
  • 325
  • 1
  • 12
  • the `.beginGroup()` and `.endGroup()` are useless here because there a not other groups or outside criterias – Maelig Aug 02 '18 at 13:00
0

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);
Maelig
  • 2,046
  • 4
  • 24
  • 49
  • 1
    "From Realm-Java code you can find 2 methods" because there are only two methods, can you reference the `contains(String fieldName, List listOfValues)` method? I don't think there is such method, anyway. – Farid Dec 24 '19 at 15:22
  • maybe they changed the API since my answer ? I don't use Realm anymore (because I don't work anymore on the project I used to) – Maelig Dec 30 '19 at 08:12