使用pymongo批量上传数据时高效查重
Efficiently check duplicates while uploading batch data with pymongo
我有一个 MongoDB 集合,它使用批量数据帧顺序更新:
print(batch_df_0)
id date shop product
1 28/10/2021 1 apple
2 28/10/2021 2 apple
3 28/10/2021 3 apple
##################
# MongoDB Update #
##################
print(batch_df_1)
id date shop product
1 28/10/2021 1 apple # not to be uploaded, since already in DB
1 29/10/2021 1 apple # OK
1 29/10/2021 1 banana # OK, since product is not key
10 29/10/2021 1 apple # OK
1 29/10/2021 2 banana # OK
1 29/10/2021 3 apple # OK
print(batch_df_1_to_be_updated)
id date shop product
1 29/10/2021 1 apple
1 29/10/2021 1 banana
10 29/10/2021 1 apple
1 29/10/2021 2 banana
1 29/10/2021 3 apple
##################
# MongoDB Update #
##################
我想确保我不会在同一行上载两次(例如 1 28/10/2021 1 apple from batch_df_1,它已经存在于 batch_df_0 中),鉴于“id”、“date”和“shop”作为应控制重复项的数据库键。
到目前为止,我尝试将复合索引设置为:
compound_index = [('id', 1), ('date', 1), ('shop', 1)]
collection.create_index(compound_index, unique=True)
insert_result = collection.insert_many(batch_df_1.to_dict("records"))
但是,一旦发现重复,它就会停止上传。
有没有一种有效的方法可以确保重复检查,对于DataFrame的每一行,没有 停止 整个 DataFrame 上传?
将ordered=False
传给insert_many
操作,使其继续推送其他文档,最后抛出异常。
try:
insert_result = collection.insert_many(batch_df_1.to_dict("records"), ordered=False)
except:
# Ignore Error
我有一个 MongoDB 集合,它使用批量数据帧顺序更新:
print(batch_df_0)
id date shop product
1 28/10/2021 1 apple
2 28/10/2021 2 apple
3 28/10/2021 3 apple
##################
# MongoDB Update #
##################
print(batch_df_1)
id date shop product
1 28/10/2021 1 apple # not to be uploaded, since already in DB
1 29/10/2021 1 apple # OK
1 29/10/2021 1 banana # OK, since product is not key
10 29/10/2021 1 apple # OK
1 29/10/2021 2 banana # OK
1 29/10/2021 3 apple # OK
print(batch_df_1_to_be_updated)
id date shop product
1 29/10/2021 1 apple
1 29/10/2021 1 banana
10 29/10/2021 1 apple
1 29/10/2021 2 banana
1 29/10/2021 3 apple
##################
# MongoDB Update #
##################
我想确保我不会在同一行上载两次(例如 1 28/10/2021 1 apple from batch_df_1,它已经存在于 batch_df_0 中),鉴于“id”、“date”和“shop”作为应控制重复项的数据库键。
到目前为止,我尝试将复合索引设置为:
compound_index = [('id', 1), ('date', 1), ('shop', 1)]
collection.create_index(compound_index, unique=True)
insert_result = collection.insert_many(batch_df_1.to_dict("records"))
但是,一旦发现重复,它就会停止上传。
有没有一种有效的方法可以确保重复检查,对于DataFrame的每一行,没有 停止 整个 DataFrame 上传?
将ordered=False
传给insert_many
操作,使其继续推送其他文档,最后抛出异常。
try:
insert_result = collection.insert_many(batch_df_1.to_dict("records"), ordered=False)
except:
# Ignore Error