Places index: drop buildings and land use, search without apostrophes and by brand
CI / check (push) Successful in 18s
CI / deploy (push) Successful in 12s

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.
This commit is contained in:
randy committed 2026-11-12 12:58:31 +01:00
1 parent 8e4c466829
commit f3dd37dd4e
5 files changed
+67 -12

No files matched your search

+1 -1
View File
@@ -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] 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] 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/<CODE>.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/<CODE>.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] 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] 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 ** [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
+35 -7
View File
@@ -13,10 +13,21 @@ module Maptool
module Places module Places
class ExtractError < StandardError; end 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 # Most to least important; the first key a feature carries decides
# its kind and rank. Within "place", the value refines it further. # 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 KIND_KEYS = %w[place natural tourism amenity historic leisure shop aeroway railway highway waterway
boundary landuse man_made office building].freeze 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 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 # 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 # 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 = SQLite3::Database.new(db_path)
db.execute(<<~SQL) db.execute(<<~SQL)
CREATE VIRTUAL TABLE places USING fts5( 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' tokenize = 'unicode61 remove_diacritics 2', prefix = '2 3'
) )
SQL SQL
db.execute("PRAGMA user_version = #{SCHEMA_VERSION}")
# A street is many way segments, all named the same — one row per # 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 # 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 # whole result list. ponytail: grid dedupe, a long road still shows
# once per cell it crosses. # once per cell it crosses.
seen = Set.new seen = Set.new
insert = db.prepare("INSERT INTO places VALUES (?, ?, ?, ?, ?, ?)") insert = db.prepare("INSERT INTO places VALUES (?, ?, ?, ?, ?, ?, ?)")
db.transaction do db.transaction do
io.each_line do |line| io.each_line do |line|
row = row(JSON.parse(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) insert.execute(row)
rescue JSON::ParserError rescue JSON::ParserError
@@ -74,13 +86,29 @@ module Maptool
db.close db.close
end 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) def self.row(feature)
tags = feature["properties"] || {} tags = feature["properties"] || {}
name = tags["name"].to_s.strip name = tags["name"].to_s.strip
geometry = feature["geometry"] || {} geometry = feature["geometry"] || {}
coords = geometry["coordinates"] 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) points = positions(coords)
lngs, lats = points.map { |p| p.first(2) }.transpose lngs, lats = points.map { |p| p.first(2) }.transpose
@@ -90,14 +118,14 @@ module Maptool
# bbox center of an area. # bbox center of an area.
lon, lat = geometry["type"] == "LineString" ? points[points.size / 2] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2] 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 value = tags[key].to_s
kind = if key.nil? then "" kind = if key.nil? then ""
elsif key == "highway" && geometry["type"] != "Point" then "street" elsif key == "highway" && geometry["type"] != "Point" then "street"
else value.tr("_", " ") else value.tr("_", " ")
end end
importance = key == "place" ? PLACE_RANK.fetch(value, KEY_RANK["place"]) : KEY_RANK[key] 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 end
def self.positions(coords) def self.positions(coords)
+1 -1
View File
@@ -419,7 +419,7 @@ module Maptool
FileUtils.mkdir_p(places_dir(data_dir)) FileUtils.mkdir_p(places_dir(data_dir))
sources.each do |source| sources.each do |source|
out_path = places_country_path(data_dir, source["code"]) 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" tmp_path = "#{out_path}.tmp"
begin begin
+3 -2
View File
@@ -97,9 +97,10 @@ module Maptool
end end
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) 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 end
def self.entries(path, read) def self.entries(path, read)
+27 -1
View File
@@ -1,5 +1,6 @@
require_relative "test_helper" require_relative "test_helper"
require "maptool/places" require "maptool/places"
require "maptool/search"
require "stringio" require "stringio"
# No real osmium — import is fed canned `osmium export -f geojsonseq` # 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("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("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("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", "not json",
] ]
Maptool::Places.import(StringIO.new(lines.join("\n")), @db) Maptool::Places.import(StringIO.new(lines.join("\n")), @db)
@@ -55,10 +61,30 @@ class PlacesTest < Minitest::Test
assert_empty search("crossing") assert_empty search("crossing")
end 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 private
def search(text, **opts) 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) } Maptool::Places.search(@db, words, **opts).map { |r| r.except(:rank) }
end end