SFDC Stop - Always the latest about Salesforce

Full Tutorial Series with videos, free apps, live sessions, salesforce consulting and much more.

Telegram logo   Join our Telegram Channel

Tuesday 30 April 2024

Unlocking the Power of Einstein Search in Salesforce

Hello Trailblazers,

In this post, we're going to learn about Einstein Search in detail. This post is contributed by Dorian Sabitov who's a 4x certified Salesforce Admin and Developer. You can learn more about Dorian in the Author's Bio section at the end. I really liked the post as I reviewed it and I hope you'll like it too. Let's talk about Einstein Search now:

Introduction: Einstein Search

Salesforce, recognized as the leading CRM platform, has continually evolved to meet the dynamic needs of businesses by integrating advanced AI capabilities. This commitment is illustrated through the development of Einstein Search, a tool designed to transform how users interact with and retrieve information from Salesforce by leveraging AI-driven search functionalities.

Einstein Search, part of the broader Einstein AI suite within Salesforce, is specifically engineered to enhance the efficiency and accuracy of search results for its users. Unlike traditional search mechanisms that offer basic query capabilities, Einstein Search utilizes artificial intelligence, machine learning, and natural language processing to deliver a more intuitive and context-aware search experience. This smart search functionality understands the user's intent and provides results that are tailored to their specific needs, thereby significantly improving productivity and user experience.


Did you know that based on the Salesforce Trailhead Module, Get Started with Einstein Search, searching is a fundamental aspect of daily activities, whether it's completing tasks or solving issues? Einstein Search enhances this process by making it quicker, simpler, and more precise. This efficiency boosts user productivity significantly. In fact, studies indicate that using Einstein Search can increase productivity by as much as 50%, saving both time and resources.

Recent updates have further enriched Einstein Search, such as the introduction of Einstein GPT, which integrates generative AI capabilities to offer even more refined and personalized search outcomes. This integration illustrates Salesforce's commitment to harnessing cutting-edge technology to serve complex business needs more effectively​.

The evolution of Einstein Search is indicative of Salesforce's broader strategic vision, which involves a significant focus on AI and data integration through platforms like Data Cloud (formerly Genie). These advancements not only enhance the functionality of Einstein Search but also broaden its applicability across various business contexts, making Salesforce a more powerful tool for enterprises aiming to optimize their customer relationship management practices​​.

Stay tuned as we delve deeper into the specifics of Einstein Search in the following sections, exploring its features, setup process, and best practices to maximize its utility within your Salesforce environment.

Image Source: Salesforce, Supercharge Productivity with Einstein Search

Understanding Einstein Search: Capabilities and Technology

Einstein Search represents a leap forward from traditional Salesforce search tools by integrating state-of-the-art AI technologies. It goes beyond mere keyword matching, incorporating machine learning, natural language processing, and even conversational AI to understand and predict user needs.

Key Features of Einstein Search

Personalized Search Results: Einstein Search delivers tailored results based on the user's Salesforce activity and profile, ensuring that the information is highly relevant to the individual's specific tasks and roles.

Natural Language Processing (NLP): Users can interact with Salesforce using natural language queries, such as "Show me high-priority cases from the last week", making the search experience more intuitive and aligned with everyday language.

Predictive Search Capabilities: Einstein Search can anticipate user needs based on their interaction patterns and context within Salesforce, suggesting relevant records and files even before a full query is entered.

These features are built on the backbone of Salesforce's AI-driven platform, powered by Einstein AI, which leverages a deep understanding of CRM data to enhance user experiences dramatically. The integration of conversational AI assistants in every CRM application further expands the capabilities of Einstein Search, allowing for a more dynamic interaction between the user and the platform​​.

Technology Behind Einstein Search

