--- android/TrainInfoService/src/dk/thoerup/traininfoservice/db/StationDAO.java 2011/06/08 16:10:49 1506 +++ android/TrainInfoService/src/dk/thoerup/traininfoservice/db/StationDAO.java 2011/06/08 16:11:27 1507 @@ -105,7 +105,7 @@ * 'select $2 ilike $1' language sql strict immutable; * create operator ~~~ (procedure = rlike, leftarg = text, rightarg = text, commutator = ~~); */ - public StationBean getByName(final String name) throws SQLException { + public StationBean getByNameNormal(final String name) throws SQLException { String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0 " + "FROM trainstations " + "WHERE (name ILIKE ? OR ? ~~~ ANY(aliases)) AND enabled = true " + @@ -121,6 +121,41 @@ return fetchStations(SQL, new NameSetter() ); } + + + public StationBean getByNameFuzzy(final String name) throws SQLException { + String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0, " + + "levenshtein(lower(name),lower(?) ) as leven " + + "FROM trainstations " + + "WHERE (levenshtein(lower(name),lower(?) ) <= 3) AND enabled = true " + + "AND enabled = true " + + "ORDER BY leven " + + "LIMIT 1"; + + class NameSetter implements StatementParamSetter { + @Override + public void setParams(PreparedStatement stmt) throws SQLException { + stmt.setString(1, name ); + stmt.setString(2, name ); + } + } + + StationBean stations = fetchStations(SQL, new NameSetter() ); + stations.fuzzystrmatch = true; + return stations; + } + + public StationBean getByName(final String name) throws SQLException { + StationBean stations = getByNameNormal(name); + + if (stations.entries.size() == 0) { + logger.info("getByName failover: " + name); + stations = getByNameFuzzy(name); + } + return stations; + } + + //Latitude (horizonal), longitude(vertical) so // 1 degree latitude is ~ 111320 meters, since the distance between the horizonal lines is always the same