mercredi 6 mai 2015

How to get the list of maximum value for a column for a list of unique key

Let's say I have a table on Parse that has two columns: an identifier set by hand and a numeric property.

I need to write a query that gets me the maximum number on the numeric property per each unique identifier. So in the example below:

| identifier | value |
----------------------
| 1          | 10    |
| 2          | 5     |
| 1          | 7     |
| 2          | 9     |

I would expect the following output:

| identifier | value |
----------------------
| 1          | 10    |
| 2          | 9     |

Now I know Parse doesn't have anything like Group By statements, so this is probably not doable as a single query.

What alternative would you suggest in this case? I see some solutions, each with serious drawbacks:

  • Compose the result from multiple queries. This would require a query that gets the unique list of identifier and then a separate query for each identifier to get the maximum value. This will probably not scale well if the table grows in size. Also the result is not exactly consistent as the DB can change between queries (for my use case slightly stale date is not too bad). This will heavily impact the request quota limit as a single request can now trigger a large number of requests.
  • Keep a separate table that keeps track of this result. This table would have a single row for each identifier, containing the max value. For this I would need a beforeSave trigger that updates the second table. From what I've read there is no guarantee that beforeSave triggers are not executed concurrently so it's very tricky to ensure that I don't accidentally insert multiple values for the same identifier. I would probably have to run a background job that removes duplicates.

For my use case I'll need to get the data on an iOS device so network traffic is also an issue.

Aucun commentaire:

Enregistrer un commentaire