Einstein Search is powered by several cutting-edge technologies:

  • AI and Machine Learning: These core technologies enable the system to learn from data, improving its accuracy and effectiveness with each interaction.
  • Data Cloud: Formerly known as Genie, this platform supports Einstein Search by managing real-time data, which is crucial for delivering accurate and up-to-date search results. The introduction of vector databases in the Data Cloud enhances its capability to handle and retrieve unstructured data, which is essential for comprehensive search functionalities​.

  • Einstein GPT: Recently introduced, this generative AI model within Salesforce enhances Einstein Search by enabling it to understand and generate human-like text responses. This technology not only improves how search results are delivered but also adds a layer of predictive analytics, offering suggestions based on the inferred needs of the user​.

Differences Between Einstein Search and Traditional Salesforce Search

The traditional Salesforce search functionality primarily relied on keyword-based queries with limited context understanding, often resulting in a broad range of results that required further refinement. In contrast, Einstein Search uses AI to understand the context of queries, delivering more precise and relevant information. This AI-driven approach not only speeds up the retrieval process but also ensures that the results are aligned with the user’s immediate needs.

The advancements in Einstein Search signify Salesforce's shift towards a more intelligent, efficient, and user-centric platform. With its ability to process natural language queries and its integration of AI to personalize search results, Einstein Search stands out as a sophisticated tool within the Salesforce ecosystem.

Image Source: Salesforce, Supercharge Productivity with Einstein Search

Key Benefits of Einstein Search in Salesforce

Einstein Search Salesforce not only enhances the search experience by integrating advanced AI technologies but also brings several key benefits that can significantly improve productivity and decision-making within organizations.

Efficiency and Speed

Einstein Search drastically reduces the time users spend searching for information. By understanding the context and intent behind queries through NLP and AI, it provides faster and more accurate results, enabling users to find the necessary data without navigating through multiple layers of the CRM.

Enhanced Data Accessibility

With the ability to handle and make sense of unstructured data, Einstein Search allows users to access a wider range of information types, including emails, PDFs, and social media content. This capability is largely supported by the new Data Cloud Vector Database, which helps manage unstructured data at scale​​.

Image Source: Salesforce, Data Cloud Vector Database

Improved Decision Making

By delivering personalized and contextually relevant search results, Einstein Search helps users make better-informed decisions quickly. The predictive search capabilities suggest relevant files and records, potentially uncovering insights that users may not have explicitly searched for but find highly valuable​​.

User Adoption and Satisfaction

The intuitive nature of Einstein Search, with its ability to understand natural language queries, enhances user adoption and overall satisfaction. Users are more likely to engage with a system that responds in a familiar, conversational manner, thus driving higher productivity across the organization​​.

Enabling and Configuring Einstein Search

Implementing Einstein Search within your Salesforce environment involves a few key steps to ensure that it is tailored to meet your organization's specific needs.

Step 1: Enable Einstein Search

When you access your Salesforce Org, Einstein AI Salesforce Search is already active and integrated by default. To verify this, go to Setup and enter 'Einstein Search' in the Search bar.

Step 2: Configure Data Sources

Administrators need to define which objects and fields Einstein Search should index. This step is crucial as it determines the breadth of data available for search queries. It involves selecting data from both structured and unstructured sources, ensuring comprehensive coverage. Select Search Manager to understand which Objects are selected as Data Sources.

Step 3: Set Up Permissions

Setting the correct permissions is vital to maintain data security and integrity. Permissions ensure that users can only search for and access data they are authorized to view, complying with organizational data policies and regulations.

Creating and Assigning Permission Sets

Accessing Permission Sets:

  • Open the Setup menu in Salesforce.
  • Use the Quick Find box to search for "Permission Sets" and select it from the Users or Security sections.

Creating a New Permission Set:

  • Click on New.
  • Provide a name and a description for the permission set that describes its use, like "Einstein Search Access".
  • Select the type of Einstein Search license, then click Save.

Setting System Permissions:

  • Click on System Settings within the permission set.
  • Select and enable the settings related to Einstein Search

Assigning the Permission Set:

  • From the permission set details, select Manage Assignments.
  • Click on Add Assignments.
  • Find and select the users or groups who need access to Einstein Search.
  • Confirm by clicking Assign and then finalize with Done.

