In my web application made with Ionic and Firestore, I would like to select 5 random items to put on sale- The items are documents that are in a collection collectA . To do this I have seen that firebase does not allow to get documents in a random way, but a possible solution to get them is shown in this post Firestore: How to get random documents in a collection . But I would like 5 random items to be taken, then another 5 that have not already been taken, and so on. When all items have been taken, you start over. Would it be a good solution to consider a new collectB collection in which to insert the 5 randomly taken items and delete them from the collectA collection? Then do it for all the items taken. When collectA becomes empty and all items are in collectB, do the same process but from collectB to collectA. The disadvantage I think is only in the increased cost of the write-offs ($0.02 per 100,000). The writes are not because when I take the 5 random items I still have to modify some fields of these documents. I don't want the queries to slow down or the costs to increase a lot.
CodePudding user response:
If you need 5 new random items for all your users in the application, then don't do that operation in Firestore, do it in the Realtime Database, it's much cheaper for choosing such random items. Both databases are working really well together in the same project. That being said, you can have a structure that looks like this:
Firebase-root
|
--- products
| |
| --- $productId: true
| |
| --- $productId: true
|
--- consumedProducts
|
--- $productId: true
|
--- $productId: true
There are two solutions to this problem. Every time you get 5 new random IDs from the "products" node, add them also to the "consumedProducts" node. To be able not to choose the same IDs again, always check if the new IDs are not already present in the "consumedProducts" node. After a while, when the "consumedProducts" will contain the same IDs as the "products" node, then you can simply remove it and start over again. The second solution might be to add those 5 elements into the "consumedProducts" and right after that delete them from "products" node. When the "products" node remains empty, do the same thing with the "consumedProducts".
Now according to the logic of your app, you should decide which one is better to be used, but remember, always keep in sync, the actual products from Firestore with corresponding IDs in the Realtime Database. For instance, if you add a new product in Firestore, add the corresponding ID in the Realtime Database node. That should happen also when you delete a product from Firestore.