Created
September 11, 2023 13:02
-
-
Save jnunemaker/bd23a9f99386c1719e9d1108c61e992a to your computer and use it in GitHub Desktop.
Some example usage of levenshtein to calculate the difference between two strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- https://www.postgresql.org/docs/current/fuzzystrmatch.html#id-1.11.7.26.7 | |
-- Calculates the distance between two strings. | |
SELECT levenshtein('New York', 'New York'); -- 0 | |
SELECT levenshtein('New York', 'New Jersey'); -- 5 | |
SELECT levenshtein('New York', 'Dallas'); -- 8 | |
-- find the opponent with the name closest to 'New York' | |
SELECT * FROM opponents WHERE team_id = 1 | |
ORDER BY levenshtein(name, 'New York') | |
-- from ActiveRecord | |
name = "New York" | |
quoted_name = ActiveRecord::Base.connection.quote(name) | |
order_by = Arel.sql("levenshtein(name, #{quoted_name})") | |
Opponent.where(team_id: 1).order(order_by) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment