0

I am an android developer. I have an app which connects to MySql DB in server. Now i am planning to migrate them to Google app engine. But i am stuck with how to structure my entities.

There are tables 'users' and 'books'. Users can own multiple books and a book can be owned by multiple people. So there is a reference table called 'book-owners'. There is a column in this table called as the number of pages read. So each user to book relationship has a this special property 'no. of pages read'.

With MySql I could perform join queries to get all the info i want.Now with GAE we can not perform join queries. All I want is these,

  1. All books owned by a user along with 'no. of pages read' property
  2. Number of owners for a particular book

When I query for user i need the following response:

{"user_id":"123","user_name":"John Doe","books":[{"book_id":"123456", "book_name":"Some book name","pages_read":126},{"book_id":"123457","book_name":"Some book name","pages_read":26},{"book_id":"123458","book_name":"Some book name","pages_read":274},{"book_id":"123459","book_name":"Some book name","pages_read":48}]}

So how to structure my entities. And how to query them back? Kindly give me some advice / pointers. Thanks already.

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
Riyaz Ahamed
  • 802
  • 8
  • 14
  • you can use MySQL with GAE quite easily, if you don't actually want to migrate to the datastore but do want to migrate to GAE in general. Search for GAE Cloud SQL – Paul Collingwood Jul 04 '15 at 12:09
  • Thanks Paul. But I still prefer datastore. – Riyaz Ahamed Jul 04 '15 at 12:14
  • 1
    ok. Look into ancestors then. Here's an answer where I talk about authors and books: http://stackoverflow.com/questions/12832782/what-is-the-purpose-of-ancestors-in-the-google-app-engine-datastore – Paul Collingwood Jul 04 '15 at 12:42

1 Answers1

2

Here is one way:

class User(ndb.Model):
    [any data here you want]

class Book(ndb.Model):
    [any data here you want]

class OwnedBook(ndb.Model):
    user = ndb.KeyProperty(User)
    book = ndb.KeyProperty(Book)
    pages_read = ndb.IntegerProperty()

To get books owned by a user with pages read, do this:

books_owned_by_user = OwnedBook.query(OwnedBook.user = user1)

After getting the OwnedBook entities, you'll need to do further queries to get more information about the books.

for owned_book in OwnedBook.query(OwnedBook.user = user1):
    book = owned_book.book.get()

You'll need to think about how to do this efficiently for your particular application.

To get the number of owners of a book, do this:

num_owners = OwnedBook.query(OwnedBook.book = book1).count()
new name
  • 15,861
  • 19
  • 68
  • 114