【问题标题】:pymongo - How to create/query by indices in GridFSpymongo - 如何通过 GridFS 中的索引创建/查询
【发布时间】:2013-04-09 16:23:09
【问题描述】:

就我而言,我需要通过 SHA1 确保文件的唯一性(存储为 filename

db = pymongo.MongoClient('localhost', 27017).test
gfs = gridfs.GridFS(db)

# How may I create a unique index in GridFS?
gfs.files.create_index([('filename', 1)], unique=True)

如果文件已经存储,则通过SHA1查找文件。

sha1 = hashlib.sha1(file_content).hexdigest()
try:
    return gfs.put(file_content, filename=sha1)
except pymongo.errors.DuplicateKeyError:

    # How may I find files via criterion?
    return gfs.find( { 'filename': sha1 } )['_id']

谁能告诉我如何做这些事情?提前致谢。

【问题讨论】:

    标签: python pymongo gridfs


    【解决方案1】:

    您可以手动为具有自身哈希值的文件提供_id 键,而不是创建索引。

    import pymongo 
    db = pymongo.MongoClient('localhost', 27017).test
    gfs = gridfs.GridFS(db)
    
    def hash(file):
       #some code to extract hash of a file from its content..
    
    file_hash = hash(file)
    if gfs.exists(_id=file_hash):
        #file exists!
    else:
        #file does not exist in the database.
        gfs.put(file, _id=file_hash) #or do something else..
    

    http://api.mongodb.org/python/current/api/gridfs/

    【讨论】:

    • 如果这段代码在并发环境中运行呢?我需要数据库来确保唯一性。
    猜你喜欢
    • 1970-01-01
    • 2018-08-17
    • 2012-06-08
    • 2016-02-06
    • 2021-03-24
    • 2014-10-21
    • 1970-01-01
    • 2019-03-24
    相关资源
    最近更新 更多