david
david

Reputation: 17

filter Two property vs filtering one computed property ? datastore google app engine

I want to build a chat application, this's my model:

class Message(ndb.Model):
  senderId = ndb.IntegerProperty()
  receiverId = ndb.IntegerProperty()
  sender_receiver = ndb.ComputedProperty(lambda self: self.senderId.join('-').join(self.receiverId))
  message = ndb.StringProperty()
  date = ndb.DateTimeProperty(auto_now_add=True)

so if I want to get the messages to userId1 and userId2 with these values: userId1 = 7878 , userId2=5264. I will run the following query:

qry = Message.query(Message.sender_receiver.IN('7878-5264','5264-7878'));

but without computed property:

qry = Message.query(Message.sender.IN(7878,5264) AND Message.receiver.IN(7878,5264));

which is better ?

Upvotes: 0

Views: 419

Answers (2)

Dmytro Sadovnychyi
Dmytro Sadovnychyi

Reputation: 6201

Use repeated property.

sender_receiver = ndb.ComputedProperty(lambda self: [self.senderId, self.receiverId], repeated=True)

qry = Message.query()
qry = qry.filter(Message.sender_receiver == 7878)
qry = qry.filter(Message.sender_receiver == 5264)
# you will get all values where sender or receiver in 7878 or 5264 with a single query

Upvotes: 1

Patrice
Patrice

Reputation: 4692

Off the top of my head (and going with what Dmitry said), In is an expensive and slow operation, since it creates multiple queries and then joins the results.

I would use the computed property, but I wouldn't even use the IN in it.

I'd do

 qry = Message.query(Message.sender_receiver = '7878-5264' OR Message.sender_receiver = '5264-7878');

the computed property will cost you a bit more time when doing saves, but it's a normal case of taking a bit more time to save so it can retrieve faster.

Upvotes: 0

Related Questions