2

我正在尝试构建一个使用 Pyrebase Helper Library 连接到 Firebase 的后端服务(FastAPI)(如 Firebase 文档所建议的那样)。Firebase 实时数据库的结构如下:

"myproject_db" : {
        "movies":
            "key1": {
                "movie_id": 33
                "other_id": 44
            },
        "ratings":
            "key1": {
                "user_id" : 1
                "rating" : 5
                "movie_id" : 33
            },
    }

电影和收视率数据库有超过 10,000 个字段。

现在,我针对特定用户的方法 /getRatedMovies 如下所述。即使它有效,它也需要超过 30 秒才能完成。主要原因是电影的迭代。似乎每次我需要找到一部特定的电影时,我都需要遍历整个表格。有没有我想念的替代解决方案?谢谢你。

@app.get("/getRatedMovies")
async def ratedMovies():
    try:
        ratings = db.child("ratings").order_by_child("user_id").equal_to(username).get()

        restructuredMovies: List[Movie] = []
        for rating in ratings.each():
            movieid: int = rating.val()["movie_id"]
            movies = db.child("movies").order_by_child("movie_id").equal_to(movie_id).get()
            for movie in movies:
                movieid: int = movie.val()['movie_id']
                other_id: Optional[str] = movie.val()["other_id"]
                restructuredMovie: Movie = Movie(title = movie.val()["title"], movieid = movieid, other_id = other_id)
                restructuredMovies.append(restructuredMovie)
        return {"Movies": restructuredMovies}
    except Exception as error:
        return {"error": "Something went wrong."}
4

0 回答 0