How to filter NDB entities having exactly the same repeated properties?

578 views Asked by At

My NDB model class has repeated property:

class Something(ndb.Model):
  tags = ndb.StringProperty(repeated=True)

Is there any way to query for all entities havings tags equal to ['music', 'cinema']? I.e. each entity returned should have music and cinema tag at the same time and shouldn't have other tags. The GAE doc says that

You cannot compare repeated properties to list objects (the Datastore won't understand it)

Will I have to fetch all entities with one tag and then filter it manually?

2

There are 2 answers

1
Greg On BEST ANSWER

Storing a serialized/hashed version of the list and querying for an exact match against that will likely be more efficient than fetching all of your entities:

class Something(ndb.Model):
  tags = ndb.StringProperty(repeated=True)
  tagset = ndb.ComputedProperty(lambda self: ','.join(self.tags.sort()))

Then to query use the same serialization on your search-tags:

    q = Something.query(cls.tagset == ','.join(sorted(['music', 'cinema'])))
1
Brent Washburne On

Yes, you can use the IN property, which uses a list object when Querying for Repeated Properties:

Something.tags.IN(['music', 'cinema'])

To see if both tags are present, you can use the AND operation:

Something.tags.query(ndb.AND(Something.tags == 'music',
                             Something.tags == 'cinema'))