Implementing a Levenshtein Distance Function in KQL

Series - LevenshteinDistance

The Levenshtein Distance was introduced by Russian mathematician Vladimir Levenshtein in 1965 to measure the difference between two sequences of characters. Specifically, it calculates the minimum number of single-character operations needed to transform one string into another. Those operations can be:

  • Insertion: Adding a character (cat → catt)
  • Deletion: Removing a character (cat → ca)
  • Substitution: Changing one character to another (cat → bat)

The distance metric effectively represents how similar two strings are. A distance of 0 means the strings are identical, while a larger distance indicates greater differences between the strings. The Levenshtein Distance has a wide range of applications, including spell checking, autocorrection, and fuzzy search.

To calculate the Levenshtein Distance, we need to build a matrix that keeps track of the minimum number of operations required to transform one string into another. We’ll go through the algorithm using an example. Suppose that we want to calculate the distance between the words plane and lines. The process goes as follows:

First, we create a matrix with dimensions (m+1) * (n+1), where m and n are the lengths of the two strings being compared. We place the characters of the first string along the rows and the characters of the second string along the columns. We also add an extra first row and first column to represent the empty string ("").

text

      ""  l  i  n  e  s
    +-------------------
 "" |  .  .  .  .  .  .
  p |  .  .  .  .  .  .
  l |  .  .  .  .  .  .
  a |  .  .  .  .  .  .
  n |  .  .  .  .  .  .
  e |  .  .  .  .  .  .

Next, initialize the first row and first column incrementally, starting from 0.

text

      ""  l  i  n  e  s
    +-------------------
 "" |  0  1  2  3  4  5
  p |  1  .  .  .  .  .
  l |  2  .  .  .  .  .
  a |  3  .  .  .  .  .
  n |  4  .  .  .  .  .
  e |  5  .  .  .  .  .

We process the matrix one cell at a time, from left to right and top to bottom. For each cell, we calculate the minimum cost of the three possible operations:

  • Deletion: The value of the cell above plus 1.
  • Insertion: The value of the cell to the left plus 1.
  • Substitution: The value of the diagonally upper-left cell plus 0 if the two characters match, or plus 1 if they differ.

In mathematical terms, each cell is calculated using the following conditions:

Levenshtein Distance cost calculation

Levenshtein Distance cost calculation

For the substitution operation c=0 if the characters being compared are identical, and c=1 otherwise.

Let’s look at the first cell, where we compare p and l. For this cell:

  • Deletion costs 1 + 1 = 2
  • Insertion costs 1 + 1 = 2
  • Substitution costs 0 + 1 = 1 (because p and l are different)

The minimum value is 1, so we place 1 in the cell.

text

      ""  l  i  n  e  s
    +-------------------
 "" |  0  1  2  3  4  5
  p |  1  1  .  .  .  .
  l |  2  .  .  .  .  .
  a |  3  .  .  .  .  .
  n |  4  .  .  .  .  .
  e |  5  .  .  .  .  .

After filling in the remaining cells in the first row we move on to the second row, comparing this time l with l. For this cell:

  • Deletion costs 1 + 1 = 2
  • Insertion costs 2 + 1 = 3
  • Substitution costs 1 + 0 = 1 (because l and l are identical)

The minimum value is 1, so we place 1 in the cell.

text

      ""  l  i  n  e  s
    +-------------------
 "" |  0  1  2  3  4  5
  p |  1  1  2  3  4  5
  l |  2  1  .  .  .  .
  a |  3  .  .  .  .  .
  n |  4  .  .  .  .  .
  e |  5  .  .  .  .  .

We proceed in a similar manner filling in all the remaining cells and rows.

text

      ""  l  i  n  e  s
    +-------------------
 "" |  0  1  2  3  4  5
  p |  1  1  2  3  4  5
  l |  2  1  2  3  4  5
  a |  3  2  2  3  4  5
  n |  4  3  3  2  3  4
  e |  5  4  4  3  2  3

Once the matrix is completely filled, the Levenshtein Distance is given by the value of the bottom-right cell. In this case the distance is 3.

To identify which operations are required, we need to backtrack through the completed matrix, starting from the bottom-right cell and moving towards the top-left cell. At each step, we check which neighboring cell could have produced the current value using the minimum cost operation.

  • Deletion: Move up if the cell above + 1 equals the current value.
  • Insertion: Move left if the cell to the left + 1 equals the current value.
  • Substitution: Move diagonally up-left if the diagonal cell + 1 equals the current value.
  • Match: If the characters are identical and the diagonal cell has the same value, move diagonally up-left without adding an operation.

