1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Implementation of classes for API access via libraries.
10 from typing import Mapping, Optional, Any, AsyncIterator, Dict, Sequence, List, Tuple
14 from pathlib import Path
16 import sqlalchemy as sa
17 import sqlalchemy.ext.asyncio as sa_asyncio
19 from nominatim.errors import UsageError
20 from nominatim.db.sqlalchemy_schema import SearchTables
21 from nominatim.db.async_core_library import PGCORE_LIB, PGCORE_ERROR
22 import nominatim.db.sqlite_functions
23 from nominatim.config import Configuration
24 from nominatim.api.connection import SearchConnection
25 from nominatim.api.status import get_status, StatusResult
26 from nominatim.api.lookup import get_detailed_place, get_simple_place
27 from nominatim.api.reverse import ReverseGeocoder
28 from nominatim.api.search import ForwardGeocoder, Phrase, PhraseType, make_query_analyzer
29 import nominatim.api.types as ntyp
30 from nominatim.api.results import DetailedResult, ReverseResult, SearchResults
33 class NominatimAPIAsync: #pylint: disable=too-many-instance-attributes
34 """ The main frontend to the Nominatim database implements the
35 functions for lookup, forward and reverse geocoding using
36 asynchronous functions.
38 This class shares most of the functions with its synchronous
39 version. There are some additional functions or parameters,
40 which are documented below.
42 def __init__(self, project_dir: Path,
43 environ: Optional[Mapping[str, str]] = None,
44 loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
45 """ Initiate a new frontend object with synchronous API functions.
48 project_dir: Path to the
49 [project directory](../admin/Import.md#creating-the-project-directory)
50 of the local Nominatim installation.
51 environ: Mapping of [configuration parameters](../customize/Settings.md).
52 When set, replaces any configuration via environment variables.
53 Settings in this mapping also have precedence over any
54 parameters found in the `.env` file of the project directory.
55 loop: The asyncio event loop that will be used when calling
56 functions. Only needed, when a custom event loop is used
57 and the Python version is 3.9 or earlier.
59 self.config = Configuration(project_dir, environ)
60 self.query_timeout = self.config.get_int('QUERY_TIMEOUT') \
61 if self.config.QUERY_TIMEOUT else None
62 self.reverse_restrict_to_country_area = self.config.get_bool('SEARCH_WITHIN_COUNTRIES')
63 self.server_version = 0
65 if sys.version_info >= (3, 10):
66 self._engine_lock = asyncio.Lock()
68 self._engine_lock = asyncio.Lock(loop=loop) # pylint: disable=unexpected-keyword-arg
69 self._engine: Optional[sa_asyncio.AsyncEngine] = None
70 self._tables: Optional[SearchTables] = None
71 self._property_cache: Dict[str, Any] = {'DB:server_version': 0}
74 async def setup_database(self) -> None:
75 """ Set up the SQL engine and connections.
77 This function will be implicitly called when the database is
78 accessed for the first time. You may also call it explicitly to
79 avoid that the first call is delayed by the setup.
81 async with self._engine_lock:
85 extra_args: Dict[str, Any] = {'future': True,
86 'echo': self.config.get_bool('DEBUG_SQL')}
88 if self.config.get_int('API_POOL_SIZE') == 0:
89 extra_args['poolclass'] = sa.pool.NullPool
91 extra_args['poolclass'] = sa.pool.QueuePool
92 extra_args['max_overflow'] = 0
93 extra_args['pool_size'] = self.config.get_int('API_POOL_SIZE')
96 is_sqlite = self.config.DATABASE_DSN.startswith('sqlite:')
99 params = dict((p.split('=', 1)
100 for p in self.config.DATABASE_DSN[7:].split(';')))
101 dburl = sa.engine.URL.create('sqlite+aiosqlite',
102 database=params.get('dbname'))
105 dsn = self.config.get_database_params()
106 query = {k: v for k, v in dsn.items()
107 if k not in ('user', 'password', 'dbname', 'host', 'port')}
109 dburl = sa.engine.URL.create(
110 f'postgresql+{PGCORE_LIB}',
111 database=dsn.get('dbname'),
112 username=dsn.get('user'),
113 password=dsn.get('password'),
114 host=dsn.get('host'),
115 port=int(dsn['port']) if 'port' in dsn else None,
118 engine = sa_asyncio.create_async_engine(dburl, **extra_args)
123 @sa.event.listens_for(engine.sync_engine, "connect")
124 def _on_sqlite_connect(dbapi_con: Any, _: Any) -> None:
125 dbapi_con.run_async(lambda conn: conn.enable_load_extension(True))
126 nominatim.db.sqlite_functions.install_custom_functions(dbapi_con)
127 cursor = dbapi_con.cursor()
128 cursor.execute("SELECT load_extension('mod_spatialite')")
129 cursor.execute('SELECT SetDecimalPrecision(7)')
130 dbapi_con.run_async(lambda conn: conn.enable_load_extension(False))
133 async with engine.begin() as conn:
134 result = await conn.scalar(sa.text('SHOW server_version_num'))
135 server_version = int(result)
136 except (PGCORE_ERROR, sa.exc.OperationalError):
139 if server_version >= 110000:
140 @sa.event.listens_for(engine.sync_engine, "connect")
141 def _on_connect(dbapi_con: Any, _: Any) -> None:
142 cursor = dbapi_con.cursor()
143 cursor.execute("SET jit_above_cost TO '-1'")
144 cursor.execute("SET max_parallel_workers_per_gather TO '0'")
145 # Make sure that all connections get the new settings
146 await engine.dispose()
148 self._property_cache['DB:server_version'] = server_version
150 self._tables = SearchTables(sa.MetaData()) # pylint: disable=no-member
151 self._engine = engine
154 async def close(self) -> None:
155 """ Close all active connections to the database. The NominatimAPIAsync
156 object remains usable after closing. If a new API functions is
157 called, new connections are created.
159 if self._engine is not None:
160 await self._engine.dispose()
163 @contextlib.asynccontextmanager
164 async def begin(self) -> AsyncIterator[SearchConnection]:
165 """ Create a new connection with automatic transaction handling.
167 This function may be used to get low-level access to the database.
168 Refer to the documentation of SQLAlchemy for details how to use
169 the connection object.
171 if self._engine is None:
172 await self.setup_database()
174 assert self._engine is not None
175 assert self._tables is not None
177 async with self._engine.begin() as conn:
178 yield SearchConnection(conn, self._tables, self._property_cache)
181 async def status(self) -> StatusResult:
182 """ Return the status of the database.
185 async with self.begin() as conn:
186 conn.set_query_timeout(self.query_timeout)
187 status = await get_status(conn)
188 except (PGCORE_ERROR, sa.exc.OperationalError):
189 return StatusResult(700, 'Database connection failed')
194 async def details(self, place: ntyp.PlaceRef, **params: Any) -> Optional[DetailedResult]:
195 """ Get detailed information about a place in the database.
197 Returns None if there is no entry under the given ID.
199 details = ntyp.LookupDetails.from_kwargs(params)
200 async with self.begin() as conn:
201 conn.set_query_timeout(self.query_timeout)
203 await make_query_analyzer(conn)
204 return await get_detailed_place(conn, place, details)
207 async def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
208 """ Get simple information about a list of places.
210 Returns a list of place information for all IDs that were found.
212 details = ntyp.LookupDetails.from_kwargs(params)
213 async with self.begin() as conn:
214 conn.set_query_timeout(self.query_timeout)
216 await make_query_analyzer(conn)
217 return SearchResults(filter(None,
218 [await get_simple_place(conn, p, details) for p in places]))
221 async def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
222 """ Find a place by its coordinates. Also known as reverse geocoding.
224 Returns the closest result that can be found or None if
225 no place matches the given criteria.
227 # The following negation handles NaN correctly. Don't change.
228 if not abs(coord[0]) <= 180 or not abs(coord[1]) <= 90:
229 # There are no results to be expected outside valid coordinates.
232 details = ntyp.ReverseDetails.from_kwargs(params)
233 async with self.begin() as conn:
234 conn.set_query_timeout(self.query_timeout)
236 await make_query_analyzer(conn)
237 geocoder = ReverseGeocoder(conn, details,
238 self.reverse_restrict_to_country_area)
239 return await geocoder.lookup(coord)
242 async def search(self, query: str, **params: Any) -> SearchResults:
243 """ Find a place by free-text search. Also known as forward geocoding.
245 query = query.strip()
247 raise UsageError('Nothing to search for.')
249 async with self.begin() as conn:
250 conn.set_query_timeout(self.query_timeout)
251 geocoder = ForwardGeocoder(conn, ntyp.SearchDetails.from_kwargs(params),
252 self.config.get_int('REQUEST_TIMEOUT') \
253 if self.config.REQUEST_TIMEOUT else None)
254 phrases = [Phrase(PhraseType.NONE, p.strip()) for p in query.split(',')]
255 return await geocoder.lookup(phrases)
258 # pylint: disable=too-many-arguments,too-many-branches
259 async def search_address(self, amenity: Optional[str] = None,
260 street: Optional[str] = None,
261 city: Optional[str] = None,
262 county: Optional[str] = None,
263 state: Optional[str] = None,
264 country: Optional[str] = None,
265 postalcode: Optional[str] = None,
266 **params: Any) -> SearchResults:
267 """ Find an address using structured search.
269 async with self.begin() as conn:
270 conn.set_query_timeout(self.query_timeout)
271 details = ntyp.SearchDetails.from_kwargs(params)
273 phrases: List[Phrase] = []
276 phrases.append(Phrase(PhraseType.AMENITY, amenity))
278 phrases.append(Phrase(PhraseType.STREET, street))
280 phrases.append(Phrase(PhraseType.CITY, city))
282 phrases.append(Phrase(PhraseType.COUNTY, county))
284 phrases.append(Phrase(PhraseType.STATE, state))
286 phrases.append(Phrase(PhraseType.POSTCODE, postalcode))
288 phrases.append(Phrase(PhraseType.COUNTRY, country))
291 raise UsageError('Nothing to search for.')
293 if amenity or street:
294 details.restrict_min_max_rank(26, 30)
296 details.restrict_min_max_rank(13, 25)
298 details.restrict_min_max_rank(10, 12)
300 details.restrict_min_max_rank(5, 9)
302 details.restrict_min_max_rank(5, 11)
304 details.restrict_min_max_rank(4, 4)
306 if 'layers' not in params:
307 details.layers = ntyp.DataLayer.ADDRESS
309 details.layers |= ntyp.DataLayer.POI
311 geocoder = ForwardGeocoder(conn, details,
312 self.config.get_int('REQUEST_TIMEOUT') \
313 if self.config.REQUEST_TIMEOUT else None)
314 return await geocoder.lookup(phrases)
317 async def search_category(self, categories: List[Tuple[str, str]],
318 near_query: Optional[str] = None,
319 **params: Any) -> SearchResults:
320 """ Find an object of a certain category near another place.
321 The near place may either be given as an unstructured search
322 query in itself or as coordinates.
325 return SearchResults()
327 details = ntyp.SearchDetails.from_kwargs(params)
328 async with self.begin() as conn:
329 conn.set_query_timeout(self.query_timeout)
331 phrases = [Phrase(PhraseType.NONE, p) for p in near_query.split(',')]
335 await make_query_analyzer(conn)
337 geocoder = ForwardGeocoder(conn, details,
338 self.config.get_int('REQUEST_TIMEOUT') \
339 if self.config.REQUEST_TIMEOUT else None)
340 return await geocoder.lookup_pois(categories, phrases)
345 """ This class provides a thin synchronous wrapper around the asynchronous
346 Nominatim functions. It creates its own event loop and runs each
347 synchronous function call to completion using that loop.
350 def __init__(self, project_dir: Path,
351 environ: Optional[Mapping[str, str]] = None) -> None:
352 """ Initiate a new frontend object with synchronous API functions.
355 project_dir: Path to the
356 [project directory](../admin/Import.md#creating-the-project-directory)
357 of the local Nominatim installation.
358 environ: Mapping of [configuration parameters](../customize/Settings.md).
359 When set, replaces any configuration via environment variables.
360 Settings in this mapping also have precedence over any
361 parameters found in the `.env` file of the project directory.
363 self._loop = asyncio.new_event_loop()
364 self._async_api = NominatimAPIAsync(project_dir, environ, loop=self._loop)
367 def close(self) -> None:
368 """ Close all active connections to the database.
370 This function also closes the asynchronous worker loop making
371 the NominatimAPI object unusuable.
373 self._loop.run_until_complete(self._async_api.close())
378 def config(self) -> Configuration:
379 """ Provide read-only access to the [configuration](#Configuration)
382 return self._async_api.config
384 def status(self) -> StatusResult:
385 """ Return the status of the database as a dataclass object
386 with the fields described below.
389 status(int): A status code as described on the status page.
390 message(str): Either 'OK' or a human-readable message of the
392 software_version(tuple): A tuple with the version of the
393 Nominatim library consisting of (major, minor, patch, db-patch)
395 database_version(tuple): A tuple with the version of the library
396 which was used for the import or last migration.
397 Also consists of (major, minor, patch, db-patch).
398 data_updated(datetime): Timestamp with the age of the data.
400 return self._loop.run_until_complete(self._async_api.status())
403 def details(self, place: ntyp.PlaceRef, **params: Any) -> Optional[DetailedResult]:
404 """ Get detailed information about a place in the database.
406 The result is a dataclass object with the fields described below
407 or `None` if the place could not be found in the database.
410 place: Description of the place to look up. See
411 [Place identification](Input-Parameter-Types.md#place-identification)
412 for the various ways to reference a place.
415 geometry_output (enum): Add the full geometry of the place to the result.
416 Multiple formats may be selected. Note that geometries can become
417 quite large. (Default: none)
418 geometry_simplification (float): Simplification factor to use on
419 the geometries before returning them. The factor expresses
420 the tolerance in degrees from which the geometry may differ.
421 Topology is preserved. (Default: 0.0)
422 address_details (bool): Add detailed information about the places
423 that make up the address of the requested object. (Default: False)
424 linked_places (bool): Add detailed information about the places
425 that link to the result. (Default: False)
426 parented_places (bool): Add detailed information about all places
427 for which the requested object is a parent, i.e. all places for
428 which the object provides the address details.
429 Only POI places can have parents. (Default: False)
430 keywords (bool): Add detailed information about the search terms
434 source_table (enum): Data source of the place. See below for possible values.
435 category (tuple): A tuple of two strings with the primary OSM tag
437 centroid (Point): Point position of the place.
438 place_id (Optional[int]): Internal ID of the place. This ID may differ
439 for the same place between different installations.
440 parent_place_id (Optional(int]): Internal ID of the parent of this
441 place. Only meaning full for POI-like objects (places with a
443 linked_place_id (Optional[int]): Internal ID of the place this object
444 linkes to. When this ID is set then there is no guarantee that
445 the rest of the result information is complete.
446 admin_level (int): Value of the `admin_level` OSM tag. Only meaningful
447 for administrative boundary objects.
448 indexed_date (datetime): Timestamp when the place was last updated.
449 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
450 names (Optional[dict]): Dictionary of names of the place. Keys are
451 usually the corresponding OSM tag keys.
452 address (Optional[dict]): Dictionary of address parts directly
453 attributed to the place. Keys are usually the corresponding
454 OSM tag keys with the `addr:` prefix removed.
455 extratags (Optional[dict]): Dictionary of additional attributes for
456 the place. Usually OSM tag keys and values.
457 housenumber (Optional[str]): House number of the place, normalised
458 for lookup. To get the house number in its original spelling,
459 use `address['housenumber']`.
460 postcode (Optional[str]): Computed postcode for the place. To get
461 directly attributed postcodes, use `address['postcode']` instead.
462 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
463 The string has the format <language code>:<wikipedia title>.
464 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
465 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
466 importance (Optional[float]): Relative importance of the place. This is a measure
467 how likely the place will be searched for.
468 country_code (Optional[str]): Country the feature is in as
469 ISO 3166-1 alpha-2 country code.
470 address_rows (Optional[AddressLines]): List of places that make up the
471 computed address. `None` when `address_details` parameter was False.
472 linked_rows (Optional[AddressLines]): List of places that link to the object.
473 `None` when `linked_places` parameter was False.
474 parented_rows (Optional[AddressLines]): List of direct children of the place.
475 `None` when `parented_places` parameter was False.
476 name_keywords (Optional[WordInfos]): List of search words for the name of
477 the place. `None` when `keywords` parameter is set to False.
478 address_keywords (Optional[WordInfos]): List of search word for the address of
479 the place. `None` when `keywords` parameter is set to False.
480 geometry (dict): Dictionary containing the full geometry of the place
481 in the formats requested in the `geometry_output` parameter.
483 return self._loop.run_until_complete(self._async_api.details(place, **params))
486 def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
487 """ Get simple information about a list of places.
489 Returns a list of place information for all IDs that were found.
490 Each result is a dataclass with the fields detailed below.
493 places: List of descriptions of the place to look up. See
494 [Place identification](Input-Parameter-Types.md#place-identification)
495 for the various ways to reference a place.
498 geometry_output (enum): Add the full geometry of the place to the result.
499 Multiple formats may be selected. Note that geometries can become
500 quite large. (Default: none)
501 geometry_simplification (float): Simplification factor to use on
502 the geometries before returning them. The factor expresses
503 the tolerance in degrees from which the geometry may differ.
504 Topology is preserved. (Default: 0.0)
505 address_details (bool): Add detailed information about the places
506 that make up the address of the requested object. (Default: False)
507 linked_places (bool): Add detailed information about the places
508 that link to the result. (Default: False)
509 parented_places (bool): Add detailed information about all places
510 for which the requested object is a parent, i.e. all places for
511 which the object provides the address details.
512 Only POI places can have parents. (Default: False)
513 keywords (bool): Add detailed information about the search terms
517 source_table (enum): Data source of the place. See below for possible values.
518 category (tuple): A tuple of two strings with the primary OSM tag
520 centroid (Point): Point position of the place.
521 place_id (Optional[int]): Internal ID of the place. This ID may differ
522 for the same place between different installations.
523 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
524 names (Optional[dict]): Dictionary of names of the place. Keys are
525 usually the corresponding OSM tag keys.
526 address (Optional[dict]): Dictionary of address parts directly
527 attributed to the place. Keys are usually the corresponding
528 OSM tag keys with the `addr:` prefix removed.
529 extratags (Optional[dict]): Dictionary of additional attributes for
530 the place. Usually OSM tag keys and values.
531 housenumber (Optional[str]): House number of the place, normalised
532 for lookup. To get the house number in its original spelling,
533 use `address['housenumber']`.
534 postcode (Optional[str]): Computed postcode for the place. To get
535 directly attributed postcodes, use `address['postcode']` instead.
536 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
537 The string has the format <language code>:<wikipedia title>.
538 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
539 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
540 importance (Optional[float]): Relative importance of the place. This is a measure
541 how likely the place will be searched for.
542 country_code (Optional[str]): Country the feature is in as
543 ISO 3166-1 alpha-2 country code.
544 address_rows (Optional[AddressLines]): List of places that make up the
545 computed address. `None` when `address_details` parameter was False.
546 linked_rows (Optional[AddressLines]): List of places that link to the object.
547 `None` when `linked_places` parameter was False.
548 parented_rows (Optional[AddressLines]): List of direct children of the place.
549 `None` when `parented_places` parameter was False.
550 name_keywords (Optional[WordInfos]): List of search words for the name of
551 the place. `None` when `keywords` parameter is set to False.
552 address_keywords (Optional[WordInfos]): List of search word for the address of
553 the place. `None` when `keywords` parameter is set to False.
554 bbox (Bbox): Bounding box of the full geometry of the place.
555 If the place is a single point, then the size of the bounding
556 box is guessed according to the type of place.
557 geometry (dict): Dictionary containing the full geometry of the place
558 in the formats requested in the `geometry_output` parameter.
560 return self._loop.run_until_complete(self._async_api.lookup(places, **params))
563 def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
564 """ Find a place by its coordinates. Also known as reverse geocoding.
566 Returns the closest result that can be found or `None` if
567 no place matches the given criteria. The result is a dataclass
568 with the fields as detailed below.
571 coord: Coordinate to lookup the place for as a Point
572 or a tuple (x, y). Must be in WGS84 projection.
575 max_rank (int): Highest address rank to return. Can be used to
576 restrict search to streets or settlements.
577 layers (enum): Defines the kind of data to take into account.
578 See description of layers below. (Default: addresses and POIs)
579 geometry_output (enum): Add the full geometry of the place to the result.
580 Multiple formats may be selected. Note that geometries can become
581 quite large. (Default: none)
582 geometry_simplification (float): Simplification factor to use on
583 the geometries before returning them. The factor expresses
584 the tolerance in degrees from which the geometry may differ.
585 Topology is preserved. (Default: 0.0)
586 address_details (bool): Add detailed information about the places
587 that make up the address of the requested object. (Default: False)
588 linked_places (bool): Add detailed information about the places
589 that link to the result. (Default: False)
590 parented_places (bool): Add detailed information about all places
591 for which the requested object is a parent, i.e. all places for
592 which the object provides the address details.
593 Only POI places can have parents. (Default: False)
594 keywords (bool): Add detailed information about the search terms
598 source_table (enum): Data source of the place. See below for possible values.
599 category (tuple): A tuple of two strings with the primary OSM tag
601 centroid (Point): Point position of the place.
602 place_id (Optional[int]): Internal ID of the place. This ID may differ
603 for the same place between different installations.
604 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
605 names (Optional[dict]): Dictionary of names of the place. Keys are
606 usually the corresponding OSM tag keys.
607 address (Optional[dict]): Dictionary of address parts directly
608 attributed to the place. Keys are usually the corresponding
609 OSM tag keys with the `addr:` prefix removed.
610 extratags (Optional[dict]): Dictionary of additional attributes for
611 the place. Usually OSM tag keys and values.
612 housenumber (Optional[str]): House number of the place, normalised
613 for lookup. To get the house number in its original spelling,
614 use `address['housenumber']`.
615 postcode (Optional[str]): Computed postcode for the place. To get
616 directly attributed postcodes, use `address['postcode']` instead.
617 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
618 The string has the format <language code>:<wikipedia title>.
619 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
620 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
621 importance (Optional[float]): Relative importance of the place. This is a measure
622 how likely the place will be searched for.
623 country_code (Optional[str]): Country the feature is in as
624 ISO 3166-1 alpha-2 country code.
625 address_rows (Optional[AddressLines]): List of places that make up the
626 computed address. `None` when `address_details` parameter was False.
627 linked_rows (Optional[AddressLines]): List of places that link to the object.
628 `None` when `linked_places` parameter was False.
629 parented_rows (Optional[AddressLines]): List of direct children of the place.
630 `None` when `parented_places` parameter was False.
631 name_keywords (Optional[WordInfos]): List of search words for the name of
632 the place. `None` when `keywords` parameter is set to False.
633 address_keywords (Optional[WordInfos]): List of search word for the address of
634 the place. `None` when `keywords` parameter is set to False.
635 bbox (Bbox): Bounding box of the full geometry of the place.
636 If the place is a single point, then the size of the bounding
637 box is guessed according to the type of place.
638 geometry (dict): Dictionary containing the full geometry of the place
639 in the formats requested in the `geometry_output` parameter.
640 distance (Optional[float]): Distance in degree from the input point.
642 return self._loop.run_until_complete(self._async_api.reverse(coord, **params))
645 def search(self, query: str, **params: Any) -> SearchResults:
646 """ Find a place by free-text search. Also known as forward geocoding.
649 query: Free-form text query searching for a place.
652 max_results (int): Maximum number of results to return. The
653 actual number of results may be less. (Default: 10)
654 min_rank (int): Lowest permissible rank for the result.
655 For addressable places this is the minimum
656 [address rank](../customize/Ranking.md#address-rank). For all
657 other places the [search rank](../customize/Ranking.md#search-rank)
659 max_rank (int): Highest permissible rank for the result. See min_rank above.
660 layers (enum): Defines the kind of data to take into account.
661 See [layers section](Input-Parameter-Types.md#layers) for details.
662 (Default: addresses and POIs)
663 countries (list[str]): Restrict search to countries with the given
664 ISO 3166-1 alpha-2 country code. An empty list (the default)
665 disables this filter.
666 excluded (list[int]): A list of internal IDs of places to exclude
668 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
669 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
670 as a filter and return only results within the bounding box.
671 near (Optional[Point]): Focus search around the given point and
672 return results ordered by distance to the given point.
673 near_radius (Optional[float]): Restrict results to results within
674 the given distance in degrees of `near` point. Ignored, when
676 categories (list[tuple]): Restrict search to places of the given
677 categories. The category is the main OSM tag assigned to each
678 place. An empty list (the default) disables this filter.
679 geometry_output (enum): Add the full geometry of the place to the result.
680 Multiple formats may be selected. Note that geometries can become
681 quite large. (Default: none)
682 geometry_simplification (float): Simplification factor to use on
683 the geometries before returning them. The factor expresses
684 the tolerance in degrees from which the geometry may differ.
685 Topology is preserved. (Default: 0.0)
686 address_details (bool): Add detailed information about the places
687 that make up the address of the requested object. (Default: False)
688 linked_places (bool): Add detailed information about the places
689 that link to the result. (Default: False)
690 parented_places (bool): Add detailed information about all places
691 for which the requested object is a parent, i.e. all places for
692 which the object provides the address details.
693 Only POI places can have parents. (Default: False)
694 keywords (bool): Add detailed information about the search terms
698 source_table (enum): Data source of the place. See below for possible values.
699 category (tuple): A tuple of two strings with the primary OSM tag
701 centroid (Point): Point position of the place.
702 place_id (Optional[int]): Internal ID of the place. This ID may differ
703 for the same place between different installations.
704 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
705 names (Optional[dict]): Dictionary of names of the place. Keys are
706 usually the corresponding OSM tag keys.
707 address (Optional[dict]): Dictionary of address parts directly
708 attributed to the place. Keys are usually the corresponding
709 OSM tag keys with the `addr:` prefix removed.
710 extratags (Optional[dict]): Dictionary of additional attributes for
711 the place. Usually OSM tag keys and values.
712 housenumber (Optional[str]): House number of the place, normalised
713 for lookup. To get the house number in its original spelling,
714 use `address['housenumber']`.
715 postcode (Optional[str]): Computed postcode for the place. To get
716 directly attributed postcodes, use `address['postcode']` instead.
717 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
718 The string has the format <language code>:<wikipedia title>.
719 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
720 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
721 importance (Optional[float]): Relative importance of the place. This is a measure
722 how likely the place will be searched for.
723 country_code (Optional[str]): Country the feature is in as
724 ISO 3166-1 alpha-2 country code.
725 address_rows (Optional[AddressLines]): List of places that make up the
726 computed address. `None` when `address_details` parameter was False.
727 linked_rows (Optional[AddressLines]): List of places that link to the object.
728 `None` when `linked_places` parameter was False.
729 parented_rows (Optional[AddressLines]): List of direct children of the place.
730 `None` when `parented_places` parameter was False.
731 name_keywords (Optional[WordInfos]): List of search words for the name of
732 the place. `None` when `keywords` parameter is set to False.
733 address_keywords (Optional[WordInfos]): List of search word for the address of
734 the place. `None` when `keywords` parameter is set to False.
735 bbox (Bbox): Bounding box of the full geometry of the place.
736 If the place is a single point, then the size of the bounding
737 box is guessed according to the type of place.
738 geometry (dict): Dictionary containing the full geometry of the place
739 in the formats requested in the `geometry_output` parameter.
741 return self._loop.run_until_complete(
742 self._async_api.search(query, **params))
745 # pylint: disable=too-many-arguments
746 def search_address(self, amenity: Optional[str] = None,
747 street: Optional[str] = None,
748 city: Optional[str] = None,
749 county: Optional[str] = None,
750 state: Optional[str] = None,
751 country: Optional[str] = None,
752 postalcode: Optional[str] = None,
753 **params: Any) -> SearchResults:
754 """ Find an address using structured search.
757 amenity: Name of a POI.
758 street: Street and optionally housenumber of the address. If the address
759 does not have a street, then the place the housenumber references to.
760 city: Postal city of the address.
761 county: County equivalent of the address. Does not exist in all
763 state: State or province of the address.
764 country: Country with its full name or its ISO 3166-1 alpha-2 country code.
765 Do not use together with the country_code filter.
766 postalcode: Post code or ZIP for the place.
769 max_results (int): Maximum number of results to return. The
770 actual number of results may be less. (Default: 10)
771 min_rank (int): Lowest permissible rank for the result.
772 For addressable places this is the minimum
773 [address rank](../customize/Ranking.md#address-rank). For all
774 other places the [search rank](../customize/Ranking.md#search-rank)
776 max_rank (int): Highest permissible rank for the result. See min_rank above.
777 layers (enum): Defines the kind of data to take into account.
778 See [layers section](Input-Parameter-Types.md#layers) for details.
779 (Default: addresses and POIs)
780 countries (list[str]): Restrict search to countries with the given
781 ISO 3166-1 alpha-2 country code. An empty list (the default)
782 disables this filter. Do not use, when the country parameter
784 excluded (list[int]): A list of internal IDs of places to exclude
786 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
787 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
788 as a filter and return only results within the bounding box.
789 near (Optional[Point]): Focus search around the given point and
790 return results ordered by distance to the given point.
791 near_radius (Optional[float]): Restrict results to results within
792 the given distance in degrees of `near` point. Ignored, when
794 categories (list[tuple]): Restrict search to places of the given
795 categories. The category is the main OSM tag assigned to each
796 place. An empty list (the default) disables this filter.
797 geometry_output (enum): Add the full geometry of the place to the result.
798 Multiple formats may be selected. Note that geometries can become
799 quite large. (Default: none)
800 geometry_simplification (float): Simplification factor to use on
801 the geometries before returning them. The factor expresses
802 the tolerance in degrees from which the geometry may differ.
803 Topology is preserved. (Default: 0.0)
804 address_details (bool): Add detailed information about the places
805 that make up the address of the requested object. (Default: False)
806 linked_places (bool): Add detailed information about the places
807 that link to the result. (Default: False)
808 parented_places (bool): Add detailed information about all places
809 for which the requested object is a parent, i.e. all places for
810 which the object provides the address details.
811 Only POI places can have parents. (Default: False)
812 keywords (bool): Add detailed information about the search terms
816 source_table (enum): Data source of the place. See below for possible values.
817 category (tuple): A tuple of two strings with the primary OSM tag
819 centroid (Point): Point position of the place.
820 place_id (Optional[int]): Internal ID of the place. This ID may differ
821 for the same place between different installations.
822 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
823 names (Optional[dict]): Dictionary of names of the place. Keys are
824 usually the corresponding OSM tag keys.
825 address (Optional[dict]): Dictionary of address parts directly
826 attributed to the place. Keys are usually the corresponding
827 OSM tag keys with the `addr:` prefix removed.
828 extratags (Optional[dict]): Dictionary of additional attributes for
829 the place. Usually OSM tag keys and values.
830 housenumber (Optional[str]): House number of the place, normalised
831 for lookup. To get the house number in its original spelling,
832 use `address['housenumber']`.
833 postcode (Optional[str]): Computed postcode for the place. To get
834 directly attributed postcodes, use `address['postcode']` instead.
835 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
836 The string has the format <language code>:<wikipedia title>.
837 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
838 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
839 importance (Optional[float]): Relative importance of the place. This is a measure
840 how likely the place will be searched for.
841 country_code (Optional[str]): Country the feature is in as
842 ISO 3166-1 alpha-2 country code.
843 address_rows (Optional[AddressLines]): List of places that make up the
844 computed address. `None` when `address_details` parameter was False.
845 linked_rows (Optional[AddressLines]): List of places that link to the object.
846 `None` when `linked_places` parameter was False.
847 parented_rows (Optional[AddressLines]): List of direct children of the place.
848 `None` when `parented_places` parameter was False.
849 name_keywords (Optional[WordInfos]): List of search words for the name of
850 the place. `None` when `keywords` parameter is set to False.
851 address_keywords (Optional[WordInfos]): List of search word for the address of
852 the place. `None` when `keywords` parameter is set to False.
853 bbox (Bbox): Bounding box of the full geometry of the place.
854 If the place is a single point, then the size of the bounding
855 box is guessed according to the type of place.
856 geometry (dict): Dictionary containing the full geometry of the place
857 in the formats requested in the `geometry_output` parameter.
859 return self._loop.run_until_complete(
860 self._async_api.search_address(amenity, street, city, county,
861 state, country, postalcode, **params))
864 def search_category(self, categories: List[Tuple[str, str]],
865 near_query: Optional[str] = None,
866 **params: Any) -> SearchResults:
867 """ Find an object of a certain category near another place.
869 The near place may either be given as an unstructured search
870 query in itself or as a geographic area through the
871 viewbox or near parameters.
874 categories: Restrict search to places of the given
875 categories. The category is the main OSM tag assigned to each
877 near_query: Optional free-text query to define the are to
881 max_results (int): Maximum number of results to return. The
882 actual number of results may be less. (Default: 10)
883 min_rank (int): Lowest permissible rank for the result.
884 For addressable places this is the minimum
885 [address rank](../customize/Ranking.md#address-rank). For all
886 other places the [search rank](../customize/Ranking.md#search-rank)
888 max_rank (int): Highest permissible rank for the result. See min_rank above.
889 layers (enum): Defines the kind of data to take into account.
890 See [layers section](Input-Parameter-Types.md#layers) for details.
891 (Default: addresses and POIs)
892 countries (list[str]): Restrict search to countries with the given
893 ISO 3166-1 alpha-2 country code. An empty list (the default)
894 disables this filter.
895 excluded (list[int]): A list of internal IDs of places to exclude
897 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
898 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
899 as a filter and return only results within the bounding box.
900 near (Optional[Point]): Focus search around the given point and
901 return results ordered by distance to the given point.
902 near_radius (Optional[float]): Restrict results to results within
903 the given distance in degrees of `near` point. Ignored, when
905 geometry_output (enum): Add the full geometry of the place to the result.
906 Multiple formats may be selected. Note that geometries can become
907 quite large. (Default: none)
908 geometry_simplification (float): Simplification factor to use on
909 the geometries before returning them. The factor expresses
910 the tolerance in degrees from which the geometry may differ.
911 Topology is preserved. (Default: 0.0)
912 address_details (bool): Add detailed information about the places
913 that make up the address of the requested object. (Default: False)
914 linked_places (bool): Add detailed information about the places
915 that link to the result. (Default: False)
916 parented_places (bool): Add detailed information about all places
917 for which the requested object is a parent, i.e. all places for
918 which the object provides the address details.
919 Only POI places can have parents. (Default: False)
920 keywords (bool): Add detailed information about the search terms
924 source_table (enum): Data source of the place. See below for possible values.
925 category (tuple): A tuple of two strings with the primary OSM tag
927 centroid (Point): Point position of the place.
928 place_id (Optional[int]): Internal ID of the place. This ID may differ
929 for the same place between different installations.
930 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
931 names (Optional[dict]): Dictionary of names of the place. Keys are
932 usually the corresponding OSM tag keys.
933 address (Optional[dict]): Dictionary of address parts directly
934 attributed to the place. Keys are usually the corresponding
935 OSM tag keys with the `addr:` prefix removed.
936 extratags (Optional[dict]): Dictionary of additional attributes for
937 the place. Usually OSM tag keys and values.
938 housenumber (Optional[str]): House number of the place, normalised
939 for lookup. To get the house number in its original spelling,
940 use `address['housenumber']`.
941 postcode (Optional[str]): Computed postcode for the place. To get
942 directly attributed postcodes, use `address['postcode']` instead.
943 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
944 The string has the format <language code>:<wikipedia title>.
945 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
946 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
947 importance (Optional[float]): Relative importance of the place. This is a measure
948 how likely the place will be searched for.
949 country_code (Optional[str]): Country the feature is in as
950 ISO 3166-1 alpha-2 country code.
951 address_rows (Optional[AddressLines]): List of places that make up the
952 computed address. `None` when `address_details` parameter was False.
953 linked_rows (Optional[AddressLines]): List of places that link to the object.
954 `None` when `linked_places` parameter was False.
955 parented_rows (Optional[AddressLines]): List of direct children of the place.
956 `None` when `parented_places` parameter was False.
957 name_keywords (Optional[WordInfos]): List of search words for the name of
958 the place. `None` when `keywords` parameter is set to False.
959 address_keywords (Optional[WordInfos]): List of search word for the address of
960 the place. `None` when `keywords` parameter is set to False.
961 bbox (Bbox): Bounding box of the full geometry of the place.
962 If the place is a single point, then the size of the bounding
963 box is guessed according to the type of place.
964 geometry (dict): Dictionary containing the full geometry of the place
965 in the formats requested in the `geometry_output` parameter.
967 return self._loop.run_until_complete(
968 self._async_api.search_category(categories, near_query, **params))