5星评级系统数据库设计

5 star rating system database design

我正在构建一个应用程序,该应用程序将具有允许您按 1-5 的等级对用户进行评分的功能。我已经决定要像这样使用加权平均值:

Sum of (weight * number of reviews at that weight) / total number of reviews

我无法弄清楚如何使用 firebase 存储此数据,因为我需要此评级值来初始化 User 对象。我想将每个评分存储为字典,其中键是用户离开评论的 id,值是实际评分。然后在我从数据库中获取用户并需要初始化 User 之后,我执行以下操作:

    // keep track of amount of each rating. 
    var oneStars = 0
    var twoStars = 0
    var threeStars = 0
    var fourStars = 0
    var fiveStars = 0

    // iterate through dictionary of ratings where key is unique Id, and value is star rating.
    for (key, value) in ratings {
        switch value {
        case 1: oneStars += 1
        case 2: twoStars += 1
        case 3: threeStars += 1
        case 4: fourStars += 1
        case 5: fiveStars += 1
        }
    }

    let weightedSum = (
        (5 * fiveStars) +
        (4 * fourStars) +
        (3 * threeStars) +
        (2 * twoStars) +
        (1 * oneStars)
    )

    let reviewsSum = oneStars + twoStars + threeStars + fourStars + fiveStars

    let rating = weightedSum / reviewsSum

    let user = User(name: "john doe", rating: rating)

这是存储评分并进行实际计算以初始化对象的最佳方式,还是有更高效的设计?谢谢。

你可能需要存储每个用户的评分,所以用这种方式存储评分是可以的。

至于计算最终评分,这里有一个更好的实现:

var count = 0
var rating = 0

for (key, value) in ratings {
    count += 1
    rating += value
}

rating /= count

let user = User(name: "john doe", rating: rating)

另一种可以处理大量评分的算法 可能会导致溢出:

var count = 0
var rating = 0

for (key, value) in ratings {
    count += 1
    rating += (value - rating) / count
}

let user = User(name: "john doe", rating: rating)

如果您在每次新用户评分时都在服务器端重新计算评分,则第二种算法效果很好(如果您有大量用户访问这些评分,并且还有大量评分,则最好计算这在服务器端)。