Step 4: Customize Search Settings

Einstein Search offers various customization options, such as creating synonyms for common search terms or setting up preferred results for frequently searched terms. These settings help refine the search experience to align more closely with user expectations and organizational terminology.

Step 5: Train Users

Finally, training end-users on how to use Einstein Search effectively is essential. This includes educating them on how to perform natural language queries and utilize the predictive search features to their full advantage.

By following these steps, organizations can harness the power of AI-driven search to enhance their Salesforce experience, making data retrieval not only faster but also more relevant and aligned with their operational needs.

Maximizing the Impact of Einstein Search: Best Practices and Practical Tips

To fully leverage the capabilities of Einstein Search within Salesforce, organizations should adopt certain best practices, einstein search recommendations, and strategies. These approaches help ensure that the search tool is as effective and efficient as possible, enhancing user experience and data accessibility across the board.

Best Practices for Einstein Search

Maintain High-Quality Data: The effectiveness of AI-driven tools like Einstein Search is heavily dependent on the quality of the underlying data. Ensuring data is accurate, up-to-date, and consistently formatted across Salesforce ensures that the search results are reliable and relevant​​.

Regularly Update and Review Search Configuration: As organizational needs evolve, so should the configurations of your search settings. Regular reviews and updates help adapt the search functionalities to changing business requirements, such as adding new data sources or adjusting permissions and security settings​.

Utilize Feedback for Continuous Improvement: Encourage users to provide feedback on their search experiences. This input is invaluable for refining search functionalities and addressing any issues that might arise. Regularly analyzing search usage patterns can also provide insights into how to further optimize the tool​.

Practical Tips for Using Einstein Search

Training and User Adoption: Conduct comprehensive training sessions for all users to familiarize them with the new search capabilities. Highlight features like natural language queries and predictive search to help them get the most out of Einstein Search.

Leverage Natural Language Queries: Encourage users to make the most of Einstein Search’s NLP capabilities by using conversational language for queries. This approach tends to yield more accurate and relevant results compared to traditional keyword-based searches.

Customize Search for Specific Roles: Tailor the search experience for different user roles within the organization. For example, sales teams might benefit from quick access to customer interaction histories, while marketing teams might prioritize campaign data. Customizing search settings to suit these needs can enhance productivity and efficiency​​.

By following these best practices and utilizing the practical tips provided, organizations can maximize the benefits of Einstein Search. This powerful tool streamlines access to information and enhances decision-making processes, ultimately contributing to greater business success. As Salesforce continues to evolve, staying updated with the latest enhancements and integrating them into your workflow will ensure that your organization remains at the cutting edge of CRM technology.

Final Thoughts

Einstein Search is more than just a search tool; it's an innovation within Salesforce that brings smarter, faster, and more relevant data access to your fingertips. Utilizing technologies like machine learning, natural language processing, and conversational AI, this tool provides a user experience that's not only efficient but also incredibly natural and intuitive. Users can expect search results that are finely tuned to their needs, thanks to AI's ability to learn and adapt from interactions and data patterns​​.

The integration of the Data Cloud and recent enhancements such as Einstein GPT enrich this experience further, allowing users to delve deeper into their data—be it structured or unstructured. This comprehensive access facilitates more informed decision-making and efficiency across various business operations​.

For organizations that adopt and adapt to Einstein Search effectively, the rewards include not just accelerated data retrieval but also a broader spectrum of actionable insights. Following best practices—like ensuring data integrity, customizing search settings to fit specific roles, and actively seeking user feedback—can significantly enhance the utility and success of implementing this sophisticated tool​​.

Looking ahead, the trajectory for search technologies within Salesforce promises even more innovation and refinement. Continued advancements in AI and machine learning are expected to further enhance the capabilities of Salesforce Einstein Search, offering even more precise and context-aware solutions to meet complex business demands.

Author's bio

Dorian Sabitov is a four-time certified Salesforce Administrator and Developer who specializes in adapting Salesforce to meet specific client requirements. His IT career began in a CRM administrative role, concentrating primarily on the Salesforce ecosystem. Dorian enjoys discovering new integrations within Salesforce and identifying innovative methods to enhance business processes within the CRM. Presently, he works full-time as a Salesforce developer and contributes educational material to the SFApps.info portal

I hope you liked this post by Dorian. Let me know your feedback in the comments down below. If you would like to contribute an article to SFDC Stop as well, feel free to fill this form here.

Happy Trailblazing!!

Thursday 25 April 2024

Building Blocks of Apex: Variables & Data Types Explained Simply - Salesforce Apex Tutorial Part 2 to 4 | Code Snippet

Hello Trailblazers,

In this post, I'm sharing the code snippet for Coding with Confidence: The Fun Way to Learn Salesforce Apex tutorial series part 2 to 4 below:
// * Variables & Data Types in Apex


? What is a variable?
* A variable is simply a named storage/memory location that contains a value. In apex, all variables have a "data type".
! Each variable is by default initialized to null

? What is a Data Type?
* Data type is a keyword associated with a variable. It basically represents the type of data which that variable will store.
* List of primitive data types:
* 1. Boolean
* 2. Integer
* 3. Decimal
* 4. Double
* 5. Long
* 6. Date
* 7. Datetime
* 8. Time
* 9. Id
* 10. String
* 11. Object
* 12. Blob

* These are the OOTB or fundamental data types available in apex programming language. Let's talk about each one of them in detail:

? What is a Boolean data type?
* A variable of Boolean data type can store only one of these two values:
* 1. True
* 2. False

* Example of Boolean data type:



// comment

// * In order to declare a variable, we follow the format: <Data Type><space><Variable name><;>
Boolean isQualified;
System.debug('Value of isQualified boolean variable is: ' + isQualified);

isQualified = false; // * Equals (=) means Assignment
System.debug('Value of isQualified boolean variable is: ' + isQualified);

isQualified = true;
System.debug('Value of isQualified boolean variable is: ' + isQualified);

// isQualified = 123;


? What is an Integer data type?
* An Integer data type can store a 32-bit number with no decimal point. It can store value between -2,147,483,647 to 2,147,483,647

* Example of Integer data type:


Integer sum;
System.debug('Value of sum Integer variable is: ' + sum);

sum = 1;
System.debug('Value of sum Integer variable is: ' + sum);

sum = 10;
System.debug('Value of sum Integer variable is: ' + sum);

sum = 2147483647;
System.debug('Value of sum Integer variable is: ' + sum);

sum = -2147483647;
System.debug('Value of sum Integer variable is: ' + sum);

// sum = false;

YouTube Tutorials

You can check out the tutorials below as well:

Building Blocks of Apex: Variables & Data Types Explained Simply - Salesforce Apex Tutorial Part 2

Apex Gotchas! Common Variable Errors (and Writing Comments) - Salesforce Apex Tutorial Part 3

Apex Integer Data Types: Understanding Limits & Avoiding Errors - Salesforce Apex Tutorial Part 4

Check out the tutorials and let me know your feedback in the comments down below.

Happy Trailblazing!!

Sunday 24 March 2024

FlowError: The number of results does not match the number of flow interviews | Building invocable actions The Right Way!

Hello Trailblazers,

In this post we're going to learn, how we can build apex invocable actions The Right Way. It might be possible that you've faced this issue in the past:

FlowError: The number of results does not match the number of flow interviews

Today, we're going to build an apex invocable action, call it from flow in a scenario such that it fails and then fix the error to make sure it works perfectly fine. Let's Begin!

Use Case

We have a custom object named Application (Application__c), the details of that object are provided below:
As you can see above, our name field is Application ID which is an auto number. We have 3 custom fields:

