gpt4 book ai didi

python - pymongo - 如何通过 GridFS 中的索引创建/查询

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:06 24 4
gpt4 key购买 nike

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

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']

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

最佳答案

您可以手动为具有自身哈希值的文件提供 _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/

关于python - pymongo - 如何通过 GridFS 中的索引创建/查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16051016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com