Charlie Morton
Charlie Morton

Reputation: 787

Best way to structure data in datastore with relationships

I'm trying to get my grips around the structuring of Datastore. Sorry in advance for the n00bness but I really can't get my head around it...

Consider a typical dating app which would use google cloud's datastore as a "database".

Suppose we have:

In a typical SQL style database I might choose to have (amongst other things):

  1. A user table with a primary key of id
  2. A photo table with a foreign key of user_id to link to the user whose photo it is
  3. A swipe table for each individual swipe by any user against any other user it would have 2 foreign keys, swiper and swiped
  4. a match table where we add a new entry if 2 people both swipe right on each other.

Would you structure it similarly in datastore by having those 4 entity types? If so how do you deal with the "foreign keys"?

Or would you nest some of those within a document e.g each user has a list of photos nested within it, or a list of all their swipes/matches, ensuring that both users in a match have that reflected?

Upvotes: 0

Views: 149

Answers (1)

NoCommandLine
NoCommandLine

Reputation: 6323

I typically prefer interacting with Datastore via the ndb library (if you're not using Python, you might still get an idea of how to apply the following suggestion in your own runtime).

Using the ndb library, I could potentially see myself going with what you have where the 'foreign keys' you refer to would be implemented as a ndb.KeyProperty.

A very rough profile of what you might have would be

    # This is your user KIND
    class User(ndb.Model):
     ....

    # This is your photo KIND
    class Photo(ndb.Model):
       # This ties each record in Photo to a person in your User table
       user = ndb.KeyProperty(kind="User", required=True)
     ....


    # This is your Swipes KIND
    class Swipes(ndb.Model):
       # This ties each swiper to a person in your User table
       swiper = ndb.KeyProperty(kind="User", required=True)

       # This ties each swiped to a person in your User table
       swiped = ndb.KeyProperty(kind="User", required=True)
     ....

From the UI, you can click on any column defined as ndb.KeyProperty and it will open up the underlying record. In your code, you can directly run a query (do a GET) to return the details of the underlying record.

Let's say you used the above model, then to run queries where you wish to list photos and the name of the user who posted them or to list swipes and who swiped to who, I would use tasklets to have the queries run concurrently & asynchronously. See the tasklets section on the old Python2 NDB documentation for a worked example

Upvotes: 2

Related Questions