在Go和MongoDB中迭代大型数据集的有效方法



这更像是一个一般性的问题,但这是我的问题。我们有两个数据库,都是mongo数据库。我们正在将数据从一个mongo实例迁移到另一个实例,我们应用程序的v1和v2之间的差异意味着对所述数据进行重构。这里的问题在于。一个特定的收藏大约有84万条记录。获取840条记录不是问题所在。我需要将数据结构转换为新的数据库模式。重构的一部分是在迁移的这个特定部分嵌入其他3个集合的新生成的objectId。

例如患者收集,护理人员收集,机构收集,这些是在没有id的情况下导入的,由mongo 生成

它们都被新生成的objectID的引用在访问集合中的840k条记录中

我的问题在于,当我遍历所有4个集合来排列这个过程所需的数据时,我甚至不知道在杀死它之前,我让它运行了4个小时。

for _, a := range agencies {
for _, c := range caregivers {
for _, p := range patients {
for _, m := range model {
if a.Name == *m.AgencyName && m.CaregiverID == &c.CareGiverID && m.PatientID == &p.PatientID {
visit := &models.Visit{
CreatedAt:  time.Now(),
UpdatedAt:  time.Now(),
AgencyID:   a.ID.Hex(),
ScheduleID: *m.ScheduleID,
Status:     *m.Status,
Start:      *m.Start,
End:        *m.End,
PatientID:  p.ID.Hex(),
UserID:     c.ID.Hex(),
}
updateModel = append(updateModel, mongo.NewUpdateOneModel().SetFilter(
bson.D{
{Key: "agencyId", Value: a.ID.Hex()},
{Key: "userId", Value: c.ID.Hex()},
{Key: "patientId", Value: p.ID.Hex()},
{Key: "scheduleId", Value: m.ScheduleID},
{Key: "start", Value: m.Start},
{Key: "end", Value: m.End},
},
).SetUpdate(
bson.D{{Key: "$set", Value: visit}},
).SetUpsert(true))
}
}
}
}
}

现在,当我做这些代码时,这些代码适用于较小的集合,但这一次所花的时间比我们等待的时间要长。我的问题是,向32个机构、8000名患者和6000名护理人员整理84万份记录最耗时的方法是什么。我做了一些数学运算,它的范围比我的计算器能吐出的数字还要多。FWI我不在乎资源消耗,因为我们可以在运行应用程序所需的时间内启动任何大小的云机器。这只是为840k次访问中的每一次从其他3个集合中获取这些对象id的有效方法。我确实有一个想法,将这些集合导入到旧数据库,并在聚合期间查找输入的id,但这不是很容易编程。

缓存对象ID的修改范围

for _, m := range model {
agency, agencyFound := c.Get(*m.AgencyName)
uid, uidFound := c.Get(fmt.Sprintf("caregiver-%v-%d", agency, *m.CaregiverID))
patientId, patientFound := c.Get(fmt.Sprintf("patient-%v-%d", agency, *m.PatientID))
if agencyFound && uidFound && patientFound {
visit := &models.Visit{
CreatedAt:  time.Now(),
UpdatedAt:  time.Now(),
AgencyID:   fmt.Sprintf("%v", agency),
ScheduleID: *m.ScheduleID,
Status:     *m.Status,
Start:      *m.Start,
End:        *m.End,
PatientID:  fmt.Sprintf("%v", patientId),
UserID:     fmt.Sprintf("%v", uid),
}
updateModel = append(updateModel, mongo.NewUpdateOneModel().SetFilter(
bson.D{
{Key: "agencyId", Value: fmt.Sprintf("%v", agency)},
{Key: "userId", Value: fmt.Sprintf("%v", uid)},
{Key: "patientId", Value: fmt.Sprintf("%v", patientId)},
{Key: "scheduleId", Value: m.ScheduleID},
{Key: "start", Value: m.Start},
{Key: "end", Value: m.End},
},
).SetUpdate(
bson.D{{Key: "$set", Value: visit}},
).SetUpsert(true))
}
}

机构、护理人员、患者和就诊的笛卡尔乘积为32x8000x6000x840000,约为10^15。

让我们假设内部if需要一个CPU周期来计算(需要更多的时间(,而4千兆赫的CPU需要89个多小时才能完成。

为每次就诊生成所有可能的组合(机构、护理人员、患者(是对资源的巨大浪费。

反向方法:迭代所有就诊,并获取该特定文档的机构、护理人员和患者。为了节省访问数据库的时间,在内存中存储具有所需ID的映射是可行的。

相关内容

最新更新