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 from nominatim.config import Configuration
23 from nominatim.api.connection import SearchConnection
24 from nominatim.api.status import get_status, StatusResult
25 from nominatim.api.lookup import get_detailed_place, get_simple_place
26 from nominatim.api.reverse import ReverseGeocoder
27 from nominatim.api.search import ForwardGeocoder, Phrase, PhraseType, make_query_analyzer
28 import nominatim.api.types as ntyp
29 from nominatim.api.results import DetailedResult, ReverseResult, SearchResults
32 class NominatimAPIAsync:
33 """ The main frontend to the Nominatim database implements the
34 functions for lookup, forward and reverse geocoding using
35 asynchronous functions.
37 This class shares most of the functions with its synchronous
38 version. There are some additional functions or parameters,
39 which are documented below.
41 def __init__(self, project_dir: Path,
42 environ: Optional[Mapping[str, str]] = None,
43 loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
44 """ Initiate a new frontend object with synchronous API functions.
47 project_dir: Path to the
48 [project directory](../admin/Import.md#creating-the-project-directory)
49 of the local Nominatim installation.
50 environ: Mapping of [configuration parameters](../customize/Settings.md).
51 When set, replaces any configuration via environment variables.
52 Settings in this mapping also have precedence over any
53 parameters found in the `.env` file of the project directory.
54 loop: The asyncio event loop that will be used when calling
55 functions. Only needed, when a custom event loop is used
56 and the Python version is 3.9 or earlier.
58 self.config = Configuration(project_dir, environ)
59 self.query_timeout = self.config.get_int('QUERY_TIMEOUT') \
60 if self.config.QUERY_TIMEOUT else None
61 self.server_version = 0
63 if sys.version_info >= (3, 10):
64 self._engine_lock = asyncio.Lock()
66 self._engine_lock = asyncio.Lock(loop=loop) # pylint: disable=unexpected-keyword-arg
67 self._engine: Optional[sa_asyncio.AsyncEngine] = None
68 self._tables: Optional[SearchTables] = None
69 self._property_cache: Dict[str, Any] = {'DB:server_version': 0}
72 async def setup_database(self) -> None:
73 """ Set up the SQL engine and connections.
75 This function will be implicitly called when the database is
76 accessed for the first time. You may also call it explicitly to
77 avoid that the first call is delayed by the setup.
79 async with self._engine_lock:
83 dsn = self.config.get_database_params()
84 pool_size = self.config.get_int('API_POOL_SIZE')
86 query = {k: v for k, v in dsn.items()
87 if k not in ('user', 'password', 'dbname', 'host', 'port')}
89 dburl = sa.engine.URL.create(
90 f'postgresql+{PGCORE_LIB}',
91 database=dsn.get('dbname'),
92 username=dsn.get('user'), password=dsn.get('password'),
93 host=dsn.get('host'), port=int(dsn['port']) if 'port' in dsn else None,
95 engine = sa_asyncio.create_async_engine(dburl, future=True,
96 max_overflow=0, pool_size=pool_size,
97 echo=self.config.get_bool('DEBUG_SQL'))
100 async with engine.begin() as conn:
101 result = await conn.scalar(sa.text('SHOW server_version_num'))
102 server_version = int(result)
103 except (PGCORE_ERROR, sa.exc.OperationalError):
106 if server_version >= 110000:
107 @sa.event.listens_for(engine.sync_engine, "connect")
108 def _on_connect(dbapi_con: Any, _: Any) -> None:
109 cursor = dbapi_con.cursor()
110 cursor.execute("SET jit_above_cost TO '-1'")
111 cursor.execute("SET max_parallel_workers_per_gather TO '0'")
112 # Make sure that all connections get the new settings
115 self._property_cache['DB:server_version'] = server_version
117 self._tables = SearchTables(sa.MetaData(), engine.name) # pylint: disable=no-member
118 self._engine = engine
121 async def close(self) -> None:
122 """ Close all active connections to the database. The NominatimAPIAsync
123 object remains usable after closing. If a new API functions is
124 called, new connections are created.
126 if self._engine is not None:
127 await self._engine.dispose()
130 @contextlib.asynccontextmanager
131 async def begin(self) -> AsyncIterator[SearchConnection]:
132 """ Create a new connection with automatic transaction handling.
134 This function may be used to get low-level access to the database.
135 Refer to the documentation of SQLAlchemy for details how to use
136 the connection object.
138 if self._engine is None:
139 await self.setup_database()
141 assert self._engine is not None
142 assert self._tables is not None
144 async with self._engine.begin() as conn:
145 yield SearchConnection(conn, self._tables, self._property_cache)
148 async def status(self) -> StatusResult:
149 """ Return the status of the database.
152 async with self.begin() as conn:
153 conn.set_query_timeout(self.query_timeout)
154 status = await get_status(conn)
155 except (PGCORE_ERROR, sa.exc.OperationalError):
156 return StatusResult(700, 'Database connection failed')
161 async def details(self, place: ntyp.PlaceRef, **params: Any) -> Optional[DetailedResult]:
162 """ Get detailed information about a place in the database.
164 Returns None if there is no entry under the given ID.
166 details = ntyp.LookupDetails.from_kwargs(params)
167 async with self.begin() as conn:
168 conn.set_query_timeout(self.query_timeout)
170 await make_query_analyzer(conn)
171 return await get_detailed_place(conn, place, details)
174 async def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
175 """ Get simple information about a list of places.
177 Returns a list of place information for all IDs that were found.
179 details = ntyp.LookupDetails.from_kwargs(params)
180 async with self.begin() as conn:
181 conn.set_query_timeout(self.query_timeout)
183 await make_query_analyzer(conn)
184 return SearchResults(filter(None,
185 [await get_simple_place(conn, p, details) for p in places]))
188 async def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
189 """ Find a place by its coordinates. Also known as reverse geocoding.
191 Returns the closest result that can be found or None if
192 no place matches the given criteria.
194 # The following negation handles NaN correctly. Don't change.
195 if not abs(coord[0]) <= 180 or not abs(coord[1]) <= 90:
196 # There are no results to be expected outside valid coordinates.
199 details = ntyp.ReverseDetails.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 geocoder = ReverseGeocoder(conn, details)
205 return await geocoder.lookup(coord)
208 async def search(self, query: str, **params: Any) -> SearchResults:
209 """ Find a place by free-text search. Also known as forward geocoding.
211 query = query.strip()
213 raise UsageError('Nothing to search for.')
215 async with self.begin() as conn:
216 conn.set_query_timeout(self.query_timeout)
217 geocoder = ForwardGeocoder(conn, ntyp.SearchDetails.from_kwargs(params),
218 self.config.get_int('REQUEST_TIMEOUT') \
219 if self.config.REQUEST_TIMEOUT else None)
220 phrases = [Phrase(PhraseType.NONE, p.strip()) for p in query.split(',')]
221 return await geocoder.lookup(phrases)
224 # pylint: disable=too-many-arguments,too-many-branches
225 async def search_address(self, amenity: Optional[str] = None,
226 street: Optional[str] = None,
227 city: Optional[str] = None,
228 county: Optional[str] = None,
229 state: Optional[str] = None,
230 country: Optional[str] = None,
231 postalcode: Optional[str] = None,
232 **params: Any) -> SearchResults:
233 """ Find an address using structured search.
235 async with self.begin() as conn:
236 conn.set_query_timeout(self.query_timeout)
237 details = ntyp.SearchDetails.from_kwargs(params)
239 phrases: List[Phrase] = []
242 phrases.append(Phrase(PhraseType.AMENITY, amenity))
244 phrases.append(Phrase(PhraseType.STREET, street))
246 phrases.append(Phrase(PhraseType.CITY, city))
248 phrases.append(Phrase(PhraseType.COUNTY, county))
250 phrases.append(Phrase(PhraseType.STATE, state))
252 phrases.append(Phrase(PhraseType.POSTCODE, postalcode))
254 phrases.append(Phrase(PhraseType.COUNTRY, country))
257 raise UsageError('Nothing to search for.')
259 if amenity or street:
260 details.restrict_min_max_rank(26, 30)
262 details.restrict_min_max_rank(13, 25)
264 details.restrict_min_max_rank(10, 12)
266 details.restrict_min_max_rank(5, 9)
268 details.restrict_min_max_rank(5, 11)
270 details.restrict_min_max_rank(4, 4)
272 if 'layers' not in params:
273 details.layers = ntyp.DataLayer.ADDRESS
275 details.layers |= ntyp.DataLayer.POI
277 geocoder = ForwardGeocoder(conn, details,
278 self.config.get_int('REQUEST_TIMEOUT') \
279 if self.config.REQUEST_TIMEOUT else None)
280 return await geocoder.lookup(phrases)
283 async def search_category(self, categories: List[Tuple[str, str]],
284 near_query: Optional[str] = None,
285 **params: Any) -> SearchResults:
286 """ Find an object of a certain category near another place.
287 The near place may either be given as an unstructured search
288 query in itself or as coordinates.
291 return SearchResults()
293 details = ntyp.SearchDetails.from_kwargs(params)
294 async with self.begin() as conn:
295 conn.set_query_timeout(self.query_timeout)
297 phrases = [Phrase(PhraseType.NONE, p) for p in near_query.split(',')]
301 await make_query_analyzer(conn)
303 geocoder = ForwardGeocoder(conn, details,
304 self.config.get_int('REQUEST_TIMEOUT') \
305 if self.config.REQUEST_TIMEOUT else None)
306 return await geocoder.lookup_pois(categories, phrases)
311 """ This class provides a thin synchronous wrapper around the asynchronous
312 Nominatim functions. It creates its own event loop and runs each
313 synchronous function call to completion using that loop.
316 def __init__(self, project_dir: Path,
317 environ: Optional[Mapping[str, str]] = None) -> None:
318 """ Initiate a new frontend object with synchronous API functions.
321 project_dir: Path to the
322 [project directory](../admin/Import.md#creating-the-project-directory)
323 of the local Nominatim installation.
324 environ: Mapping of [configuration parameters](../customize/Settings.md).
325 When set, replaces any configuration via environment variables.
326 Settings in this mapping also have precedence over any
327 parameters found in the `.env` file of the project directory.
329 self._loop = asyncio.new_event_loop()
330 self._async_api = NominatimAPIAsync(project_dir, environ, loop=self._loop)
333 def close(self) -> None:
334 """ Close all active connections to the database.
336 This function also closes the asynchronous worker loop making
337 the NominatimAPI object unusuable.
339 self._loop.run_until_complete(self._async_api.close())
344 def config(self) -> Configuration:
345 """ Provide read-only access to the [configuration](#Configuration)
348 return self._async_api.config
350 def status(self) -> StatusResult:
351 """ Return the status of the database as a dataclass object
352 with the fields described below.
355 status(int): A status code as described on the status page.
356 message(str): Either 'OK' or a human-readable message of the
358 software_version(tuple): A tuple with the version of the
359 Nominatim library consisting of (major, minor, patch, db-patch)
361 database_version(tuple): A tuple with the version of the library
362 which was used for the import or last migration.
363 Also consists of (major, minor, patch, db-patch).
364 data_updated(datetime): Timestamp with the age of the data.
366 return self._loop.run_until_complete(self._async_api.status())
369 def details(self, place: ntyp.PlaceRef, **params: Any) -> Optional[DetailedResult]:
370 """ Get detailed information about a place in the database.
372 The result is a dataclass object with the fields described below
373 or `None` if the place could not be found in the database.
376 place: Description of the place to look up. See
377 [Place identification](Input-Parameter-Types.md#place-identification)
378 for the various ways to reference a place.
381 geometry_output (enum): Add the full geometry of the place to the result.
382 Multiple formats may be selected. Note that geometries can become
383 quite large. (Default: none)
384 geometry_simplification (float): Simplification factor to use on
385 the geometries before returning them. The factor expresses
386 the tolerance in degrees from which the geometry may differ.
387 Topology is preserved. (Default: 0.0)
388 address_details (bool): Add detailed information about the places
389 that make up the address of the requested object. (Default: False)
390 linked_places (bool): Add detailed information about the places
391 that link to the result. (Default: False)
392 parented_places (bool): Add detailed information about all places
393 for which the requested object is a parent, i.e. all places for
394 which the object provides the address details.
395 Only POI places can have parents. (Default: False)
396 keywords (bool): Add detailed information about the search terms
400 source_table (enum): Data source of the place. See below for possible values.
401 category (tuple): A tuple of two strings with the primary OSM tag
403 centroid (Point): Point position of the place.
404 place_id (Optional[int]): Internal ID of the place. This ID may differ
405 for the same place between different installations.
406 parent_place_id (Optional(int]): Internal ID of the parent of this
407 place. Only meaning full for POI-like objects (places with a
409 linked_place_id (Optional[int]): Internal ID of the place this object
410 linkes to. When this ID is set then there is no guarantee that
411 the rest of the result information is complete.
412 admin_level (int): Value of the `admin_level` OSM tag. Only meaningful
413 for administrative boundary objects.
414 indexed_date (datetime): Timestamp when the place was last updated.
415 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
416 names (Optional[dict]): Dictionary of names of the place. Keys are
417 usually the corresponding OSM tag keys.
418 address (Optional[dict]): Dictionary of address parts directly
419 attributed to the place. Keys are usually the corresponding
420 OSM tag keys with the `addr:` prefix removed.
421 extratags (Optional[dict]): Dictionary of additional attributes for
422 the place. Usually OSM tag keys and values.
423 housenumber (Optional[str]): House number of the place, normalised
424 for lookup. To get the house number in its original spelling,
425 use `address['housenumber']`.
426 postcode (Optional[str]): Computed postcode for the place. To get
427 directly attributed postcodes, use `address['postcode']` instead.
428 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
429 The string has the format <language code>:<wikipedia title>.
430 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
431 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
432 importance (Optional[float]): Relative importance of the place. This is a measure
433 how likely the place will be searched for.
434 country_code (Optional[str]): Country the feature is in as
435 ISO 3166-1 alpha-2 country code.
436 address_rows (Optional[AddressLines]): List of places that make up the
437 computed address. `None` when `address_details` parameter was False.
438 linked_rows (Optional[AddressLines]): List of places that link to the object.
439 `None` when `linked_places` parameter was False.
440 parented_rows (Optional[AddressLines]): List of direct children of the place.
441 `None` when `parented_places` parameter was False.
442 name_keywords (Optional[WordInfos]): List of search words for the name of
443 the place. `None` when `keywords` parameter is set to False.
444 address_keywords (Optional[WordInfos]): List of search word for the address of
445 the place. `None` when `keywords` parameter is set to False.
446 geometry (dict): Dictionary containing the full geometry of the place
447 in the formats requested in the `geometry_output` parameter.
449 return self._loop.run_until_complete(self._async_api.details(place, **params))
452 def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
453 """ Get simple information about a list of places.
455 Returns a list of place information for all IDs that were found.
456 Each result is a dataclass with the fields detailed below.
459 places: List of descriptions of the place to look up. See
460 [Place identification](Input-Parameter-Types.md#place-identification)
461 for the various ways to reference a place.
464 geometry_output (enum): Add the full geometry of the place to the result.
465 Multiple formats may be selected. Note that geometries can become
466 quite large. (Default: none)
467 geometry_simplification (float): Simplification factor to use on
468 the geometries before returning them. The factor expresses
469 the tolerance in degrees from which the geometry may differ.
470 Topology is preserved. (Default: 0.0)
471 address_details (bool): Add detailed information about the places
472 that make up the address of the requested object. (Default: False)
473 linked_places (bool): Add detailed information about the places
474 that link to the result. (Default: False)
475 parented_places (bool): Add detailed information about all places
476 for which the requested object is a parent, i.e. all places for
477 which the object provides the address details.
478 Only POI places can have parents. (Default: False)
479 keywords (bool): Add detailed information about the search terms
483 source_table (enum): Data source of the place. See below for possible values.
484 category (tuple): A tuple of two strings with the primary OSM tag
486 centroid (Point): Point position of the place.
487 place_id (Optional[int]): Internal ID of the place. This ID may differ
488 for the same place between different installations.
489 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
490 names (Optional[dict]): Dictionary of names of the place. Keys are
491 usually the corresponding OSM tag keys.
492 address (Optional[dict]): Dictionary of address parts directly
493 attributed to the place. Keys are usually the corresponding
494 OSM tag keys with the `addr:` prefix removed.
495 extratags (Optional[dict]): Dictionary of additional attributes for
496 the place. Usually OSM tag keys and values.
497 housenumber (Optional[str]): House number of the place, normalised
498 for lookup. To get the house number in its original spelling,
499 use `address['housenumber']`.
500 postcode (Optional[str]): Computed postcode for the place. To get
501 directly attributed postcodes, use `address['postcode']` instead.
502 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
503 The string has the format <language code>:<wikipedia title>.
504 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
505 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
506 importance (Optional[float]): Relative importance of the place. This is a measure
507 how likely the place will be searched for.
508 country_code (Optional[str]): Country the feature is in as
509 ISO 3166-1 alpha-2 country code.
510 address_rows (Optional[AddressLines]): List of places that make up the
511 computed address. `None` when `address_details` parameter was False.
512 linked_rows (Optional[AddressLines]): List of places that link to the object.
513 `None` when `linked_places` parameter was False.
514 parented_rows (Optional[AddressLines]): List of direct children of the place.
515 `None` when `parented_places` parameter was False.
516 name_keywords (Optional[WordInfos]): List of search words for the name of
517 the place. `None` when `keywords` parameter is set to False.
518 address_keywords (Optional[WordInfos]): List of search word for the address of
519 the place. `None` when `keywords` parameter is set to False.
520 bbox (Bbox): Bounding box of the full geometry of the place.
521 If the place is a single point, then the size of the bounding
522 box is guessed according to the type of place.
523 geometry (dict): Dictionary containing the full geometry of the place
524 in the formats requested in the `geometry_output` parameter.
526 return self._loop.run_until_complete(self._async_api.lookup(places, **params))
529 def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
530 """ Find a place by its coordinates. Also known as reverse geocoding.
532 Returns the closest result that can be found or `None` if
533 no place matches the given criteria. The result is a dataclass
534 with the fields as detailed below.
537 coord: Coordinate to lookup the place for as a Point
538 or a tuple (x, y). Must be in WGS84 projection.
541 max_rank (int): Highest address rank to return. Can be used to
542 restrict search to streets or settlements.
543 layers (enum): Defines the kind of data to take into account.
544 See description of layers below. (Default: addresses and POIs)
545 geometry_output (enum): Add the full geometry of the place to the result.
546 Multiple formats may be selected. Note that geometries can become
547 quite large. (Default: none)
548 geometry_simplification (float): Simplification factor to use on
549 the geometries before returning them. The factor expresses
550 the tolerance in degrees from which the geometry may differ.
551 Topology is preserved. (Default: 0.0)
552 address_details (bool): Add detailed information about the places
553 that make up the address of the requested object. (Default: False)
554 linked_places (bool): Add detailed information about the places
555 that link to the result. (Default: False)
556 parented_places (bool): Add detailed information about all places
557 for which the requested object is a parent, i.e. all places for
558 which the object provides the address details.
559 Only POI places can have parents. (Default: False)
560 keywords (bool): Add detailed information about the search terms
564 source_table (enum): Data source of the place. See below for possible values.
565 category (tuple): A tuple of two strings with the primary OSM tag
567 centroid (Point): Point position of the place.
568 place_id (Optional[int]): Internal ID of the place. This ID may differ
569 for the same place between different installations.
570 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
571 names (Optional[dict]): Dictionary of names of the place. Keys are
572 usually the corresponding OSM tag keys.
573 address (Optional[dict]): Dictionary of address parts directly
574 attributed to the place. Keys are usually the corresponding
575 OSM tag keys with the `addr:` prefix removed.
576 extratags (Optional[dict]): Dictionary of additional attributes for
577 the place. Usually OSM tag keys and values.
578 housenumber (Optional[str]): House number of the place, normalised
579 for lookup. To get the house number in its original spelling,
580 use `address['housenumber']`.
581 postcode (Optional[str]): Computed postcode for the place. To get
582 directly attributed postcodes, use `address['postcode']` instead.
583 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
584 The string has the format <language code>:<wikipedia title>.
585 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
586 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
587 importance (Optional[float]): Relative importance of the place. This is a measure
588 how likely the place will be searched for.
589 country_code (Optional[str]): Country the feature is in as
590 ISO 3166-1 alpha-2 country code.
591 address_rows (Optional[AddressLines]): List of places that make up the
592 computed address. `None` when `address_details` parameter was False.
593 linked_rows (Optional[AddressLines]): List of places that link to the object.
594 `None` when `linked_places` parameter was False.
595 parented_rows (Optional[AddressLines]): List of direct children of the place.
596 `None` when `parented_places` parameter was False.
597 name_keywords (Optional[WordInfos]): List of search words for the name of
598 the place. `None` when `keywords` parameter is set to False.
599 address_keywords (Optional[WordInfos]): List of search word for the address of
600 the place. `None` when `keywords` parameter is set to False.
601 bbox (Bbox): Bounding box of the full geometry of the place.
602 If the place is a single point, then the size of the bounding
603 box is guessed according to the type of place.
604 geometry (dict): Dictionary containing the full geometry of the place
605 in the formats requested in the `geometry_output` parameter.
606 distance (Optional[float]): Distance in degree from the input point.
608 return self._loop.run_until_complete(self._async_api.reverse(coord, **params))
611 def search(self, query: str, **params: Any) -> SearchResults:
612 """ Find a place by free-text search. Also known as forward geocoding.
615 query: Free-form text query searching for a place.
618 max_results (int): Maximum number of results to return. The
619 actual number of results may be less. (Default: 10)
620 min_rank (int): Lowest [address rank](../customize/Ranking.md#address-rank) to return.
621 max_rank (int): Highest address rank to return.
622 layers (enum): Defines the kind of data to take into account.
623 See description of layers below. (Default: addresses and POIs)
624 countries (list[str]): Restrict search to countries with the given
625 ISO 3166-1 alpha-2 country code. An empty list (the default)
626 disables this filter.
627 excluded (list[int]): A list of internal IDs of places to exclude
629 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
630 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
631 as a filter and return only results within the bounding box.
632 near (Optional[Point]): Focus search around the given point and
633 return results ordered by distance to the given point.
634 near_radius (Optional[float]): Restrict results to results within
635 the given distance in degrees of `near` point. Ignored, when
637 categories (list[tuple]): Restrict search to places of the given
638 categories. The category is the main OSM tag assigned to each
639 place. An empty list (the default) disables this filter.
640 geometry_output (enum): Add the full geometry of the place to the result.
641 Multiple formats may be selected. Note that geometries can become
642 quite large. (Default: none)
643 geometry_simplification (float): Simplification factor to use on
644 the geometries before returning them. The factor expresses
645 the tolerance in degrees from which the geometry may differ.
646 Topology is preserved. (Default: 0.0)
647 address_details (bool): Add detailed information about the places
648 that make up the address of the requested object. (Default: False)
649 linked_places (bool): Add detailed information about the places
650 that link to the result. (Default: False)
651 parented_places (bool): Add detailed information about all places
652 for which the requested object is a parent, i.e. all places for
653 which the object provides the address details.
654 Only POI places can have parents. (Default: False)
655 keywords (bool): Add detailed information about the search terms
659 source_table (enum): Data source of the place. See below for possible values.
660 category (tuple): A tuple of two strings with the primary OSM tag
662 centroid (Point): Point position of the place.
663 place_id (Optional[int]): Internal ID of the place. This ID may differ
664 for the same place between different installations.
665 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
666 names (Optional[dict]): Dictionary of names of the place. Keys are
667 usually the corresponding OSM tag keys.
668 address (Optional[dict]): Dictionary of address parts directly
669 attributed to the place. Keys are usually the corresponding
670 OSM tag keys with the `addr:` prefix removed.
671 extratags (Optional[dict]): Dictionary of additional attributes for
672 the place. Usually OSM tag keys and values.
673 housenumber (Optional[str]): House number of the place, normalised
674 for lookup. To get the house number in its original spelling,
675 use `address['housenumber']`.
676 postcode (Optional[str]): Computed postcode for the place. To get
677 directly attributed postcodes, use `address['postcode']` instead.
678 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
679 The string has the format <language code>:<wikipedia title>.
680 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
681 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
682 importance (Optional[float]): Relative importance of the place. This is a measure
683 how likely the place will be searched for.
684 country_code (Optional[str]): Country the feature is in as
685 ISO 3166-1 alpha-2 country code.
686 address_rows (Optional[AddressLines]): List of places that make up the
687 computed address. `None` when `address_details` parameter was False.
688 linked_rows (Optional[AddressLines]): List of places that link to the object.
689 `None` when `linked_places` parameter was False.
690 parented_rows (Optional[AddressLines]): List of direct children of the place.
691 `None` when `parented_places` parameter was False.
692 name_keywords (Optional[WordInfos]): List of search words for the name of
693 the place. `None` when `keywords` parameter is set to False.
694 address_keywords (Optional[WordInfos]): List of search word for the address of
695 the place. `None` when `keywords` parameter is set to False.
696 bbox (Bbox): Bounding box of the full geometry of the place.
697 If the place is a single point, then the size of the bounding
698 box is guessed according to the type of place.
699 geometry (dict): Dictionary containing the full geometry of the place
700 in the formats requested in the `geometry_output` parameter.
702 return self._loop.run_until_complete(
703 self._async_api.search(query, **params))
706 # pylint: disable=too-many-arguments
707 def search_address(self, amenity: Optional[str] = None,
708 street: Optional[str] = None,
709 city: Optional[str] = None,
710 county: Optional[str] = None,
711 state: Optional[str] = None,
712 country: Optional[str] = None,
713 postalcode: Optional[str] = None,
714 **params: Any) -> SearchResults:
715 """ Find an address using structured search.
718 amenity: Name of a POI.
719 street: Street and optionally housenumber of the address. If the address
720 does not have a street, then the place the housenumber references to.
721 city: Postal city of the address.
722 county: County equivalent of the address. Does not exist in all
724 state: State or province of the address.
725 country: Country with its full name or its ISO 3166-1 alpha-2 country code.
726 Do not use together with the country_code filter.
727 postalcode: Post code or ZIP for the place.
730 max_results (int): Maximum number of results to return. The
731 actual number of results may be less. (Default: 10)
732 min_rank (int): Lowest [address rank](../customize/Ranking.md#address-rank) to return.
733 max_rank (int): Highest address rank to return.
734 layers (enum): Defines the kind of data to take into account.
735 See description of layers below. (Default: addresses and POIs)
736 countries (list[str]): Restrict search to countries with the given
737 ISO 3166-1 alpha-2 country code. An empty list (the default)
738 disables this filter. Do not use, when the country parameter
740 excluded (list[int]): A list of internal IDs of places to exclude
742 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
743 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
744 as a filter and return only results within the bounding box.
745 near (Optional[Point]): Focus search around the given point and
746 return results ordered by distance to the given point.
747 near_radius (Optional[float]): Restrict results to results within
748 the given distance in degrees of `near` point. Ignored, when
750 categories (list[tuple]): Restrict search to places of the given
751 categories. The category is the main OSM tag assigned to each
752 place. An empty list (the default) disables this filter.
753 geometry_output (enum): Add the full geometry of the place to the result.
754 Multiple formats may be selected. Note that geometries can become
755 quite large. (Default: none)
756 geometry_simplification (float): Simplification factor to use on
757 the geometries before returning them. The factor expresses
758 the tolerance in degrees from which the geometry may differ.
759 Topology is preserved. (Default: 0.0)
760 address_details (bool): Add detailed information about the places
761 that make up the address of the requested object. (Default: False)
762 linked_places (bool): Add detailed information about the places
763 that link to the result. (Default: False)
764 parented_places (bool): Add detailed information about all places
765 for which the requested object is a parent, i.e. all places for
766 which the object provides the address details.
767 Only POI places can have parents. (Default: False)
768 keywords (bool): Add detailed information about the search terms
772 source_table (enum): Data source of the place. See below for possible values.
773 category (tuple): A tuple of two strings with the primary OSM tag
775 centroid (Point): Point position of the place.
776 place_id (Optional[int]): Internal ID of the place. This ID may differ
777 for the same place between different installations.
778 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
779 names (Optional[dict]): Dictionary of names of the place. Keys are
780 usually the corresponding OSM tag keys.
781 address (Optional[dict]): Dictionary of address parts directly
782 attributed to the place. Keys are usually the corresponding
783 OSM tag keys with the `addr:` prefix removed.
784 extratags (Optional[dict]): Dictionary of additional attributes for
785 the place. Usually OSM tag keys and values.
786 housenumber (Optional[str]): House number of the place, normalised
787 for lookup. To get the house number in its original spelling,
788 use `address['housenumber']`.
789 postcode (Optional[str]): Computed postcode for the place. To get
790 directly attributed postcodes, use `address['postcode']` instead.
791 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
792 The string has the format <language code>:<wikipedia title>.
793 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
794 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
795 importance (Optional[float]): Relative importance of the place. This is a measure
796 how likely the place will be searched for.
797 country_code (Optional[str]): Country the feature is in as
798 ISO 3166-1 alpha-2 country code.
799 address_rows (Optional[AddressLines]): List of places that make up the
800 computed address. `None` when `address_details` parameter was False.
801 linked_rows (Optional[AddressLines]): List of places that link to the object.
802 `None` when `linked_places` parameter was False.
803 parented_rows (Optional[AddressLines]): List of direct children of the place.
804 `None` when `parented_places` parameter was False.
805 name_keywords (Optional[WordInfos]): List of search words for the name of
806 the place. `None` when `keywords` parameter is set to False.
807 address_keywords (Optional[WordInfos]): List of search word for the address of
808 the place. `None` when `keywords` parameter is set to False.
809 bbox (Bbox): Bounding box of the full geometry of the place.
810 If the place is a single point, then the size of the bounding
811 box is guessed according to the type of place.
812 geometry (dict): Dictionary containing the full geometry of the place
813 in the formats requested in the `geometry_output` parameter.
815 return self._loop.run_until_complete(
816 self._async_api.search_address(amenity, street, city, county,
817 state, country, postalcode, **params))
820 def search_category(self, categories: List[Tuple[str, str]],
821 near_query: Optional[str] = None,
822 **params: Any) -> SearchResults:
823 """ Find an object of a certain category near another place.
825 The near place may either be given as an unstructured search
826 query in itself or as a geographic area through the
827 viewbox or near parameters.
830 categories: Restrict search to places of the given
831 categories. The category is the main OSM tag assigned to each
833 near_query: Optional free-text query to define the are to
837 max_results (int): Maximum number of results to return. The
838 actual number of results may be less. (Default: 10)
839 min_rank (int): Lowest [address rank](../customize/Ranking.md#address-rank) to return.
840 max_rank (int): Highest address rank to return.
841 layers (enum): Defines the kind of data to take into account.
842 See description of layers below. (Default: addresses and POIs)
843 countries (list[str]): Restrict search to countries with the given
844 ISO 3166-1 alpha-2 country code. An empty list (the default)
845 disables this filter.
846 excluded (list[int]): A list of internal IDs of places to exclude
848 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
849 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
850 as a filter and return only results within the bounding box.
851 near (Optional[Point]): Focus search around the given point and
852 return results ordered by distance to the given point.
853 near_radius (Optional[float]): Restrict results to results within
854 the given distance in degrees of `near` point. Ignored, when
856 geometry_output (enum): Add the full geometry of the place to the result.
857 Multiple formats may be selected. Note that geometries can become
858 quite large. (Default: none)
859 geometry_simplification (float): Simplification factor to use on
860 the geometries before returning them. The factor expresses
861 the tolerance in degrees from which the geometry may differ.
862 Topology is preserved. (Default: 0.0)
863 address_details (bool): Add detailed information about the places
864 that make up the address of the requested object. (Default: False)
865 linked_places (bool): Add detailed information about the places
866 that link to the result. (Default: False)
867 parented_places (bool): Add detailed information about all places
868 for which the requested object is a parent, i.e. all places for
869 which the object provides the address details.
870 Only POI places can have parents. (Default: False)
871 keywords (bool): Add detailed information about the search terms
875 source_table (enum): Data source of the place. See below for possible values.
876 category (tuple): A tuple of two strings with the primary OSM tag
878 centroid (Point): Point position of the place.
879 place_id (Optional[int]): Internal ID of the place. This ID may differ
880 for the same place between different installations.
881 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
882 names (Optional[dict]): Dictionary of names of the place. Keys are
883 usually the corresponding OSM tag keys.
884 address (Optional[dict]): Dictionary of address parts directly
885 attributed to the place. Keys are usually the corresponding
886 OSM tag keys with the `addr:` prefix removed.
887 extratags (Optional[dict]): Dictionary of additional attributes for
888 the place. Usually OSM tag keys and values.
889 housenumber (Optional[str]): House number of the place, normalised
890 for lookup. To get the house number in its original spelling,
891 use `address['housenumber']`.
892 postcode (Optional[str]): Computed postcode for the place. To get
893 directly attributed postcodes, use `address['postcode']` instead.
894 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
895 The string has the format <language code>:<wikipedia title>.
896 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
897 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
898 importance (Optional[float]): Relative importance of the place. This is a measure
899 how likely the place will be searched for.
900 country_code (Optional[str]): Country the feature is in as
901 ISO 3166-1 alpha-2 country code.
902 address_rows (Optional[AddressLines]): List of places that make up the
903 computed address. `None` when `address_details` parameter was False.
904 linked_rows (Optional[AddressLines]): List of places that link to the object.
905 `None` when `linked_places` parameter was False.
906 parented_rows (Optional[AddressLines]): List of direct children of the place.
907 `None` when `parented_places` parameter was False.
908 name_keywords (Optional[WordInfos]): List of search words for the name of
909 the place. `None` when `keywords` parameter is set to False.
910 address_keywords (Optional[WordInfos]): List of search word for the address of
911 the place. `None` when `keywords` parameter is set to False.
912 bbox (Bbox): Bounding box of the full geometry of the place.
913 If the place is a single point, then the size of the bounding
914 box is guessed according to the type of place.
915 geometry (dict): Dictionary containing the full geometry of the place
916 in the formats requested in the `geometry_output` parameter.
918 return self._loop.run_until_complete(
919 self._async_api.search_category(categories, near_query, **params))