Let’s see how these steps can be applied in our example:

  1. Compare e and s. The current value is 3. The cell to the left contains 2. Since 2+1=3, we move left. This represents an insertion of s.
  2. Compare e and e. The diagonal cell contains 2, which is equal to the current value and the characters match, so we move diagonally without adding an operation.
  3. Compare n and n. Again, the diagonal cell has the same value as the current cell and the characters match. We move diagonally without adding an operation.
  4. Compare a and i. The diagonal cell contains 1. Since 1+1=2, we move diagonally. This represents the substitution of a with i.
  5. Compare l and l. The characters match, so we move diagonally without adding an operation.
  6. Compare p and the empty string. We move up, representing the deletion of p.

text

      ""  l  i  n  e  s
    +-------------------
 "" |  0  1  2  3  4  5
  p |  1  1  2  3  4  5
  l |  2  1  2  3  4  5
  a |  3  2  2  3  4  5
  n |  4  3  3  2  3  4
  e |  5  4  4  3  2  3

Reading the operations in the opposite direction gives us:

  1. Delete p: plane → lane
  2. Substitute a with i: lane → line
  3. Insert s: line → lines

With a total cost (distance) of 3 operations.

Visualization of Levenshtein Distance operations for plane → lines

Visualization of Levenshtein Distance operations for plane → lines

Now that we understand how the Levenshtein Distance is calculated, let’s look at how we can implement the algorithm in KQL since there is no native built-in KQL function.

We are introducing a function that accepts 3 parameters:

  • tbl: The input table containing the data to be processed.
  • ColumnA: The name of the column containing the first string.
  • ColumnB: The name of the column containing the second string.

The function will calculate the Levenshtein Distance between all unique combinations of values from ColumnA and ColumnB.

kusto

let LevenshteinDistance = (tbl:(*), ColumnA:string, ColumnB:string) {
    let T = materialize(
        tbl
        | extend
            WordA = tostring(column_ifexists(ColumnA, "")),
            WordB = tostring(column_ifexists(ColumnB, ""))
        | summarize by WordA, WordB
    );
    T
    | serialize
    | extend _id = row_number()
    | extend LengthA = strlen(WordA)
    | extend LengthB = strlen(WordB)
    | mv-expand i = range(0, LengthA) to typeof(long)
    | mv-expand j = range(0, LengthB) to typeof(long)
    | sort by _id asc, i asc, j asc
    | scan declare (
        lev_matrix:dynamic = dynamic({})
    )
    with (
        step s: true =>
            lev_matrix = bag_set_key(
                iff(i == 0 and j == 0, dynamic({}), s.lev_matrix),
                strcat(i, "_", j),
                case(
                    i == 0, j,
                    j == 0, i,
                    min_of(
                        tolong(s.lev_matrix[strcat(i - 1, "_", j)]) + 1,
                        tolong(s.lev_matrix[strcat(i, "_", j - 1)]) + 1,
                        tolong(s.lev_matrix[strcat(i - 1, "_", j - 1)])
                            + iff(
                                substring(WordA, i - 1, 1)
                                == substring(WordB, j - 1, 1),
                                0,
                                1
                            )
                    )
                )
            );
    )
    | where i == LengthA and j == LengthB
    | extend Distance = tolong(lev_matrix[strcat(LengthA, "_", LengthB)])
    | project
        WordA,
        WordB,
        Distance
};

We’ll break down the KQL function into smaller sections and explain what each part does.

First, we prepare the input table before performing the distance calculation. The materialize() function stores the result of the tabular expression for reuse during query execution. We then use extend to add the input strings WordA and WordB as columns, retrieving their values dynamically using column_ifexists(). This function takes the column names provided through the ColumnA and ColumnB parameters and returns their values. If either specified column does not exist, it returns an empty string. Finally, summarize by WordA, WordB removes duplicate combinations, ensuring that each unique combination of strings is processed only once. The resulting table is stored in T and used in the subsequent calculations.

kusto

let T = materialize(
    tbl
    | extend
        WordA = tostring(column_ifexists(ColumnA, "")),
        WordB = tostring(column_ifexists(ColumnB, ""))
    | summarize by WordA, WordB
);

The serialize operator marks the rows as serialized, allowing us to assign a unique identifier to each row using row_number(). This identifier, stored in _id, will help us track the matrix calculations for the different string pairs.

