You can use DuplicateResult class to get duplicate records detected by duplicate rule.
Using Database.SaveResult saveResult = Database.insert(contact, false);
get errors and successes. You may need to do few tweaks in code to get duplicate records.
for (Database.Error error : saveResult.getErrors()) {
if (error instanceof Database.DuplicateError) {
Database.DuplicateError duplicateError = (Database.DuplicateError)error;
Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();
ApexPages.Message errorMessage = new ApexPages.Message(
ApexPages.Severity.ERROR, 'Duplicate Error: ' +
duplicateResult.getErrorMessage());
ApexPages.addMessage(errorMessage);
this.duplicateRecords = new List<sObject>();
Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();
Datacloud.MatchResult matchResult = matchResults[0];
Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
}
}
You can use Datacloud.MatchResult
to get duplicate records. Please find the sample code.