Google App Engine NDB custom key id
Asked Answered
J

3

23

When I create an object with ndb's method put it creates the key automatically of the type Key(kind, id) where id is a number. All over the documentation it shows that you can use a string for the key's id but I couldn't find out how to do this automatically when an object is created.

I have a User model and I was thinking to use the user's username (since its unique) as the key's id for faster retrieval. Is that even a good idea? Would I have any problems with the username since it's user submited (i'm validating the input)?

Jolin answered 24/10, 2012 at 21:50 Comment(0)
B
32
class UserModel(ndb.Model):
  ...

user_model_entity = UserModel(id='some_string', ...)

If these IDs are subject to change, this may be a bad idea. If it's your own system and you can react to potential changes, it is a fine idea, but you need make sure the IDs will be unique and relatively stable before deciding to use them.

Barrows answered 24/10, 2012 at 21:58 Comment(1)
I experienced latency issue with this approach before. It's not a good idea to manually set IDs for Datastore entities, as you will also run into the problem of "hot tablets" . It's best to let the datastore generate entity IDs automatically and not encode data into the key itself. Instead use an Property in the entity. It may be tempting to apply relational database conventions to the Datastore, such as auto-incrementing primary keys, but this will actually undo the sharding of the keyspace and create problems. [1] cloud.google.com/appengine/articles/handling_datastore_errorsDissever
P
13

You specify the id of the entity at the time of creation. When you define the model, you don't set an id attribute there. Thus, for example you have:

class User(ndb.Model):
    # fields here

When you create the model, you have:

user = User(id='username', ...)

Since the username is unique and you validate your input, then you will not have any problems with this approach.

For more information about an ndb Model constructor, you can take a look at NDB Model Class - Constructor.

Hope this helps.

Preliminary answered 24/10, 2012 at 22:23 Comment(0)
N
0

You can also supply integer ID (not necessarily a string) for your model entity.

class User(ndb.Model):
...

user = User(id=1234567890, ...)
user.put()
Norvol answered 9/5, 2017 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.