在 each 循环里面调用 update/create 接口,执行时间会很长,而且也会很容易达到 API 调用次数上限。因此,将【多次】 update/create 转化成【1次】 batch 批量调用,会大幅提升函数执行效率,而且也能避免收到 API 调用次数的限制。
List searchCondition = []
Fx.log.info("查询条件为 :" + searchCondition)
Map orderBy = ["_id": 1]
boolean hasData = true
Integer limit = 100
//循环聚合所有数据
Map updateData = [:]
Range range = Ranges.of(0,200)
range.each { i ->
if(hasData == false){
return
}
Integer skip = i * limit
def(Boolean error,QueryResult result,String errorMessage) = Fx.object.find("object_tsfnr__c", searchCondition, orderBy, limit, skip)
if(error){
hasData = false
Fx.log.info("查询失败" + "当前跳过的数量为 " + skip + "错误原因为" + errorMessage)
return
}
//获取所有更新的数据,如果是预设对象,就在循环里面直接更新。
List dataList = result.dataList
if(dataList.size() < limit){
hasData = false
}
//如果不需要合并数据,在这里就可以100条
dataList.each{ item ->
Map objectData = item as Map
updateData.put(objectData._id,["field_SNdj9__c":"5f587913bb60d50001afffa1"])
}
}
//极端情况,所有查询都失败了
if(!updateData){
Fx.log.info("循环查询出来数据为空")
return
}
//如果是自定义对象,直接调用批量更新即可,更新单次500条限制,所以我们拆分数据
List idList = updateData.keys() as List
List partitionList = Fx.utils.listPartition(idList,500)
partitionList.each{ item ->
Map currentUpdateMap = [:]
//根据id分批组装数据
List ids = item as List
ids.each{ id ->
String stringId = id as String
Map totalMap = updateData
Map updateMap = totalMap[stringId] as Map
currentUpdateMap.put(id,updateMap)
}
//获取这一批的数据,然后调用批量更新接口
def updateResult = Fx.object.batchUpdate("object_tsfnr__c",currentUpdateMap)
if(updateResult[0]){
Fx.log.info("更新失败 原因为 " + updateResult[2])
}else{
Fx.log.info("更新成功")
}
}
Fx.log.info("实际更新的数据为" + idList.size())