+ Start a Discussion

Batch Apex Help

This is my first time creating Batch Apex.  I'm looking to count similar records in a custom object and create records within that object based of this count.  I'm looking to see if anyone can point me in the right direction to get started.  I've read a bunch on Batch Apex and seen the example of reassigning Account owners, but my scenario is a little different.


Below is my scenario:


Custom_Object__c - This is the object where there will be 200,000 records imported each month.

Number_Reference__c - This will be the field in which may have duplicate values

Contact_Reference__c - This will be the name of the Contact

Number_Count__c - This will be a sum field that will populate in a record after the Batch Apex is ran.


Month 1, the user imports records.  Let's say that 500 of these records have the same Contact_Reference__c and the same Number_Reference__c.  For example, there are 500 records where John Doe has the number 123 in the Number_Reference__c.  Now, when the user presses a button to run the Batch Apex, it will detect that John Doe has 500 identical records, (meaning records with the same Number_Reference__c and Contact_Reference__c fields), and will then create a record in the same object that equal the following fields:  

Contact_Reference__c = John Doe

Number_Reference__c = 123

Number_Count__c = 50


Thanks in advance for any guidance.







You probably don't need batch APEX to do this. You could use aggregate queries instead: Docs here


The SOQL syntax woudl be like this:

SELECT Contact_Reference__c, Number_Reference__c, COUNT()

FROM Custom_Object__c

GROUP BY Contact_Reference__c, Number_Reference__c



Provided there aren't more than 50,000 contacts that have duplicate records, you should be able to run this without a batch. If it is greater than 50K, you will need to run it in a batch, but I would still use this same query.


Thanks MIke, would this query to into my Start method of the Batch?  


That is correct. Put the query in the start method.


Hey Mike, so I ended up filling up a nested map to hold the data I need to populate new records within my batch apex class.  But I was wondering if you had any pointers as to how I can get values out of this map and insert records:


map<Id, map<Date, set<Decimal>>> conid2datemapmap = new map<Id, map<Date, set<Decimal>>>();


This map holds the Contact ID, and then a date, and the different number of unique numbers there are within the records.  So, I'm trying to create another record within the custom object, like below, but it's not working out for me:


List <Custom_Object__c> newrecord = new List<Custom_Object__c>();


Custom_Object__c custom = new Custom_Object__c (
Contact_Reference__c =  conid2datemapmap.Id, Date_Field__c =  conid2datemapmap.Date, Count_Field__c =  conid2datemapmap.size());

insert newrecord;



I have the full code posted below, but this is the part I'm struggling with: