function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kyle Morris 15Kyle Morris 15 

bulkify SOSL query

I am trying to write a trigger that, given a string, will search SFDC for an account using SOSL. 

This is working when you update/insert a few leads but if you go beyond ten or so I'm getting an error: `CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: LeadTrigger: System.LimitException: Too many SOSL queries: 21 []`

The obvious issue is that I have my SOSL query within the FOR loop. That said, I can't seem to figure out how to bulkify this query. I've tried creating a list of matched names and then pass that list into the SOSL query but I can't seem to iterate through that and match the accounts to the appropriate lead.

I need to use SOSL rather than SOQL in this case because SOQL + LIKE isn't working, it's too broad.
public class LeadTriggerHelper {
        
        Public static void UpdateLead(List<Lead> Leads){
            for(Lead ld1 : Leads){
                String accountName;
                accountName = ld1.cleaned_email__c;

                List<List<Account>> matchedAccount = [FIND :accountName IN NAME FIELDS RETURNING Account LIMIT 1];

                if(matchedAccount.size()>0){
                    ld1.Account_Lookup__c = matchedAccount[0][0].Id;
                } else {
                    System.debug('No Account Found');
                }   
            }
        }
    }



    trigger LeadTrigger on Lead (before insert, before update) {
        if(trigger.isBefore){
            if(trigger.isInsert){
                for (Lead lead : Trigger.new){
                    if((lead.email != '' || lead.website!='') && lead.Trigger_Account_Update__c >=0){
                        LeadTriggerHelper.UpdateLead(trigger.new);                                    
                    }
                }
            }
            If(trigger.isUpdate){
                for (Lead lead : Trigger.new){
                    Lead oldLead = Trigger.oldMap.get(lead.Id);
                    if (oldLead.Trigger_Account_Update__c != lead.Trigger_Account_Update__c){
                        System.debug('updating lead');
                        LeadTriggerHelper.UpdateLead(trigger.new);                        
                    }
                }

            }
        }
    }

 
Amit Chaudhary 8Amit Chaudhary 8
Issue is coming because of SOSL inside the for loop. Please change your logic and remove SOSL from loop