Reputation: 325
I am trying to create a search engine that will show results containing different tags. The results must be sorted by relevance.
Lets say I have the following models:
public class Article extends RealmObject{
@PrimaryKey
private String aID = UUID.randomUUID().toString();
private RealmList<Tags> tags;
}
public class Tags extends RealmObject{
@PrimaryKey
private String tID = UUID.randomUUID().toString();
private String tag;
private RealmList<articleTagsRelation> articlesTag;
}
public class articleTagsRelation extends RealmObject{
private String tID;
private String aID;
private long timesArticleSelectedByTag;
}
So the relation between RealmObjects are: Article (many-to-many) tags (many-to-many) articleTagsRelation
When users search by tag, the app should return all the Articles that fill the search:
realm.where(Article.class).equalTo("tags.tag", userSearch).findAll().
However, I would like to sort the results by relevance. Relevance in this example is the number of times users have selected the article when searching by the related tag (articleTagsRelation.timesArticleSelectedByTag).
I have been struggling for a while to find a direct way to accomplish this with no result. Is there any direct way to do it? if not, sorting the results one by one will be the unique solution?
Thanks
Upvotes: 0
Views: 78
Reputation: 81559
Realm 3.5.0+:
public class Article extends RealmObject{
@PrimaryKey
private String aID = UUID.randomUUID().toString();
private RealmList<Tags> tags;
@LinkingObjects("article")
private final RealmResults<ArticleTagsRelation> articleOfRelation = null;
}
public class Tags extends RealmObject{
@PrimaryKey
private String tID = UUID.randomUUID().toString();
private String tag;
@LinkingObjects("tag")
private final RealmResults<ArticleTagsRelation> tagOfRelation = null;
}
public class ArticleTagsRelation extends RealmObject{
private Tags tag;
private Article article;
private long timesArticleSelectedByTag;
}
realm.where(Article.class)
.equalTo("tags.tag", userSearch)
.findAllSorted("articleOfRelation.timesArticleSelectedByTag", Sort.DESCENDING);
Upvotes: 1