Skip to content

Instantly share code, notes, and snippets.

@jnunemaker
Created September 11, 2023 13:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnunemaker/bd23a9f99386c1719e9d1108c61e992a to your computer and use it in GitHub Desktop.
Save jnunemaker/bd23a9f99386c1719e9d1108c61e992a to your computer and use it in GitHub Desktop.
Some example usage of levenshtein to calculate the difference between two strings.
-- 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