kusto

T
| serialize
| extend _id = row_number()

Next, we use strlen() to calculate the lengths of WordA and WordB, storing them in LengthA and LengthB, respectively. These values are important for simulating the matrix calculation described above.

kusto

| extend LengthA = strlen(WordA)
| extend LengthB = strlen(WordB)

To better understand the transformation we have done so far, the following screenshot shows the intermediate state of comparing the string plane against a dataset of other strings.

Table transformation for a list of test words against the string plane

Table transformation for a list of test words against the string plane

Now comes the interesting part of generating the coordinates required to build the matrix for each pair of strings. The range() function generates a sequence of numbers starting at 0 and ending at the length of the corresponding string. We use mv-expand to expand these sequences into individual rows, first for the row indexes (i) and then for the column indexes (j). This creates every possible combination of row and column indexes needed to represent the matrix, including the initial row and column used for empty strings. Finally, the sort operator sorts the coordinates by _id, i, and j, ensuring that each matrix is processed sequentially, from left to right and top to bottom as the algorithm requires. This ordering is very important because each cell depends on values calculated in the preceding cells.

kusto

| mv-expand i = range(0, LengthA) to typeof(long)
| mv-expand j = range(0, LengthB) to typeof(long)
| sort by _id asc, i asc, j asc

The expanded dataset contains all possible combinations of row (i) and column (j) indexes for each pair of strings being compared. Each row represents a cell in the Levenshtein Distance matrix, ready to be populated with its corresponding edit distance. The _id column represents a unique string pair.

Intermediate results after expanding the row and column indexes

Intermediate results after expanding the row and column indexes

Before moving to the core of the algorithm, the matrix calculation, let’s first understand the scan operator.

The scan operator in KQL allows us to process a sequence of rows while maintaining state between consecutive rows. Unlike operators that process each row independently, scan can remember values calculated in previous steps and use them when processing the next row. A simple way to understand the scan operator is to use it to calculate a running total. In this example, we process a sequence of numbers and keep track of the cumulative sum as we move from one row to the next.

kusto

datatable(Number:long)
[
    1,
    2,
    3,
    4,
    5
]
| serialize
| scan declare (
    RunningTotal:long = 0
)
with (
    step s: true =>
        RunningTotal = s.RunningTotal + Number;
)

First, we declare a variable called RunningTotal, initialized to 0. The scan operator then processes each row sequentially. For every row, it adds the current value of Number to the previous value of RunningTotal and stores the result.

For example, when processing the fourth row, the previous running total is 6. We add the current number 4, resulting in a new running total of 10.

Results of running total calculation

Results of running total calculation

Now back to the core of the implementation, where we use the scan operator to build the Levenshtein Distance matrix and calculate the value of each cell. As discussed earlier, scan processes the rows sequentially while maintaining state between iterations. In our case, this state is stored in a dynamic variable called lev_matrix, which holds the values calculated for the matrix cells.

Each cell is identified by a key constructed from its row and column indexes using strcat(i, "_", j). For example, the cell at row 1 and column 2 is stored under the key 1_2. The bag_set_key() function is then used to add the calculated value to the matrix under the corresponding key.

The case() expression handles the initialization of the first row and column, as demonstrated in the algorithm explanation above, assigning the column index when i == 0 and the row index when j == 0. For all other cells, the min_of() function calculates the minimum cost of the three possible operations: deletion, insertion, or substitution. To do so, it retrieves the values of the previously calculated cells directly above, to the left, and diagonally above-left.

To calculate the cost of the substitution operation as we saw in the algorithm above, the substring() function extracts the characters at the current positions from both strings and compares them. The iff() function then assigns a cost of 0 if the characters match (no substitution is needed) or 1 if they differ (one substitution is required). This cost is added to the value of the diagonally upper-left cell.

Finally, the iff(i == 0 and j == 0, dynamic({}), s.lev_matrix) condition is very important to the implementation as it checks whether the current cell is the first cell of a matrix (i == 0 and j == 0). If it is, it returns an empty dynamic object using dynamic({}), effectively resetting the matrix before starting a comparison for a new pair of strings. Otherwise, it returns s.lev_matrix, preserving the values calculated in previous iterations.

kusto

