通过 GridFS 将大型 DataFrame 写入 MongoDB

tsc*_*chm 5 mongodb gridfs mongoengine python-3.x pandas

我处理包含数字和文本的大型数据帧。显然我可以将每列/行存储为一个 sep。我的 mongoDB 中的文档,但我想在加载数据时删除和麻烦。

我考虑过使用 GridFS,它是通过使用 MongoEngine FileField 进行抽象的。与此同时,我想出了一个适合我的解决方案:

import pandas as pd
from mongoengine import Document, StringField, FileField

from io import BytesIO


class Frame(Document):
    name = StringField(required=True, max_length=200, unique=True)
    data = FileField()

    @property
    def frame(self):
        str_data = BytesIO(self.data.read()).read().decode()

        try:
            return pd.read_json(str_data, typ="frame")
        except ValueError:
            return pd.read_json(str_data, typ="series")

    def __str__(self):
        return "{name}: \n{frame}".format(name=self.name, frame=self.frame)

    def put(self, frame):
        if self.data:
            self.data.replace(frame.to_json().encode())
        else:
            self.data.new_file()
            self.data.write(frame.to_json().encode())
            self.data.close()

        self.save()


if __name__ == '__main__':
    from pydata.config import connect_production

    connect_production()
    frame = pd.DataFrame(data=[[1,2,4],[3,4,6]], columns=["A","B","C"], index=["X","Y"])

    f = Frame.objects(name="history").update_one(name="history", upsert=True)
    f = Frame.objects(name="history").first()
    f.put(frame=frame)
    print(f)
Run Code Online (Sandbox Code Playgroud)