From f3dd37dd4e5c4ab41238acdb83aa9e94dcb7e25e Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Thu, 12 Nov 2026 12:58:31 +0100 Subject: [PATCH] Places index: drop buildings and land use, search without apostrophes and by brand MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Named buildings and land-use areas are skipped unless they're also a shop/amenity/etc. A second, unshown FTS column holds the name without apostrophes and the brand tag, so "mcdonalds" finds McDonald's and "lidl" finds "Lidl Petržalka". The index records a schema version; rake places:index rebuilds older ones by itself. --- TODO.adoc | 2 +- lib/maptool/places.rb | 42 ++++++++++++++++++++++++++++------ lib/maptool/pmtiles_builder.rb | 2 +- lib/maptool/search.rb | 5 ++-- test/test_places.rb | 28 ++++++++++++++++++++++- 5 files changed, 67 insertions(+), 12 deletions(-) diff --git a/TODO.adoc b/TODO.adoc index 1c01812..7fd00c4 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -63,7 +63,7 @@ independence from connectivity. * [x] Unified search box — one query across every data source, not just what's currently on the map. `GET /api/search` (`lib/maptool/search.rb`) for local sources, online ones queried from the browser (`public/js/search.js`) ** [x] Every layer under Tracks & Points (GPX, FIT, GeoJSON, notes, plugin output) and offline hiking trails — shown *and* hidden ones. Matches name + description, case/diacritics-insensitive ("kosice" finds "Košice"); parsed features cached in memory per file by mtime -** [x] Offline vector data — every named OSM object in each country's Geofabrik `.osm.pbf` (`osmium tags-filter nwr/name` + `osmium export -f geojsonseq`) into a SQLite FTS5 index, `data/places/.sqlite` (`lib/maptool/places.rb`), built as the last offline-build step ("indexing places") and cached by mtime like hiking trails. Prefix + diacritics-insensitive matching, street segments merged per ~2 km cell +** [x] Offline vector data — every named OSM object in each country's Geofabrik `.osm.pbf` (`osmium tags-filter nwr/name` + `osmium export -f geojsonseq`) into a SQLite FTS5 index, `data/places/.sqlite` (`lib/maptool/places.rb`), built as the last offline-build step ("indexing places") and cached by mtime like hiking trails. Prefix + diacritics-insensitive matching, street segments merged per ~2 km cell; named buildings and land-use areas dropped (unless they're also a shop/amenity/…), names searchable without their apostrophes ("mcdonalds") and by `brand`. `Places::SCHEMA_VERSION` makes `rake places:index` rebuild older indexes by itself ** [x] Every result shows where it was found (layer file / "Hiking trails SK" / "Online · Nominatim"); clicking one zooms to it (fitBounds for a track) and switches its layer on if it was off ** [x] Source checklist in the search panel (all on by default), re-runs the search on change ** [x] Online sources pluggable — one more entry in search.js's `SOURCES`; Nominatim already in, its failure only adds a "no connection" line under the local results diff --git a/lib/maptool/places.rb b/lib/maptool/places.rb index 22060a5..5f89f98 100644 --- a/lib/maptool/places.rb +++ b/lib/maptool/places.rb @@ -13,10 +13,21 @@ module Maptool module Places class ExtractError < StandardError; end + # Bumped whenever the table layout or what goes into it changes — + # PmtilesBuilder rebuilds an index whose user_version is older, so a + # plain `rake places:index` picks the change up. + SCHEMA_VERSION = 2 + # Most to least important; the first key a feature carries decides # its kind and rank. Within "place", the value refines it further. KIND_KEYS = %w[place natural tourism amenity historic leisure shop aeroway railway highway waterway boundary landuse man_made office building].freeze + # Named buildings and land-use areas (a farm's fields, an industrial + # estate) are a large share of every country's index and nobody looks + # for them by name — dropped, but only when that's what the object + # *is*: a supermarket drawn as a building is still shop=supermarket. + SKIPPED_KEYS = %w[landuse building].freeze + APOSTROPHES = "'’ʼ`" PLACE_RANK = { "city" => 0, "town" => 1, "village" => 2, "suburb" => 3, "hamlet" => 3 }.freeze # How much closer a settlement counts as when results are ordered by # distance from the map center (Search) — so typing a city's name finds @@ -49,20 +60,21 @@ module Maptool db = SQLite3::Database.new(db_path) db.execute(<<~SQL) CREATE VIRTUAL TABLE places USING fts5( - name, kind UNINDEXED, importance UNINDEXED, lon UNINDEXED, lat UNINDEXED, bbox UNINDEXED, + name, extra, kind UNINDEXED, importance UNINDEXED, lon UNINDEXED, lat UNINDEXED, bbox UNINDEXED, tokenize = 'unicode61 remove_diacritics 2', prefix = '2 3' ) SQL + db.execute("PRAGMA user_version = #{SCHEMA_VERSION}") # A street is many way segments, all named the same — one row per # name/kind per ~2 km cell keeps a town's "Hlavná" from filling the # whole result list. ponytail: grid dedupe, a long road still shows # once per cell it crosses. seen = Set.new - insert = db.prepare("INSERT INTO places VALUES (?, ?, ?, ?, ?, ?)") + insert = db.prepare("INSERT INTO places VALUES (?, ?, ?, ?, ?, ?, ?)") db.transaction do io.each_line do |line| row = row(JSON.parse(line)) - next unless row && seen.add?([row[0], row[1], (row[4] * 50).round, (row[3] * 50).round]) + next unless row && seen.add?([row[0], row[2], (row[5] * 50).round, (row[4] * 50).round]) insert.execute(row) rescue JSON::ParserError @@ -74,13 +86,29 @@ module Maptool db.close end - # [name, kind, importance, lon, lat, bbox json] or nil + def self.current?(db_path) + return false unless File.exist?(db_path) + + db = SQLite3::Database.new(db_path, readonly: true) + db.get_first_value("PRAGMA user_version") >= SCHEMA_VERSION + rescue SQLite3::Exception + false + ensure + db&.close + end + + # [name, extra, kind, importance, lon, lat, bbox json] or nil. extra is + # searched too but never shown: the name with its apostrophes dropped + # (FTS5 splits "McDonald's" into "mcdonald" + "s", so "mcdonalds" would + # otherwise find nothing — Search.normalize drops them from the query + # the same way) and the brand tag ("Lidl" for "Lidl Petržalka"). def self.row(feature) tags = feature["properties"] || {} name = tags["name"].to_s.strip geometry = feature["geometry"] || {} coords = geometry["coordinates"] - return nil if name.empty? || !coords.is_a?(Array) || coords.empty? + key = KIND_KEYS.find { |k| tags[k] } + return nil if name.empty? || !coords.is_a?(Array) || coords.empty? || SKIPPED_KEYS.include?(key) points = positions(coords) lngs, lats = points.map { |p| p.first(2) }.transpose @@ -90,14 +118,14 @@ module Maptool # bbox center of an area. lon, lat = geometry["type"] == "LineString" ? points[points.size / 2] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2] - key = KIND_KEYS.find { |k| tags[k] } value = tags[key].to_s kind = if key.nil? then "" elsif key == "highway" && geometry["type"] != "Point" then "street" else value.tr("_", " ") end importance = key == "place" ? PLACE_RANK.fetch(value, KEY_RANK["place"]) : KEY_RANK[key] - [name, kind, importance, lon, lat, JSON.generate(bbox)] + extra = [(name.delete(APOSTROPHES) if name.count(APOSTROPHES).positive?), tags["brand"]].compact.uniq - [name] + [name, extra.join(" "), kind, importance, lon, lat, JSON.generate(bbox)] end def self.positions(coords) diff --git a/lib/maptool/pmtiles_builder.rb b/lib/maptool/pmtiles_builder.rb index bdc1bad..96bbad0 100644 --- a/lib/maptool/pmtiles_builder.rb +++ b/lib/maptool/pmtiles_builder.rb @@ -419,7 +419,7 @@ module Maptool FileUtils.mkdir_p(places_dir(data_dir)) sources.each do |source| out_path = places_country_path(data_dir, source["code"]) - next if File.exist?(out_path) && File.mtime(out_path) >= File.mtime(source["path"]) + next if File.exist?(out_path) && File.mtime(out_path) >= File.mtime(source["path"]) && Places.current?(out_path) tmp_path = "#{out_path}.tmp" begin diff --git a/lib/maptool/search.rb b/lib/maptool/search.rb index 6984923..49dd54a 100644 --- a/lib/maptool/search.rb +++ b/lib/maptool/search.rb @@ -97,9 +97,10 @@ module Maptool end end - # Lowercased, diacritics stripped — "kosice" finds "Košice". + # Lowercased, diacritics and apostrophes stripped — "kosice" finds + # "Košice", "mcdonalds" finds "McDonald's" (see Places.row's extra). def self.normalize(text) - text.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").downcase + text.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").delete(Places::APOSTROPHES).downcase end def self.entries(path, read) diff --git a/test/test_places.rb b/test/test_places.rb index 27ae609..6f6ba1f 100644 --- a/test/test_places.rb +++ b/test/test_places.rb @@ -1,5 +1,6 @@ require_relative "test_helper" require "maptool/places" +require "maptool/search" require "stringio" # No real osmium — import is fed canned `osmium export -f geojsonseq` @@ -17,6 +18,11 @@ class PlacesTest < Minitest::Test feature("LineString", [[17.103, 48.143], [17.104, 48.144]], "name" => "Hlavná", "highway" => "residential"), feature("Polygon", [[[19.0, 48.0], [19.2, 48.0], [19.2, 48.2], [19.0, 48.0]]], "name" => "Košické jazero", "natural" => "water"), feature("Point", [18.0, 48.0], "highway" => "crossing"), # no name -> skipped + feature("Polygon", [[[17.0, 48.0], [17.01, 48.0], [17.01, 48.01], [17.0, 48.0]]], "name" => "Bytovka Lidl", "building" => "yes"), + feature("Polygon", [[[17.0, 48.0], [17.01, 48.0], [17.01, 48.01], [17.0, 48.0]]], "name" => "Družstvo", "landuse" => "farmland"), + feature("Polygon", [[[17.2, 48.1], [17.21, 48.1], [17.21, 48.11], [17.2, 48.1]]], + "name" => "Lidl Petržalka", "brand" => "Lidl", "shop" => "supermarket", "building" => "retail"), + feature("Point", [17.15, 48.15], "name" => "McDonald's", "amenity" => "fast_food", "brand" => "McDonald's"), "not json", ] Maptool::Places.import(StringIO.new(lines.join("\n")), @db) @@ -55,10 +61,30 @@ class PlacesTest < Minitest::Test assert_empty search("crossing") end + def test_buildings_and_land_use_are_dropped_but_a_shop_in_a_building_is_kept + assert_empty search("bytovka") + assert_empty search("druzstvo") + assert_equal [["Lidl Petržalka", "supermarket"]], search("lidl").map { |r| r.values_at(:name, :kind) } + end + + def test_apostrophes_and_brand_are_searchable + assert_equal ["McDonald's"], search("mcdonalds").map { |r| r[:name] } + assert_equal ["McDonald's"], search("McDonald's").map { |r| r[:name] } + assert_equal ["McDonald's"], search("mcdonald").map { |r| r[:name] } + assert_equal ["Lidl Petržalka"], search("lidl").map { |r| r[:name] } # also via brand + end + + def test_an_index_from_an_older_schema_is_not_current + assert Maptool::Places.current?(@db) + SQLite3::Database.new(@db) { |db| db.execute("PRAGMA user_version = 1") } + refute Maptool::Places.current?(@db) + refute Maptool::Places.current?(File.join(@dir, "missing.sqlite")) + end + private def search(text, **opts) - words = text.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").downcase.split + words = Maptool::Search.normalize(text).split Maptool::Places.search(@db, words, **opts).map { |r| r.except(:rank) } end