简体   繁体   中英

How to get 10 random GAE ndb entities?

I have the following class to keep my records:

class List(ndb.Model):
    '''
    Index
      Key:              sender
    '''
    sender = ndb.StringProperty()
    ...
    counter = ndb.IntegerProperty(default=0)
    ignore = ndb.BooleanProperty(default=False)

    added = ndb.DateTimeProperty(auto_now_add=True, indexed=False)
    updated = ndb.DateTimeProperty(auto_now=True, indexed=False)

The following code is used to return all entities I need:

entries = List.query()
entries = entries.filter(List.counter > 5)
entries = entries.filter(List.ignore == False)
entries = entries.fetch()

How should I modify the code to get 10 random records from entries ? I am planning to have a daily cron task to extract random records, so they should be really random. What is the best way to get these records (to minimize number of read operations)?

I don't think that the following code is the best:

entries = random.sample(entries, 10)

Well after reading the comments the only improvement you can make as far I can see is to fetch the keys only and limit if possible.

Haven't tested but like so

list_query = List.query()
list_query = list_query.filter(List.counter > 5)
list_query = list_query.filter(List.ignore == False)
list_keys = list_query.fetch(keys_only=True) # maybe put a limit here.

list_keys = random.sample(list_keys, 10)
lists = [list_key.get() for list_key in list_keys]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM