简体   繁体   中英

Most efficient voting system in Firebase

I'm working on an app that lets users upload pictures and rate (so vote with stars 1-5) each others pictures. But I keep thinking that the database system that I'm building is not efficient enough. I hope that there is someone who can give me advice.

Right now I have a database table called "images". It has the following fields:

  • doc_id
  • user_id
  • image
  • amount_of_votes
  • rating

Everytime a user votes the amount_of_votes gets a +1 and the rating gets calculated by (rating*old amount of votes + new vote) / new amount of votes

But this gives me the following problems:

  • If 2 users look at the same image at the same time (for example an iamge with 2 votes with 1 star) then if the first user votes 5 stars a new rating is calculated. But if the second user votes 1 star again then the last user who votes still gets 2 votes with 1 star and doesn't see the new 5 star rating.
  • Also I think that it's not safe to do it this way. A user can in theorie just change the amount to 1 and the rating to 1.

I want to build a new voting system where there is a new table called votes and it holds the user_id and the vote that the user gives. But that gives me the following problem:

  • if a user clicks on a really popular image then if has to load a lot of votes and calculate an average. That isn't efficient.

Does anyone know what the best system is that I can use? I have spend days on the internet but I haven't found the best system yet...

I didn't try implementing it myself but my approach for this will be the use of a Snapshot listener .

It can help you to have updated information in the application whenever something changes in the document. The voting system which I use is collecting 5 stars, 4 stars , 3 stars, etc, separately. For example: how many 5 stars ratings a user got, how many 4 stars a user got and so on. Then, to calculate the average rating I use the following formula:

((no_of_votes_for_5stars * 5) + (no_of_votes_for_4stars * 4) + (no_of_votes_for_3stars * 3) + (no_of_votes_for_2stars * 2) + (no_of_votes_for_1star * 1)) / (no_of_votes_for_5stars +no_of_votes_for_4stars + no_of_votes_for_3stars + no_of_votes_for_2stars + no_of_votes_for_1star )

You can save the number of stars data separately in the Firestore database and whenever someone rates a photo, you can increment the current count. And you can implement the above formula inside the app code so your application gets the number of stars info and calculates the average using the above formula, and then displays it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM