Sub topic 14
Finding duplicates in Apex with Datacloud.FindDuplicates
This chapter assumes you know the Salesforce data model, can read basic Apex and SOQL, and have read the earlier chapters on matching rules and duplicate rules. You should know that a duplicate rule points to a matching rule, and that the matching rule decides which records count as alike.
What the method does
Datacloud.FindDuplicates.findDuplicates takes a list of records and returns the existing records that match them. The records you pass in do not need to be saved, and the method inserts nothing. Use it when you want to ask "would this record be a duplicate?" before you decide what to do. Typical cases are a custom screen, an integration that cleans data before loading it, and a trigger that routes likely duplicates for review.
The method does not use whichever rule you pick. It runs the active duplicate rules for each record's object, and each duplicate rule uses its matching rule. If no active duplicate rule exists for the object, you get no matches. This surprises people who test in a sandbox where the rules are still inactive.
A first example
The following code checks one unsaved Contact and prints each possible duplicate.
Contact candidate = new Contact(
FirstName = 'Jon',
LastName = 'Smith',
Email = '[email protected]'
);
List<Datacloud.FindDuplicatesResult> results =
Datacloud.FindDuplicates.findDuplicates(new List<Contact>{ candidate });
for (Datacloud.FindDuplicatesResult findResult : results) {
for (Datacloud.DuplicateResult dupResult : findResult.getDuplicateResults()) {
for (Datacloud.MatchResult matchResult : dupResult.getMatchResults()) {
for (Datacloud.MatchRecord matchRecord : matchResult.getMatchRecords()) {
System.debug('Possible duplicate: ' + matchRecord.getRecord());
}
}
}
}Run it in Anonymous Apex with the debug log open. If your org has an active Contact duplicate rule and a Contact named Jon Smith with a similar email, you will see one debug line per match.
Reading the result structure
The result has four levels of nesting. Each level maps to something you configured in Setup.
| Type | One instance per | Useful methods |
|---|---|---|
| `FindDuplicatesResult` | Input record, in input order | `getDuplicateResults()`, `getErrors()` |
| `DuplicateResult` | Active duplicate rule that ran | `getDuplicateRule()`, `getMatchResults()`, `isAllowSave()` |
| `MatchResult` | Matching rule used by that duplicate rule | `getMatchRecords()`, `getRule()`, `getSize()`, `isSuccess()` |
| `MatchRecord` | Matched existing record | `getRecord()`, `getMatchConfidence()`, `getFieldDiffs()` |
Three details matter in practice:
- The outer list lines up with the input list. Index 0 of the result belongs to index 0 of the records you passed in.
- A duplicate rule that finds nothing still produces a
DuplicateResult. ItsMatchResulthas no match records. CheckgetSize()or the list length, not just whether the result exists. - With a fuzzy matching rule,
getMatchConfidence()gives a score for each match. Exact matches report 100. Use the score if your code needs to treat strong and weak matches differently.
Running more than one record
You can pass a list. Salesforce compares each record against existing data, and the results come back per record. Keep the list small. The method is documented with a limit of 50 records per call, and the call counts against governor limits, including SOQL query rows and DML-independent limits that apply to the matching work. Check the current Apex Developer Guide for exact numbers, because they change between releases.
Here is a helper that returns only the inputs that have at least one match. It uses the input order to pair each record with its result.
public with sharing class DuplicateChecker {
public static Map<Integer, List<SObject>> findMatches(List<SObject> candidates) {
Map<Integer, List<SObject>> matchesByIndex = new Map<Integer, List<SObject>>();
List<Datacloud.FindDuplicatesResult> results =
Datacloud.FindDuplicates.findDuplicates(candidates);
for (Integer i = 0; i < results.size(); i++) {
List<SObject> found = new List<SObject>();
for (Datacloud.DuplicateResult dupResult : results[i].getDuplicateResults()) {
for (Datacloud.MatchResult matchResult : dupResult.getMatchResults()) {
for (Datacloud.MatchRecord matchRecord : matchResult.getMatchRecords()) {
found.add(matchRecord.getRecord());
}
}
}
if (!found.isEmpty()) {
matchesByIndex.put(i, found);
}
}
return matchesByIndex;
}
}Two duplicate rules can find the same existing record, so found may contain the same record twice. If that matters, collect Ids in a Set<Id> instead of a list.
What the method respects, and what it ignores
The method follows the same configuration the user interface uses, with some differences you should know about.
- Rule conditions and active status. Only active rules run. Conditions on a duplicate rule, such as limiting it to certain record types, apply to the record you pass in. Fill in those fields on the candidate, or the rule may not run.
- Sharing. A duplicate rule can compare against all records or only records the user can see. Apex class sharing is set by your class declaration. Declare
with sharingif you want the check to reflect the running user's visibility, and review the rule's own sharing setting too. - Actions. The rule's action (allow, block, alert, report) does not stop
findDuplicates. Nothing is blocked because nothing is saved. The result tells you what the rule found, andisAllowSave()onDuplicateResulttells you whether a save would be allowed under that rule's action. - Reports and record sets. Calling the method does not create duplicate record sets. Those are created when rules run on a real save.
Using the result to decide
A common design is to call findDuplicates, then decide what to do based on the match count and confidence. This example blocks high-confidence matches and flags weaker ones.
public with sharing class LeadIntake {
public static void checkLead(Lead newLead) {
List<Datacloud.FindDuplicatesResult> results =
Datacloud.FindDuplicates.findDuplicates(new List<Lead>{ newLead });
Double best = 0;
for (Datacloud.DuplicateResult dupResult : results[0].getDuplicateResults()) {
for (Datacloud.MatchResult matchResult : dupResult.getMatchResults()) {
for (Datacloud.MatchRecord matchRecord : matchResult.getMatchRecords()) {
if (matchRecord.getMatchConfidence() > best) {
best = matchRecord.getMatchConfidence();
}
}
}
}
if (best >= 90) {
newLead.addError('This lead looks like an existing record.');
} else if (best > 0) {
System.debug('Weak match, confidence ' + best);
}
}
}The threshold of 90 is only an example. Choose it after you look at real match scores from your own data.
Common errors and gotchas
- Empty results in tests. Test methods do not see existing org data by default, and duplicate rules need data to match against. Insert the existing records inside the test first. Then confirm your rules are active in the test org. Do not use
SeeAllData=truejust to get this working. - No rule for the object. If the object has no active duplicate rule, the call returns results with no matches. It does not throw an error.
- Unsupported objects. Not every object supports duplicate rules. Check the supported list for your edition before you design around one.
- Blank fields. If the matching equation requires a field and the candidate leaves it blank, the matching rule's blank-field setting decides whether the record can match. A missing email often explains a missing match.
- Calling inside loops. Each call uses limits. Collect records first, then make a single call for the batch.
- Reading
getRecord()fields. The returned record contains the fields the rule needed, not necessarily every field. Query by Id if you need more.
When to use it
Use the method when you need the matches as data, for example to show them in a custom component, to log them, or to pick a survivor for a merge. If you only need to stop users from creating duplicates, a duplicate rule with the Block action needs no code and is easier to maintain. The next chapter covers what happens when a real save is blocked and how DML code can handle that.
Exercise
A developer calls findDuplicates on an unsaved Account in a test method. The org has an active Account duplicate rule, but the call returns no matches. Name two likely causes and how to fix each.
Show answer
First, the test has no existing Accounts to match against, because tests do not see org data by default. Insert the existing Account in the test before calling the method. Second, the duplicate rule or its matching rule may be inactive, or the candidate may leave blank a field the matching equation needs. Check that both rules are active and populate the fields the matching rule compares.
Exercise
You pass a list of three Contacts to findDuplicates. How do you tell which results belong to which Contact, and what does an empty getMatchRecords() list mean?
Show answer
The outer list of FindDuplicatesResult keeps the input order, so index 0 belongs to the first Contact, index 1 to the second, and so on. An empty getMatchRecords() list means the rule ran and found no matching existing records for that Contact.