数据库访问速度慢(FastAPI+Firebase)

2024-09-30 14:35:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个后端服务(FastAPI),它使用Pyrebase助手库(如Firebase文档所建议的)连接到Firebase。 Firebase实时数据库的结构为:

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

电影和收视率数据库有10000多个字段

下面介绍了我为特定用户提供的方法/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."}

Tags: idchilddbget电影valmoviesmovie