Sub topic 12
Fuzzy matching for inconsistent keys
This chapter assumes you can already run a standard merge, pick a join kind, and expand the merged column. It also assumes you know why exact key matching fails on text such as "Contoso Ltd" and "Contoso Ltd.". If any of that is unfamiliar, review the chapters on merging two queries, join kinds, and preparing key columns first.
What fuzzy matching does
A standard merge matches two key values only when they are exactly equal. A fuzzy merge matches values that are similar. Power Query compares each pair of text values and gives the pair a similarity score between 0 and 1. If the score reaches your threshold, the rows match.
Fuzzy matching helps when the keys come from different systems or from people typing. Typical cases:
- Typos:
MicrosoftandMircosoft. - Punctuation and spacing differences:
Contoso LtdandContoso Ltd.. - Extra or missing words:
Northwind TradersandNorthwind Traders Inc. - Singular and plural forms:
EmployeeandEmployees.
Fuzzy matching only works on text columns. If a key is a number or a date, it can't be fuzzy-matched. Convert it to text first, and consider whether an exact match on the original type would be better.
Running a fuzzy merge in the editor
You start a fuzzy merge from the same place as a normal one.
- In the Power Query Editor, select Home > Merge Queries.
- Choose the two queries and click the key column in each.
- Select Use fuzzy matching to perform the merge.
- Open Fuzzy matching options to adjust the settings.
- Select a join kind and click OK.
The result is the usual nested table column. Expand or aggregate it as you would after an exact merge.
The options dialog offers these settings:
| Option | What it controls | Default |
|---|---|---|
| Similarity threshold | Minimum score for two values to match. 0 is the loosest and 1 allows only exact matches. | 0.8 |
| Ignore case | Treats `abc` and `ABC` as the same. | On |
| Match by combining text parts | Lets Power Query join separated parts of a value, such as matching `Micro soft` to `Microsoft`. | On |
| Maximum number of matches | Limits how many matching rows come back for each row on the left. | All matches |
| Transformation table | A table of `From` and `To` pairs that tells Power Query which values mean the same thing. | None |
The exact set of options can vary a little between Excel versions. The M function accepts the same ideas, as the next sections show.
The M code behind a fuzzy merge
The editor generates Table.FuzzyNestedJoin. It takes the same arguments as Table.NestedJoin plus an options record at the end.
let
Source = Table.FuzzyNestedJoin(
Orders, {"CustomerName"},
Customers, {"CustomerName"},
"Matches",
JoinKind.LeftOuter,
[IgnoreCase = true, IgnoreSpace = true, Threshold = 0.8]
)
in
SourceThe options record accepts these fields:
IgnoreCase:trueorfalse.IgnoreSpace:trueorfalse. Spaces are ignored when comparing.Threshold: a number from 0 to 1.NumberOfMatches: the maximum number of matches per left row.SimilarityColumnName: the name of an extra column that holds the similarity score of each match.TransformationTable: a table withFromandTocolumns.
Any field you leave out takes its default. The join kind argument works as it does in an exact merge, so JoinKind.LeftOuter keeps every row on the left. A left outer join is the usual choice for fuzzy merges, because an inner join silently drops every row that falls under the threshold.
A complete example you can run
This query builds both tables inline, so you can paste it into a blank query in the Advanced Editor. It uses a lower threshold than the default and asks for the similarity score.
let
Orders = #table(
type table [OrderID = Int64.Type, CustomerName = text],
{
{1, "Contoso Ltd."},
{2, "northwind traders"},
{3, "Adventure Works"},
{4, "Fabrikam Incorporated"}
}
),
Customers = #table(
type table [CustomerName = text, Region = text],
{
{"Contoso Ltd", "West"},
{"Northwind Traders", "East"},
{"Adventure Works Cycles", "North"}
}
),
Merged = Table.FuzzyNestedJoin(
Orders, {"CustomerName"},
Customers, {"CustomerName"},
"Matches",
JoinKind.LeftOuter,
[
IgnoreCase = true,
IgnoreSpace = true,
Threshold = 0.7,
NumberOfMatches = 1,
SimilarityColumnName = "Score"
]
),
Expanded = Table.ExpandTableColumn(
Merged, "Matches",
{"CustomerName", "Region", "Score"},
{"Matched Name", "Region", "Score"}
)
in
ExpandedExpect the first three orders to pick up a region and a score, and order 4 to have null in the matched columns, because no customer is similar to "Fabrikam Incorporated". Treat the exact scores as something to read from your own output rather than assume. Different versions of the engine and different data can give slightly different numbers.
Tuning the threshold
The threshold is the main control, and it works as a trade-off between two kinds of error.
- A high threshold, such as 0.9 or above, produces few false matches but misses real ones. Rows that should match show
null. - A low threshold, such as 0.5 or below, finds more real matches but starts joining unrelated values. Lowering it to 0 matches almost everything.
A reasonable process:
- Start at the default of 0.8.
- Run the merge with
SimilarityColumnNameset, and expand the score column. - Sort by score ascending, and read the matched pairs near the bottom.
- If the weakest pairs are still correct, lower the threshold a little and repeat. If wrong pairs appear, raise it.
- Handle the remaining misses with a transformation table, described next.
Transformation tables
Some differences are not typos, so similarity scoring handles them poorly. Corp and Corporation, or St and Street, are different strings that mean the same thing. A transformation table lists such pairs. Power Query applies the replacements before it compares values.
The table needs two text columns named From and To.
let
Replacements = #table(
type table [From = text, To = text],
{
{"Corp", "Corporation"},
{"Inc", "Incorporated"},
{"Ltd", "Limited"}
}
),
Orders = #table(
type table [CustomerName = text],
{{"Fabrikam Inc"}, {"Contoso Ltd"}}
),
Customers = #table(
type table [CustomerName = text, Region = text],
{{"Fabrikam Incorporated", "South"}, {"Contoso Limited", "West"}}
),
Merged = Table.FuzzyNestedJoin(
Orders, {"CustomerName"},
Customers, {"CustomerName"},
"Matches",
JoinKind.LeftOuter,
[Threshold = 0.8, TransformationTable = Replacements]
)
in
MergedIn the editor you pick the transformation table in the fuzzy matching options. It must already exist as a query in the workbook, so create it first and set it to connection only.
Limits and failure modes
Fuzzy matching is a tool for cleanup and exploration. These are the main reasons to be careful with it.
- False matches. Two different companies with similar names, such as
Acme NorthandAcme South, can score above the threshold. The merge will not warn you. - Duplicated rows. If one left row is similar to several right rows, every match produces a row after expansion. Set
NumberOfMatches = 1when you want one match per row, and then verify the choice, because Power Query picks the best-scoring match. - Unstable results. Changing the data or the threshold can change which rows match. A match that was correct last month may fail after a new customer is added, or the reverse.
- Speed. Fuzzy merges compare many pairs of values, so they are much slower than exact merges on large tables. Reduce both tables first, for example by removing columns and filtering rows, before the fuzzy step.
- Text only. Keys of other types must be converted to text.
- Silent loss with inner joins. An inner fuzzy join drops rows with no match above the threshold, with no error message.
When to avoid fuzzy matching
Fuzzy matching is a fallback. If a reliable ID exists, such as a customer number, use an exact merge on it. If the differences are only spacing and case, trimming and normalizing the key, as covered in the key preparation chapter, gives an exact and repeatable result without a threshold to defend. If the problem is a small set of known variants, a transformation table or a mapping query with an exact merge is easier to audit.
Use fuzzy matching when the variation is genuinely unpredictable and a person will review the output, such as a one-time cleanup of free-text company names.
Exercise
An order table has 500 rows. After a left outer fuzzy merge with Threshold = 0.6 and no limit on matches, then expanding the matched column, the result has 540 rows. What is the likely cause, and what two changes would you try?
Show answer
Some order rows matched more than one customer name above the 0.6 threshold, and expanding the nested table created one output row per match. Set NumberOfMatches = 1 so each order keeps only its best match, and raise the threshold, for example to 0.8. Then expand the similarity score and check the weakest matches. The row count should return to 500.
Exercise
Your keys are "Acme Corp" in one table and "Acme Corporation" in the other, and a fuzzy merge at 0.8 misses them. Rather than lowering the threshold for every row, what can you add, and what must it contain?
Show answer
Add a transformation table, a query with text columns named From and To, containing a row such as From = "Corp" and To = "Corporation". Select it in the fuzzy matching options, or pass it as TransformationTable in the options record. Power Query applies the replacement before comparing, so the threshold can stay at 0.8.