1. Candidate Name (CandidateName__c): This is a text field with length 255. It'll store the name of our candidate who has submitted the application
2. Candidate Phone (CandidatePhone__c): This is a phone field. It'll store the phone number of our candidate
3. Lead (Lead__c): This is a lookup to standard lead object. For each new application, if the candidate is not present as a lead in salesforce, we'll create a new lead in salesforce and will tag that lead to our application record. If a lead is already present in salesforce, we'll tag that existing lead to our application record as well.


How do we check whether we should create a new lead or use an existing lead?

We're going to do that using candidate's phone number in the application. If there exists a lead with the same phone number as that of a candidate, we're going to tag that lead to the application record as it's created. Otherwise, we're going to create a new lead with that phone number and candidate's name and we're going to tag that lead to our application record.

So, we can say that our Application's CandidatePhone__c will map to Lead's Phone field. We need an automation (flow) to create lead records automatically and tag them to application records as these are created. We'll create that flow soon.

Platform Encryption

For security reasons, we've turned on platform encryption in our salesforce org and the lead's Phone field is encrypted as shown below:
If we click on Select Fields button above in Encrypt Standard Fields section, we'll get the below page, where we've encrypted Lead's Phone field as shown below:
This encryption will create one challenge in building our flow, which we'll see soon. Let's build a flow now.

Building a Flow

We need a Record Triggered flow which will fire when an application record is created. It'll check if an existing lead record is present with Phone = CandidatePhone__c or not. If yes, it'll tag that record with the application record. Otherwise, it'll create one new lead record using CandidatePhone__c and CandidateName__c and will tag that new lead record to our application record.

Got to Setup, search for flow, and click on the New Flow button as shown below:
You'll get the below screen:
Choose Record-Triggered flow as shown above and click Create.

Choose the object as Application, this flow will run when an application record is created, in After context as shown below:
Click on the Save button to save the flow. The details are provided below:
Flow Label: Tag Lead to Application
Flow API Name: Tag_Lead_to_Application
Description: This flow will tag a lead record to the application record as it's created.

Click on Save button in the dialog to save the flow.

Now, our flow is saved. The first step is to query lead records where Phone = CandidatePhone__c. We're going to use a Get element to query records as shown below:
We only need the Lead Id here, so we're querying only that:

Problem in the Flow

Let's save the flow once by clicking the Save button. As you try to save the flow, you'll get an error as shown below:
It says: Because Lead's Phone field is encrypted, our flow cannot reference that field. We need to remove this reference in order to save the flow. This means that we cannot query our existing lead records by filtering through Phone field. In order to achieve this functionality now, it's time to move to Invocable Apex.

Resolution: Invocable Apex

We're going to create a new apex class which will help us in querying the leads by phone number. The code for the same is provided below:
public class LeadQueryAction {

