Files
maptool/lib/maptool/places.rb
T
randy e2461f794c Places index: also drop localities, isolated dwellings and kindless objects
Measured on France (5.3M rows): place=locality ~10% (mostly cadastral
names of fields and woods), isolated_dwelling ~5%, objects with a name
but none of the recognized kind keys ~4% (bus route relations etc.).
Schema version 3, so rake places:index rebuilds existing indexes.
2026-11-12 13:42:04 +01:00

173 lines
8.1 KiB
Ruby

require "json"
require "open3"
require "set"
require "sqlite3"
require "tmpdir"
module Maptool
# Offline place-name search: every named OSM object in a country's
# Geofabrik .osm.pbf (towns, streets, peaks, POIs, ...) in a SQLite FTS5
# index, one data/places/<CODE>.sqlite per country — built during the
# offline build next to hiking trails, from the same already-downloaded
# PBF. offline.pmtiles itself is tiles, not searchable by name.
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 = 3
# 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 noise in results — nobody looks for them by name — so
# they're dropped, but only when that's what the object *is*: a
# supermarket drawn as a building is still shop=supermarket. (Measured:
# only ~1-7% of an index's size, so this is about result quality.)
SKIPPED_KEYS = %w[landuse building].freeze
# Same idea, measured on France (5.3M rows): place=locality (~10%,
# mostly cadastral names of fields and woods) and isolated_dwelling
# (~5%, single farms/houses) — plus anything named but with none of
# KIND_KEYS (~4%: bus route relations and the like).
SKIPPED_PLACES = %w[locality isolated_dwelling].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
# the city, not a same-named street around the corner, while a shop or
# a street is purely nearest-first. Keyed by importance (PLACE_RANK).
# ponytail: fixed multipliers, tune if real searches rank oddly.
DISTANCE_WEIGHT = Hash.new(1.0).merge(0 => 0.01, 1 => 0.03, 2 => 0.1, 3 => 0.3).freeze
KEY_RANK = Hash.new(7).merge("place" => 4, "natural" => 5, "tourism" => 5, "amenity" => 5, "historic" => 5,
"leisure" => 5, "shop" => 5, "aeroway" => 5, "railway" => 6, "highway" => 6, "waterway" => 6)
def self.osmium_bin
ENV.fetch("OSMIUM_BIN", "osmium")
end
def self.extract(pbf_path, db_path)
Dir.mktmpdir("maptool-places") do |dir|
named = File.join(dir, "named.osm.pbf")
run!(osmium_bin, "tags-filter", pbf_path, "nwr/name", "-o", named)
seq = File.join(dir, "named.geojsonseq")
run!(osmium_bin, "export", named, "-f", "geojsonseq", "-x", "print_record_separator=false", "-o", seq)
File.open(seq) { |io| import(io, db_path) }
end
end
# Pure apart from SQLite — one GeoJSON feature per line in, index out —
# so it's testable without osmium installed (same split as
# HikingTrails.extract/parse_opl).
def self.import(io, db_path)
File.delete(db_path) if File.exist?(db_path)
db = SQLite3::Database.new(db_path)
db.execute(<<~SQL)
CREATE VIRTUAL TABLE places USING fts5(
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 (?, ?, ?, ?, ?, ?, ?)")
db.transaction do
io.each_line do |line|
row = row(JSON.parse(line))
next unless row && seen.add?([row[0], row[2], (row[5] * 50).round, (row[4] * 50).round])
insert.execute(row)
rescue JSON::ParserError
next
end
end
insert.close
db.execute("INSERT INTO places(places) VALUES ('optimize')")
db.close
end
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"]
key = KIND_KEYS.find { |k| tags[k] }
return nil if name.empty? || !coords.is_a?(Array) || coords.empty? || key.nil? || SKIPPED_KEYS.include?(key)
return nil if key == "place" && SKIPPED_PLACES.include?(tags["place"])
points = positions(coords)
lngs, lats = points.map { |p| p.first(2) }.transpose
bbox = [lngs.min, lats.min, lngs.max, lats.max]
# A label point that's actually on the thing: the middle vertex of a
# line (a curved street's bbox center can be off the street), the
# bbox center of an area.
lon, lat = geometry["type"] == "LineString" ? points[points.size / 2] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
value = tags[key].to_s
kind = if key == "highway" && geometry["type"] != "Point" then "street"
else value.tr("_", " ")
end
importance = key == "place" ? PLACE_RANK.fetch(value, KEY_RANK["place"]) : KEY_RANK[key]
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)
coords.first.is_a?(Numeric) ? [coords] : coords.flat_map { |c| positions(c) }
end
# words: already lowercased/diacritics-stripped (Search.normalize);
# every one must match as a word prefix. Nearest to `center` ([lat,
# lng], the map's) first, settlements weighted closer (DISTANCE_WEIGHT);
# with no center, most important kinds first.
def self.search(db_path, words, center: nil, limit: 50)
match = words.map { |word| %("#{word.gsub('"', '""')}"*) }.join(" ")
order, params =
if center
weight = DISTANCE_WEIGHT.map { |importance, w| "WHEN #{importance} THEN #{w * w}" }.join(" ")
["((lat - ?) * (lat - ?) + (lon - ?) * (lon - ?)) * CASE importance #{weight} ELSE 1 END",
[center[0], center[0], center[1], center[1]]]
else
["importance, rank", []]
end
db = SQLite3::Database.new(db_path, readonly: true)
db.execute("SELECT name, kind, bbox, importance FROM places WHERE places MATCH ? ORDER BY #{order} LIMIT ?", [match, *params, limit])
.map { |name, kind, bbox, importance| { name: name, kind: kind, bbox: JSON.parse(bbox), importance: importance } }
rescue SQLite3::Exception
[]
ensure
db&.close
end
def self.run!(*args)
stdout, stderr, status = Open3.capture3(*args)
raise ExtractError, "#{args.first} exited with status #{status.exitstatus}: #{[stdout, stderr].map(&:strip).reject(&:empty?).join("\n")}" unless status.success?
rescue Errno::ENOENT, Errno::EACCES => e
raise ExtractError, "could not run '#{args.first}' (#{e.message}) — is osmium-tool installed and on PATH?"
end
private_class_method :run!
end
end