Recently I was working on a production incident and have found issues with child queries in batch apex where the following stats holds right:
Query: On contact
Total records: ~0.4 million
Child query filters: Two string and one record type check
Issues:
- CPU timeout error
- Batch will not start.
Solution: Removed child query completely and written logic inside execute method. Please follow code snippet given below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global void execute(Database.BatchableContext bc, Contact[] conScopeLst) { | |
Set<id> conIds = new Set<id>(); | |
for (Contact c : conScopeLst) conIds.add(c.Id); | |
Map<Id, list<Contact_Child__c>> conChildMap = new Map<Id, list<Contact_Child__c>>(); | |
for(Contact_Child__c cc : [SELECT Id, contact__c FROM Contact_Child__c WHERE filter1__c = 'filter1' AND filter2__c = 'filter2' AND contact__c =:conIds ]){ | |
list<Contact_Child__c> tempLst = new list<Contact_Child__c>(); | |
if(conChildMap.containsKey(cc.contact__c))tempLst = conChildMap.get(cc.contact__c); | |
tempLst.add(cc); | |
conChildMap.put(cc.contact__c, tempLst); | |
} | |
//rest of the logic: | |
//usage of map | |
//list<Contact_Child__c> list = conChildMap.get(----pass contact record id------); | |
} |
Comments
Post a Comment