    * This method will query leads by phone numbers and return the list of lead ids
    @InvocableMethod(label='Get Leads by Phone Numbers' description='Return lead records filtered by phone numbers' category='Lead')
    public static List<Id> queryLeadsByPhoneNumbers(List<String> phoneNumbers) {
        Map<Id, Lead> leadsMap = new Map<Id, Lead>([SELECT Id FROM Lead WHERE Phone IN :phoneNumbers]);
        return new List<Id>(leadsMap.keySet());
As you can see above, we have a class named LeadQueryAction. This class has a method named queryLeadsByPhoneNumbers(List<String> phoneNumbers). This method will receive the list of phone numbers from flow, will query the leads using those phone nunbers and will return the list of lead ids. We're querying lead records using SOQL query: [SELECT Id FROM Lead WHERE Phone IN :phoneNumbers];. We're converting the queried lead records list directly into a Map<Id, Lead> named leadsMap so that we can get the lead ids easily using this map. Finally, we're returning the list of lead ids by converting lead ids set into a list using new List<Id>(leadsMap.keySet());

Also, note that in the @InvocableMethod annotation, we've specified the label as Get Leads by Phone Numbers and description as Return lead records filtered by phone numbers. We've also specified the category as Lead. This label will be visible in our flow when we'll search for our invocable action.

Our apex class is ready now, let's get back to our flow and call this method.

First of all, let's delete the Get element as we're going to query lead records using our invocable apex method now:

Click on the + icon again and search for Get Leads by Phone Numbers action as shown below:
Notice that our invocable method's label and description are visible here. Choose this action and you'll get the New Action dialog as shown below:
Alternatively, you can also search for action, click the Action option and then search for Get Leads by Phone Numbers action as shown below:
You'll get the new Action dialog here as well as shown below:
In our New Apex Action dialog, fill the following information as shown below:
Label: Get Existing Leads
API Name: Get_Existing_Leads
Description: This element will get ids of existing lead records where Phone = CandidatePhone__c

Click on Include button to pass information to phoneNumbers parameter of our invocable apex method and let's bind it with CandidatePhone__c field of our current application record {!$Record.CandidatePhone__c}.

Click on Done.

Now, our Get Existing Leads apex action will provide us the id of the lead (if it exists) which is present in our salesforce org where Phone = CandidatePhone__c for our current application record.

We need to check, if a lead id is returned by our method or not. If a lead id is returned, the existing lead id will be populated in our application's Lead__c lookup. Otherwise, we'll create a new lead record and will populate it's id in our application's Lead__c lookup field.

To check this, we are going to add a decision element as shown below:

Label: Is lead present?
API Name: Is_lead_present
Description: This decision element will check if an existing lead with the candidate's phone number is present in the system or not

Outcomes will be Yes and No (the default outcome from the decision is renamed to No). For the outcome to be Yes, we're checking that the Text from Get_Existing_Leads {!Get_Existing_Leads} (which is nothing but our Lead Id) should not be Blank.

If the outcome of the decision is Yes, we'll update our applicaton record using an update element as shown below:

We'll choose Update Triggering Record option as we want to update lead id on the same record which fired the flow:

The details added in this Update Triggering Record element are provided below:

Label: Update existing lead id on application
API Name: Update_existing_lead_id_on_application
Description: This element will update the Lead__c on application with the lead id received from Get Existing Leads invocable action
How to Find Records to Update and Set Their Values: Use the application record that triggered the flow
Set Field Values for the Application Record: Lead__c = {!Get_Existing_Leads}

If outcome of the decision is No, we'll create a new Lead record and tag that to the application record as shown below:

We'll add a Create Records element in our No path as shown above. The details added in the Create Records element are provided below:

Label: Create new lead
API Name: Create_new_lead
Description: This element will create a new lead record using the candidate details from application record
How Many Records to Create: One
How to Set the Record Fields: Use separate resources, and literal values
Object: Lead
Set Field Values for the Lead:
LastName = {!$Record.CandidateName__c}
Phone = {!$Record.CandidatePhone__c}

As Company field is mandatory on lead, let's add that as well in our Create Records element with a value as SFDC Stop as shown below:
Company = SFDC Stop
This element will create a new lead record for us. Let's update our application record with this lead id. For this, we'll add an Update Triggering Record element again as shown below:
The details added in the Update Triggering Record element are provided below:

Label: Update new lead id on application
API Name: Update_new_lead_id_on_application
Description: This element will update the Lead__c on application with the lead id received from Create new lead action
How to Find Records to Update and Set Their Values: Use the application record that triggered the flow
Set Field Values for the Application Record: Lead__c = {!Create_new_lead}

Let's save our flow by clicking the Save button.
Once saved, activate the same by clicking the Activate button.
Now, it's time to test our flow!

Let's go to the Applications tab in our salesforce org and create a new Application record as shown below:
We've kept the Lead lookup as empty. The Candidate Name is Richard Hendricks and Candidate's Phone is 9999999999. As we click on Save, our flow will create a new lead record for us, as a lead record with this phone number is not already present in salesforce and it'll tag the newly created lead to our application record as shown below:
As you can see above, a lead record named Richard Hendricks is tagged. The Phone is the same as Candidate Phone in our application record and the Company is SFDC Stop.

Now, let's try creating another application record using the same details as shown below:
You'll notice that as the record is created, the same (already existing) lead is tagged to this application record:
Note: You can verify the lead ids of both the lead records tagged to application records to make sure that the same lead record is tagged to both the application records.

This means that our flow and invocable apex method is working perfectly fine. But What will happen if we have more than one application records? Let's test it!

Flow: Bulk Testing

Let's consider a scenario where we're creating two application records in a single transaction. Both the application records should be connected to the same lead record. The code snippet to create these applications is provided below:
List<Application__c> applications = new List<Application__c>();
applications.add(new Application__c(CandidateName__c = 'Richard Hendricks', CandidatePhone__c = '9999999999'));
applications.add(new Application__c(CandidateName__c = 'Richard Hendricks', CandidatePhone__c = '9999999999'));
insert applications;
As you can see above, we're inserting a list of applications with 2 records. Both the records are by the same candidate, so, ideally the same lead record should be tagged to both the applications. When we execute this code snippet, we get the result as shown below:
As you can see above, our flow is failing and we're getting an error. In our case, it's not showing the exact issue but in some scenarios it'll show the actual error like: FlowError: The number of results does not match the number of flow interviews

This error basically means that the invocable method is not returning the list of same size as it was passed to the method while calling it from flow. Let's debug this by using the below code snippet:
List<String> phoneNumbers = new List<String>{'9999999999','9999999999'};
In the above snippet, we're calling our invocable action method directly and passing a list of two phone numbers which are exactly the same as of our Richard Hendricks lead record. The output when the above code snippet is executed is provided below:
If you remember, our invocable method has some System.debug() statements, I'm sharing those again below for your reference:
The first debug statement is displaying the list of phone numbers received by our invocable method in parameter. It's showing both the phone numbers as: (9999999999, 9999999999). This is perfectly all right. 

We queried our lead records using these phone numbers and got the following ids in our leadsMap.keySet() which is used in the second debug statement: {00QH40000010giZMAQ}. As you can see, we're getting only one lead id in this set as there's a single lead record present in the system with this phone number.

The third debug statement which is coming from System.debug(LeadQueryAction.queryLeadsByPhoneNumbers(phoneNumbers)); is showing the same lead id in a list instead of a set as: (00QH40000010giZMAQ). This means that the list of lead ids which is returned from our invocable method is having only one lead id, however, we passed 2 phone numbers in this method to query and get our related lead records. 

This is why our flow is failing because when our flow is running for 2 records created in the same transaction, we have 2 flow interviews. As the flow is bulkified, the phone numbers list passed to our invocable method consist of 2 phone numbers however our method returned only a single lead id in the list of ids. Therefore, The number of results (lead ids) does not match the number of flow interviews. These metrics (debug statements) are also visible in the earlier logs when we tried to create our application records as shown below:
You can see above that the phoneNumbers list has two phone numbers whereas the leadsMap.keySet() has a single lead id.

In order to make our invocable method work correctly, we need to return the list of lead ids of same size as the size of our input list i.e. the list of phone numbers. Let's fix our invocable method now.

Issue Resolution for "FlowError: The number of results does not match the number of flow interviews"

In order to fix our invocable method, we'll do the following:

1. Query our lead records.
2. Create a map of lead phone to lead id
3. Loop our phone numbers and check: If we have a lead id corresponding to the current phone number, add it to the lead ids list, otherwise, add null to the lead ids list.
4. Return the list of lead ids.

This will ensure that the order of phone numbers received and the lead ids corresponding to those phone numbers remains aligned, it's important to ensure that our flow behaves correctly. The updated code for our invocable action class is provided below:
public class LeadQueryAction {

    * This method will query leads by phone numbers and return the list of lead ids
    @InvocableMethod(label='Get Leads by Phone Numbers' description='Return lead records filtered by phone numbers' category='Lead')
    public static List<Id> queryLeadsByPhoneNumbers(List<String> phoneNumbers) {
        List<Id> leadIds = new List<Id>();
        List<Lead> leads = [SELECT Id, Phone FROM Lead WHERE Phone IN :phoneNumbers];
        Map<String, Id> leadPhoneNumberToIdMap = new Map<String, Id>();
        for(Lead lead : leads) {
            leadPhoneNumberToIdMap.put(lead.Phone, (Id) lead.Id);
        for(String phoneNumber : phoneNumbers) {
            if(leadPhoneNumberToIdMap.containsKey(phoneNumber)) {
            } else {
        return leadIds;
As you can see above, we created a list of lead ids named leadIds. This list will store our lead ids which we'll return from our method. Then we queried the lead records as we were doing earlier. This time, we're storing it in a list named leads.

Now, we created a Map<String, Id> named leadPhoneNumberToIdMap. This map will store our lead phone number and the corresponding lead id. We looped all the queried lead records to populate this map. Finally, we looped the phone numbers which we received in our method, we then checked: if our leadPhoneNumberToIdMap contains the current phone number as a key, we'll add the corresponding lead id to the leadIds list, otherwise, we'll add null to our leadIds list. Adding null basically means that for the current phone number, we don't have any lead present in salesforce. Note that a list can have multiple null values.

Let's save our updated apex class and run the below code snippet to test our flow once again. This time we'll create 4 application records as shown below:
List<Application__c> applications = new List<Application__c>();
applications.add(new Application__c(CandidateName__c = 'Richard Hendricks', CandidatePhone__c = '9999999999'));
applications.add(new Application__c(CandidateName__c = 'Erlich Bachman', CandidatePhone__c = '9999999991'));
applications.add(new Application__c(CandidateName__c = 'Richard Hendricks', CandidatePhone__c = '9999999999'));
applications.add(new Application__c(CandidateName__c = 'Gavin Belson', CandidatePhone__c = '9999999992'));
insert applications;
If you notice above, the first and third application records have the same candidate Richard Hendricks with the same phone number as: 9999999999, so, our flow should link the existing lead to both the application records. However, the second and fourth application records have different candidates i.e. Erlich Bachman and Gavin Belson with different phone numbers. So, our flow should create new leads and link them with our application records.

Currently, we only have 2 application records in the system that we created earlier as shown below:

Now, as we execute our code snippet, we get the below output:
Notice that we got 4 new applications created as shown above. The first and third application records are linked with the same lead Richard Hendricks, however, the second and fourth records are linked with new lead records i.e. Erlich Bachman and Gavin Belson

This time our invocable method is working Perfectly Fine! and the flow is not failing. You can add debug statements in this method to see how it works. However, I'm displaying the output we get from our invocable method as it's called internally using the below code snippet:
List<String> phoneNumbers = new List<String>{'9999999999', '9999999993', '9999999999', '9999999994'};
If you notice above, the first and third phone numbers are the same i.e. 9999999999 however, the second and fourth phone numbers are different i.e. 9999999993 and 9999999994 as was there in our application records. I didn't use 9999999991 and 9999999992 here because now we have leads present in the system linked with these phone numbers. When we execute this code snippet, the output list of lead ids which we got from our method is as shown below:
As you can see above, in our output, the first and third entry in our list is the lead id of Richard Hendricks lead and it's the same. However, the second and fourth entry in our list is coming as null because there are no leads for these phone numbers present in salesforce.

Therefore, we passed 4 phone numbers and got a list of 4 elements i.e. lead ids. Now, we can say that: The number of results match the number of flow interviews.

That's all for this tutorial everyone, I hope you liked it, let me know your feedback in the comments down below.

Happy Holi! Get my Mastering Lightning Datatable in Salesforce LWC course at best price using the coupon code "HAPPYHOLI". You can get the same by clicking this link: https://www.udemy.com/course/mastering-lightning-datatable-in-salesforce-lwc/?couponCode=HAPPYHOLI

Happy Trailblazing!!