Java 如何从Firestore中删除集合或子集合?
我有一个名为列表的集合,它有一个ID表示列表ID的文档。此文档有一个名为Java 如何从Firestore中删除集合或子集合?,java,android,firebase,google-cloud-firestore,Java,Android,Firebase,Google Cloud Firestore,我有一个名为列表的集合,它有一个ID表示列表ID的文档。此文档有一个名为employees的集合和另一个名为locations的集合 结构如下所示: (lists) -listId (employees) (locations) 如果用户想要删除一个特定的列表,那么问题是我们不能删除listId,因为这将保留集合(正如Firestore文档所提到的) 如何对结构进行建模以满足需求?我似乎无法回避再次收集的必要性 有什么建议吗?没有必要为了删除某些集合而重新构
employees
的集合和另一个名为locations
的集合
结构如下所示:
(lists)
-listId
(employees)
(locations)
如果用户想要删除一个特定的列表,那么问题是我们不能删除listId,因为这将保留集合(正如Firestore文档所提到的)
如何对结构进行建模以满足需求?我似乎无法回避再次收集的必要性
有什么建议吗?没有必要为了删除某些集合而重新构建数据库。要在Cloud Firestore中删除整个集合或子集合,请检索集合或子集合中的所有文档并将其删除。因此,要删除特定列表,请使用以下步骤:
employees
collection下的所有文档并将其删除位置下的所有文档
集合并删除它们listId
文档会对安全性和性能产生负面影响
,您仍然可以执行该操作,但仅限于小集合。如果需要删除整个web集合,请仅从受信任的服务器环境中删除
对于Android,您可以使用以下代码:
private void deleteCollection(final CollectionReference collection, Executor executor) {
Tasks.call(executor, () -> {
int batchSize = 10;
Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize);
List<DocumentSnapshot> deleted = deleteQueryBatch(query);
while (deleted.size() >= batchSize) {
DocumentSnapshot last = deleted.get(deleted.size() - 1);
query = collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize);
deleted = deleteQueryBatch(query);
}
return null;
});
}
@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
QuerySnapshot querySnapshot = Tasks.await(query.get());
WriteBatch batch = query.getFirestore().batch();
for (DocumentSnapshot snapshot : querySnapshot) {
batch.delete(snapshot.getReference());
}
Tasks.await(batch.commit());
return querySnapshot.getDocuments();
}
private void deleteCollection(最终收集参考收集,执行者执行者){
任务。调用(执行器,()->{
int batchSize=10;
Query=collection.orderBy(FieldPath.documentId()).limit(batchSize);
删除列表=删除查询批次(查询);
while(deleted.size()>=batchSize){
DocumentSnapshot last=deleted.get(deleted.size()-1);
query=collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize);
删除=删除查询批次(查询);
}
返回null;
});
}
@工作线程
私有列表deleteQueryBatch(最终查询)引发异常{
QuerySnapshot QuerySnapshot=Tasks.await(query.get());
WriteBatch batch=query.getFirestore().batch();
用于(DocumentSnapshot快照:querySnapshot){
batch.delete(snapshot.getReference());
}
Tasks.wait(batch.commit());
返回querySnapshot.getDocuments();
}
Hmmm我明白了。所以我想用这种方式一个接一个地删除是可以的。谢谢你的代码片段,我现在正试图剖析它:)你能解释一下如何使用上面提到的执行器吗?@Ben-Hey-Ben。一般来说,与其他概念相关的问题应单独添加。因此,请发布一个新问题,以便我和其他Firebase开发人员可以帮助您。