Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Objectify query by "key" field

I have the following Objectify relationship:

@Entity(“Author”)
public class Author{
  @Id
  private long authorId;
  …

}

@Entity(“Book”)
public class Book{
  @Id
  private long id;
  private Key<Author> authorKey;
  …

}

Now for the fun part: I have the authorId (the id, not entity) and I need to query Book for that author. My query is below, but it is returning an empty list, whereas I know for a fact that this author has books in the datastore. So how might I fix this query?

public static List<Book> getBooksForAuthor(Long authorId) {
    Key<Author> authorKey = Key.create(Author.class, authorId);
    return OfyService.ofy().load().type(Book.class).filter("authorKey", authorKey).order(“-date").list();
  }
like image 323
learner Avatar asked Sep 27 '22 11:09

learner


2 Answers

You will need to @Index the Book.authorKey and Book.date fields. I can't remember offhand if this will require a multiproperty index on {authorKey, date}, but try without and see if it works.

I would also recommend that you call the field 'author' not 'authorKey'.

like image 74
stickfigure Avatar answered Sep 30 '22 07:09

stickfigure


You are querying with the field authorId instead of the authorKey that you just created.

OfyService.ofy().load().type(Book.class).filter("authorKey", authorKey).order(“-date").list();

With this change and the index in place, you should get the result.

like image 40
Qutub Dahodwala Avatar answered Sep 30 '22 06:09

Qutub Dahodwala