google-app-enginegoogle-cloud-datastoreapp-engine-ndb

Query highest number of one-to-many relationships


I have a "Like" system in place to track who likes what.

The Like model's parent is the object that is liked. This could be anything. For this example lets use a Car. The Like model also has an account property that determines who liked that Car.

I'm wondering if there's a way in datastore/NDB to query the highest number of likes. This isn't normalized to just have a raw number on the Car object, but I'm wondering if that's the only real way to do this.

Basically, if 10 different people like a single Car object, and 5 different people like a different Car object, what would be the query to list those to items out look like, with the count?

If I knew which Car objects to query for, I could simply query those on the Like table and just count the number of objects it has, and that obviously gives me the total Like count for that Car, but I'm going the other direction with it.


Solution

  • As described it is not possible: without an actual counter property you'd first need to perform individual queries to get each of the relevant counts, then perform an additional step to determine the maximum of those counts.

    If however you add a liked counter property to the liked objects (Car in your example), which you'd increment in the same transaction in which you create the corresponding Like entity, you will no longer need the first round of queries to get the counts. You will thus be able to perform a single query per kind of liked object (a query for Car entities in the example) - ordered (desc) by the liked property and maybe with a result count limit - which will give you the most liked object(s) of that kind.