| scan declare (
    lev_matrix:dynamic = dynamic({})
)
with (
    step s: true =>
        lev_matrix = bag_set_key(
            iff(i == 0 and j == 0, dynamic({}), s.lev_matrix),
            strcat(i, "_", j),
            case(
                i == 0, j,
                j == 0, i,
                min_of(
                    tolong(s.lev_matrix[strcat(i - 1, "_", j)]) + 1,
                    tolong(s.lev_matrix[strcat(i, "_", j - 1)]) + 1,
                    tolong(s.lev_matrix[strcat(i - 1, "_", j - 1)])
                        + iff(
                            substring(WordA, i - 1, 1)
                            == substring(WordB, j - 1, 1),
                            0,
                            1
                        )
                )
            )
        );
)

Levenshtein matrix gradually being filled with each iteration

Levenshtein matrix gradually being filled with each iteration

Levenshtein matrix being reset for a new pair of words calculation

Levenshtein matrix being reset for a new pair of words calculation

After the scan operator has populated the entire distance matrix, we retrieve the final Levenshtein Distance from its bottom-right cell. The where operator filters the results to the row where i == LengthA and j == LengthB. Then, extend extracts the value stored at that position in lev_matrix and assigns it to the Distance column. Finally, project selects the output columns: WordA, WordB, and Distance.

kusto

| where i == LengthA and j == LengthB
| extend Distance = tolong(lev_matrix[strcat(LengthA, "_", LengthB)])
| project
    WordA,
    WordB,
    Distance

For sanity checking and to validate the results of our KQL function, we can compare its output against an independent implementation of the Levenshtein distance algorithm provided by the Python RapidFuzz package, using the following script.

python

"""Install: pip install rapidfuzz"""
from rapidfuzz.distance import Levenshtein

WORD_A = "plane"
VARIATIONS = [
    "plane", "plans", "plan", "planes", "place", "lanes",
    "lines", "plate", "planet", "panel", "apple",
]


def main() -> None:
    rows = []
    for WORD_B in VARIATIONS:
        rows.append((
            WORD_A,
            WORD_B,
            Levenshtein.distance(WORD_A, WORD_B)
        ))
    rows.sort(key=lambda r: (r[2], r[1].strip(" ").lower(), r[1]))
    print(f"{'WordA':<8}{'WordB':<14}{'Distance':>9}")
    for word, val, dist in rows:
        print(f"{word:<8}{repr(val):<14}{dist:>9}")


if __name__ == "__main__":
    main()

Levenshtein Distance calculation for a test dataset from our python script

Levenshtein Distance calculation for a test dataset from our python script

Indeed, the distance calculations match those produced by our KQL function for the test dataset.

kusto

let TestWords = datatable(Variation:string)
[
    "plane",
    "plans",
    "plan",
    "planes",
    "place",
    "lanes",
    "lines",
    "plate",
    "planet",
    "panel",
    "apple"
];
TestWords
| extend Original = "plane"
| invoke LevenshteinDistance(ColumnA="Original", ColumnB="Variation")

Levenshtein Distance calculation for a test dataset from our KQL function

Levenshtein Distance calculation for a test dataset from our KQL function

A few limitations and considerations worth taking into account when using this function:

  • Performance considerations: For sufficiently large datasets or long input strings, the function may eventually time out. To reduce this risk, limit the input dataset and string lengths as much as possible before invoking the function. Filtering out irrelevant records early can also help improve performance.
  • Case sensitivity and normalization: The function performs a direct comparison of the input strings without applying any normalization. As a result, comparisons are case-sensitive, and differences in leading, trailing, or internal whitespace contribute to the calculated distance. If you need to treat strings the same regardless of case (e.g. Plane = plane) then normalization should take place before invoking the function.
  • Computational complexity: The algorithm’s complexity relies on the lengths of the two strings being compared. As string lengths increase, the number of calculations and the distance matrix grow accordingly, making the function more expensive to execute. Although deduplication of the string pairs takes place early in the function logic, for a large enough dataset it is possible that the function will time out.

In this post, we explored the Levenshtein Distance algorithm, understood how it works through a practical example, and implemented it in KQL using the scan operator to build and populate the distance matrix. We also validated our implementation against a Python implementation to verify that it produces the expected results.

This is all very nice, but you may be wondering, what use I could possibly have for it? In the context of cybersecurity, string similarity can be particularly useful for identifying typosquatting and masquerading attacks. But before exploring this application in more detail, we’ll first look at an improved version of the Levenshtein distance algorithm, known as the Damerau-Levenshtein distance, which extends the original algorithm by accounting for character transpositions.

Related Content