Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the $in operator through Morphia - doing it wrong?

I have the following Play Framework entity (using Morphia for persistence) as part of a generic blogging app:

@Entity
public class Comment extends Model {

    ...

    @Reference
    @Indexed
    public SiteUser commenter;

    public static List<Comment> getLastCommentsByUsers(final List<SiteUser> users) {
        final Query<Comment> query ds().createQuery(Comment.class);
        query.field(commenter).hasAnyOf(users);
        return query.asList();
    }

}

SiteUser:

@Entity(noClassnameStored=true)
public class SiteUser extends AbstractUser {

    public String realName;

}

AbstractUser:

public class AbstractUser extends Model {

    @Indexed(value= IndexDirection.DESC, unique = true)
    public String emailAddress;

    @Required
    public String password;
}

The method getLastCommentsByUsers() is supposed to return all comments by the users in the users parameter, but I always get an empty List back. The reason that Commment is a separate collection is to be able to retrieve last X Comments by certain users across their associated Posts, which isn't possible if the Comment is embedded in the Post collection.

Is there something wrong with my query (should I be using something other than hasAnyOf), or is it a problem with the relationship mapping - should I be using ObjectId instead?

like image 833
Rich Avatar asked May 25 '11 12:05

Rich


2 Answers

I use the in() method with a list or set and its working perfectly. Here's a snippet:

List<String> keywordList;
List<Product> products = Product.find().field("keywords").in(keywordList).asList();

This should work for collection of embedded or references too.

like image 63
Joel Grenon Avatar answered Sep 22 '22 14:09

Joel Grenon


You should use List<Key<SiteUser>> to query:

public static List<Comment> getLastCommentsByUsers(final List<SiteUser> users) {
    final Query<Comment> query ds().createQuery(Comment.class);
    query.field(commenter).hasAnyOf(toKeys(users)); // convert to keys
    return query.asList();
}

public static List<Key<SiteUser>> toKeys(List<SiteUser> users) {
    List<Key<SiteUser>> keys = new ArrayList<Key<SiteUser>>();
    for(SiteUser user: users) {
        keys.add(ds().getMapper().getKey(user));
    }
    return keys;
}

Or you can just get the keys by:

List<Key<SiteUser>> keys = ds().createQuery(SiteUser.class).query().filter(...).asKeyList();
like image 33
Freewind Avatar answered Sep 22 '22 14:09

Freewind