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 PlaceRef below
377 for the various ways to reference a place.
380 geometry_output (enum): Add the full geometry of the place to the result.
381 Multiple formats may be selected. Note that geometries can become
382 quite large. (Default: none)
383 geometry_simplification (float): Simplification factor to use on
384 the geometries before returning them. The factor expresses
385 the tolerance in degrees from which the geometry may differ.
386 Topology is preserved. (Default: 0.0)
387 address_details (bool): Add detailed information about the places
388 that make up the address of the requested object. (Default: False)
389 linked_places (bool): Add detailed information about the places
390 that link to the result. (Default: False)
391 parented_places (bool): Add detailed information about all places
392 for which the requested object is a parent, i.e. all places for
393 which the object provides the address details.
394 Only POI places can have parents. (Default: False)
395 keywords (bool): Add detailed information about the search terms
399 source_table (enum): Data source of the place. See below for possible values.
400 category (tuple): A tuple of two strings with the primary OSM tag
402 centroid (Point): Point position of the place.
403 place_id (Optional[int]): Internal ID of the place. This ID may differ
404 for the same place between different installations.
405 parent_place_id (Optional(int]): Internal ID of the parent of this
406 place. Only meaning full for POI-like objects (places with a
408 linked_place_id (Optional[int]): Internal ID of the place this object
409 linkes to. When this ID is set then there is no guarantee that
410 the rest of the result information is complete.
411 admin_level (int): Value of the `admin_level` OSM tag. Only meaningful
412 for administrative boundary objects.
413 indexed_date (datetime): Timestamp when the place was last updated.
414 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
415 names (Optional[dict]): Dictionary of names of the place. Keys are
416 usually the corresponding OSM tag keys.
417 address (Optional[dict]): Dictionary of address parts directly
418 attributed to the place. Keys are usually the corresponding
419 OSM tag keys with the `addr:` prefix removed.
420 extratags (Optional[dict]): Dictionary of additional attributes for
421 the place. Usually OSM tag keys and values.
422 housenumber (Optional[str]): House number of the place, normalised
423 for lookup. To get the house number in its original spelling,
424 use `address['housenumber']`.
425 postcode (Optional[str]): Computed postcode for the place. To get
426 directly attributed postcodes, use `address['postcode']` instead.
427 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
428 The string has the format <language code>:<wikipedia title>.
429 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
430 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
431 importance (Optional[float]): Relative importance of the place. This is a measure
432 how likely the place will be searched for.
433 country_code (Optional[str]): Country the feature is in as
434 ISO 3166-1 alpha-2 country code.
435 address_rows (Optional[AddressLines]): List of places that make up the
436 computed address. `None` when `address_details` parameter was False.
437 linked_rows (Optional[AddressLines]): List of places that link to the object.
438 `None` when `linked_places` parameter was False.
439 parented_rows (Optional[AddressLines]): List of direct children of the place.
440 `None` when `parented_places` parameter was False.
441 name_keywords (Optional[WordInfos]): List of search words for the name of
442 the place. `None` when `keywords` parameter is set to False.
443 address_keywords (Optional[WordInfos]): List of search word for the address of
444 the place. `None` when `keywords` parameter is set to False.
445 geometry (dict): Dictionary containing the full geometry of the place
446 in the formats requested in the `geometry_output` parameter.
448 return self._loop.run_until_complete(self._async_api.details(place, **params))
451 def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
452 """ Get simple information about a list of places.
454 Returns a list of place information for all IDs that were found.
455 Each result is a dataclass with the fields detailed below.
458 places: List of descriptions of the place to look up. See PlaceRef below
459 for the various ways to reference a place.
462 geometry_output (enum): Add the full geometry of the place to the result.
463 Multiple formats may be selected. Note that geometries can become
464 quite large. (Default: none)
465 geometry_simplification (float): Simplification factor to use on
466 the geometries before returning them. The factor expresses
467 the tolerance in degrees from which the geometry may differ.
468 Topology is preserved. (Default: 0.0)
469 address_details (bool): Add detailed information about the places
470 that make up the address of the requested object. (Default: False)
471 linked_places (bool): Add detailed information about the places
472 that link to the result. (Default: False)
473 parented_places (bool): Add detailed information about all places
474 for which the requested object is a parent, i.e. all places for
475 which the object provides the address details.
476 Only POI places can have parents. (Default: False)
477 keywords (bool): Add detailed information about the search terms
481 source_table (enum): Data source of the place. See below for possible values.
482 category (tuple): A tuple of two strings with the primary OSM tag
484 centroid (Point): Point position of the place.
485 place_id (Optional[int]): Internal ID of the place. This ID may differ
486 for the same place between different installations.
487 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
488 names (Optional[dict]): Dictionary of names of the place. Keys are
489 usually the corresponding OSM tag keys.
490 address (Optional[dict]): Dictionary of address parts directly
491 attributed to the place. Keys are usually the corresponding
492 OSM tag keys with the `addr:` prefix removed.
493 extratags (Optional[dict]): Dictionary of additional attributes for
494 the place. Usually OSM tag keys and values.
495 housenumber (Optional[str]): House number of the place, normalised
496 for lookup. To get the house number in its original spelling,
497 use `address['housenumber']`.
498 postcode (Optional[str]): Computed postcode for the place. To get
499 directly attributed postcodes, use `address['postcode']` instead.
500 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
501 The string has the format <language code>:<wikipedia title>.
502 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
503 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
504 importance (Optional[float]): Relative importance of the place. This is a measure
505 how likely the place will be searched for.
506 country_code (Optional[str]): Country the feature is in as
507 ISO 3166-1 alpha-2 country code.
508 address_rows (Optional[AddressLines]): List of places that make up the
509 computed address. `None` when `address_details` parameter was False.
510 linked_rows (Optional[AddressLines]): List of places that link to the object.
511 `None` when `linked_places` parameter was False.
512 parented_rows (Optional[AddressLines]): List of direct children of the place.
513 `None` when `parented_places` parameter was False.
514 name_keywords (Optional[WordInfos]): List of search words for the name of
515 the place. `None` when `keywords` parameter is set to False.
516 address_keywords (Optional[WordInfos]): List of search word for the address of
517 the place. `None` when `keywords` parameter is set to False.
518 bbox (Bbox): Bounding box of the full geometry of the place.
519 If the place is a single point, then the size of the bounding
520 box is guessed according to the type of place.
521 geometry (dict): Dictionary containing the full geometry of the place
522 in the formats requested in the `geometry_output` parameter.
524 return self._loop.run_until_complete(self._async_api.lookup(places, **params))
527 def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
528 """ Find a place by its coordinates. Also known as reverse geocoding.
530 Returns the closest result that can be found or `None` if
531 no place matches the given criteria. The result is a dataclass
532 with the fields as detailed below.
535 coord: Coordinate to lookup the place for as a Point
536 or a tuple (x, y). Must be in WGS84 projection.
539 max_rank (int): Highest address rank to return. Can be used to
540 restrict search to streets or settlements.
541 layers (enum): Defines the kind of data to take into account.
542 See description of layers below. (Default: addresses and POIs)
543 geometry_output (enum): Add the full geometry of the place to the result.
544 Multiple formats may be selected. Note that geometries can become
545 quite large. (Default: none)
546 geometry_simplification (float): Simplification factor to use on
547 the geometries before returning them. The factor expresses
548 the tolerance in degrees from which the geometry may differ.
549 Topology is preserved. (Default: 0.0)
550 address_details (bool): Add detailed information about the places
551 that make up the address of the requested object. (Default: False)
552 linked_places (bool): Add detailed information about the places
553 that link to the result. (Default: False)
554 parented_places (bool): Add detailed information about all places
555 for which the requested object is a parent, i.e. all places for
556 which the object provides the address details.
557 Only POI places can have parents. (Default: False)
558 keywords (bool): Add detailed information about the search terms
562 source_table (enum): Data source of the place. See below for possible values.
563 category (tuple): A tuple of two strings with the primary OSM tag
565 centroid (Point): Point position of the place.
566 place_id (Optional[int]): Internal ID of the place. This ID may differ
567 for the same place between different installations.
568 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
569 names (Optional[dict]): Dictionary of names of the place. Keys are
570 usually the corresponding OSM tag keys.
571 address (Optional[dict]): Dictionary of address parts directly
572 attributed to the place. Keys are usually the corresponding
573 OSM tag keys with the `addr:` prefix removed.
574 extratags (Optional[dict]): Dictionary of additional attributes for
575 the place. Usually OSM tag keys and values.
576 housenumber (Optional[str]): House number of the place, normalised
577 for lookup. To get the house number in its original spelling,
578 use `address['housenumber']`.
579 postcode (Optional[str]): Computed postcode for the place. To get
580 directly attributed postcodes, use `address['postcode']` instead.
581 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
582 The string has the format <language code>:<wikipedia title>.
583 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
584 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
585 importance (Optional[float]): Relative importance of the place. This is a measure
586 how likely the place will be searched for.
587 country_code (Optional[str]): Country the feature is in as
588 ISO 3166-1 alpha-2 country code.
589 address_rows (Optional[AddressLines]): List of places that make up the
590 computed address. `None` when `address_details` parameter was False.
591 linked_rows (Optional[AddressLines]): List of places that link to the object.
592 `None` when `linked_places` parameter was False.
593 parented_rows (Optional[AddressLines]): List of direct children of the place.
594 `None` when `parented_places` parameter was False.
595 name_keywords (Optional[WordInfos]): List of search words for the name of
596 the place. `None` when `keywords` parameter is set to False.
597 address_keywords (Optional[WordInfos]): List of search word for the address of
598 the place. `None` when `keywords` parameter is set to False.
599 bbox (Bbox): Bounding box of the full geometry of the place.
600 If the place is a single point, then the size of the bounding
601 box is guessed according to the type of place.
602 geometry (dict): Dictionary containing the full geometry of the place
603 in the formats requested in the `geometry_output` parameter.
604 distance (Optional[float]): Distance in degree from the input point.
606 return self._loop.run_until_complete(self._async_api.reverse(coord, **params))
609 def search(self, query: str, **params: Any) -> SearchResults:
610 """ Find a place by free-text search. Also known as forward geocoding.
613 query: Free-form text query searching for a place.
616 max_results (int): Maximum number of results to return. The
617 actual number of results may be less. (Default: 10)
618 min_rank (int): Lowest [address rank](../customize/Ranking.md#address-rank) to return.
619 max_rank (int): Highest address rank to return.
620 layers (enum): Defines the kind of data to take into account.
621 See description of layers below. (Default: addresses and POIs)
622 countries (list[str]): Restrict search to countries with the given
623 ISO 3166-1 alpha-2 country code. An empty list (the default)
624 disables this filter.
625 excluded (list[int]): A list of internal IDs of places to exclude
627 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
628 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
629 as a filter and return only results within the bounding box.
630 near (Optional[Point]): Focus search around the given point and
631 return results ordered by distance to the given point.
632 near_radius (Optional[float]): Restrict results to results within
633 the given distance in degrees of `near` point. Ignored, when
635 categories (list[tuple]): Restrict search to places of the given
636 categories. The category is the main OSM tag assigned to each
637 place. An empty list (the default) disables this filter.
638 geometry_output (enum): Add the full geometry of the place to the result.
639 Multiple formats may be selected. Note that geometries can become
640 quite large. (Default: none)
641 geometry_simplification (float): Simplification factor to use on
642 the geometries before returning them. The factor expresses
643 the tolerance in degrees from which the geometry may differ.
644 Topology is preserved. (Default: 0.0)
645 address_details (bool): Add detailed information about the places
646 that make up the address of the requested object. (Default: False)
647 linked_places (bool): Add detailed information about the places
648 that link to the result. (Default: False)
649 parented_places (bool): Add detailed information about all places
650 for which the requested object is a parent, i.e. all places for
651 which the object provides the address details.
652 Only POI places can have parents. (Default: False)
653 keywords (bool): Add detailed information about the search terms
657 source_table (enum): Data source of the place. See below for possible values.
658 category (tuple): A tuple of two strings with the primary OSM tag
660 centroid (Point): Point position of the place.
661 place_id (Optional[int]): Internal ID of the place. This ID may differ
662 for the same place between different installations.
663 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
664 names (Optional[dict]): Dictionary of names of the place. Keys are
665 usually the corresponding OSM tag keys.
666 address (Optional[dict]): Dictionary of address parts directly
667 attributed to the place. Keys are usually the corresponding
668 OSM tag keys with the `addr:` prefix removed.
669 extratags (Optional[dict]): Dictionary of additional attributes for
670 the place. Usually OSM tag keys and values.
671 housenumber (Optional[str]): House number of the place, normalised
672 for lookup. To get the house number in its original spelling,
673 use `address['housenumber']`.
674 postcode (Optional[str]): Computed postcode for the place. To get
675 directly attributed postcodes, use `address['postcode']` instead.
676 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
677 The string has the format <language code>:<wikipedia title>.
678 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
679 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
680 importance (Optional[float]): Relative importance of the place. This is a measure
681 how likely the place will be searched for.
682 country_code (Optional[str]): Country the feature is in as
683 ISO 3166-1 alpha-2 country code.
684 address_rows (Optional[AddressLines]): List of places that make up the
685 computed address. `None` when `address_details` parameter was False.
686 linked_rows (Optional[AddressLines]): List of places that link to the object.
687 `None` when `linked_places` parameter was False.
688 parented_rows (Optional[AddressLines]): List of direct children of the place.
689 `None` when `parented_places` parameter was False.
690 name_keywords (Optional[WordInfos]): List of search words for the name of
691 the place. `None` when `keywords` parameter is set to False.
692 address_keywords (Optional[WordInfos]): List of search word for the address of
693 the place. `None` when `keywords` parameter is set to False.
694 bbox (Bbox): Bounding box of the full geometry of the place.
695 If the place is a single point, then the size of the bounding
696 box is guessed according to the type of place.
697 geometry (dict): Dictionary containing the full geometry of the place
698 in the formats requested in the `geometry_output` parameter.
700 return self._loop.run_until_complete(
701 self._async_api.search(query, **params))
704 # pylint: disable=too-many-arguments
705 def search_address(self, amenity: Optional[str] = None,
706 street: Optional[str] = None,
707 city: Optional[str] = None,
708 county: Optional[str] = None,
709 state: Optional[str] = None,
710 country: Optional[str] = None,
711 postalcode: Optional[str] = None,
712 **params: Any) -> SearchResults:
713 """ Find an address using structured search.
716 amenity: Name of a POI.
717 street: Street and optionally housenumber of the address. If the address
718 does not have a street, then the place the housenumber references to.
719 city: Postal city of the address.
720 county: County equivalent of the address. Does not exist in all
722 state: State or province of the address.
723 country: Country with its full name or its ISO 3166-1 alpha-2 country code.
724 Do not use together with the country_code filter.
725 postalcode: Post code or ZIP for the place.
728 max_results (int): Maximum number of results to return. The
729 actual number of results may be less. (Default: 10)
730 min_rank (int): Lowest [address rank](../customize/Ranking.md#address-rank) to return.
731 max_rank (int): Highest address rank to return.
732 layers (enum): Defines the kind of data to take into account.
733 See description of layers below. (Default: addresses and POIs)
734 countries (list[str]): Restrict search to countries with the given
735 ISO 3166-1 alpha-2 country code. An empty list (the default)
736 disables this filter. Do not use, when the country parameter
738 excluded (list[int]): A list of internal IDs of places to exclude
740 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
741 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
742 as a filter and return only results within the bounding box.
743 near (Optional[Point]): Focus search around the given point and
744 return results ordered by distance to the given point.
745 near_radius (Optional[float]): Restrict results to results within
746 the given distance in degrees of `near` point. Ignored, when
748 categories (list[tuple]): Restrict search to places of the given
749 categories. The category is the main OSM tag assigned to each
750 place. An empty list (the default) disables this filter.
751 geometry_output (enum): Add the full geometry of the place to the result.
752 Multiple formats may be selected. Note that geometries can become
753 quite large. (Default: none)
754 geometry_simplification (float): Simplification factor to use on
755 the geometries before returning them. The factor expresses
756 the tolerance in degrees from which the geometry may differ.
757 Topology is preserved. (Default: 0.0)
758 address_details (bool): Add detailed information about the places
759 that make up the address of the requested object. (Default: False)
760 linked_places (bool): Add detailed information about the places
761 that link to the result. (Default: False)
762 parented_places (bool): Add detailed information about all places
763 for which the requested object is a parent, i.e. all places for
764 which the object provides the address details.
765 Only POI places can have parents. (Default: False)
766 keywords (bool): Add detailed information about the search terms
770 source_table (enum): Data source of the place. See below for possible values.
771 category (tuple): A tuple of two strings with the primary OSM tag
773 centroid (Point): Point position of the place.
774 place_id (Optional[int]): Internal ID of the place. This ID may differ
775 for the same place between different installations.
776 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
777 names (Optional[dict]): Dictionary of names of the place. Keys are
778 usually the corresponding OSM tag keys.
779 address (Optional[dict]): Dictionary of address parts directly
780 attributed to the place. Keys are usually the corresponding
781 OSM tag keys with the `addr:` prefix removed.
782 extratags (Optional[dict]): Dictionary of additional attributes for
783 the place. Usually OSM tag keys and values.
784 housenumber (Optional[str]): House number of the place, normalised
785 for lookup. To get the house number in its original spelling,
786 use `address['housenumber']`.
787 postcode (Optional[str]): Computed postcode for the place. To get
788 directly attributed postcodes, use `address['postcode']` instead.
789 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
790 The string has the format <language code>:<wikipedia title>.
791 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
792 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
793 importance (Optional[float]): Relative importance of the place. This is a measure
794 how likely the place will be searched for.
795 country_code (Optional[str]): Country the feature is in as
796 ISO 3166-1 alpha-2 country code.
797 address_rows (Optional[AddressLines]): List of places that make up the
798 computed address. `None` when `address_details` parameter was False.
799 linked_rows (Optional[AddressLines]): List of places that link to the object.
800 `None` when `linked_places` parameter was False.
801 parented_rows (Optional[AddressLines]): List of direct children of the place.
802 `None` when `parented_places` parameter was False.
803 name_keywords (Optional[WordInfos]): List of search words for the name of
804 the place. `None` when `keywords` parameter is set to False.
805 address_keywords (Optional[WordInfos]): List of search word for the address of
806 the place. `None` when `keywords` parameter is set to False.
807 bbox (Bbox): Bounding box of the full geometry of the place.
808 If the place is a single point, then the size of the bounding
809 box is guessed according to the type of place.
810 geometry (dict): Dictionary containing the full geometry of the place
811 in the formats requested in the `geometry_output` parameter.
813 return self._loop.run_until_complete(
814 self._async_api.search_address(amenity, street, city, county,
815 state, country, postalcode, **params))
818 def search_category(self, categories: List[Tuple[str, str]],
819 near_query: Optional[str] = None,
820 **params: Any) -> SearchResults:
821 """ Find an object of a certain category near another place.
823 The near place may either be given as an unstructured search
824 query in itself or as a geographic area through the
825 viewbox or near parameters.
828 categories: Restrict search to places of the given
829 categories. The category is the main OSM tag assigned to each
831 near_query: Optional free-text query to define the are to
835 max_results (int): Maximum number of results to return. The
836 actual number of results may be less. (Default: 10)
837 min_rank (int): Lowest [address rank](../customize/Ranking.md#address-rank) to return.
838 max_rank (int): Highest address rank to return.
839 layers (enum): Defines the kind of data to take into account.
840 See description of layers below. (Default: addresses and POIs)
841 countries (list[str]): Restrict search to countries with the given
842 ISO 3166-1 alpha-2 country code. An empty list (the default)
843 disables this filter.
844 excluded (list[int]): A list of internal IDs of places to exclude
846 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
847 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
848 as a filter and return only results within the bounding box.
849 near (Optional[Point]): Focus search around the given point and
850 return results ordered by distance to the given point.
851 near_radius (Optional[float]): Restrict results to results within
852 the given distance in degrees of `near` point. Ignored, when
854 geometry_output (enum): Add the full geometry of the place to the result.
855 Multiple formats may be selected. Note that geometries can become
856 quite large. (Default: none)
857 geometry_simplification (float): Simplification factor to use on
858 the geometries before returning them. The factor expresses
859 the tolerance in degrees from which the geometry may differ.
860 Topology is preserved. (Default: 0.0)
861 address_details (bool): Add detailed information about the places
862 that make up the address of the requested object. (Default: False)
863 linked_places (bool): Add detailed information about the places
864 that link to the result. (Default: False)
865 parented_places (bool): Add detailed information about all places
866 for which the requested object is a parent, i.e. all places for
867 which the object provides the address details.
868 Only POI places can have parents. (Default: False)
869 keywords (bool): Add detailed information about the search terms
873 source_table (enum): Data source of the place. See below for possible values.
874 category (tuple): A tuple of two strings with the primary OSM tag
876 centroid (Point): Point position of the place.
877 place_id (Optional[int]): Internal ID of the place. This ID may differ
878 for the same place between different installations.
879 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
880 names (Optional[dict]): Dictionary of names of the place. Keys are
881 usually the corresponding OSM tag keys.
882 address (Optional[dict]): Dictionary of address parts directly
883 attributed to the place. Keys are usually the corresponding
884 OSM tag keys with the `addr:` prefix removed.
885 extratags (Optional[dict]): Dictionary of additional attributes for
886 the place. Usually OSM tag keys and values.
887 housenumber (Optional[str]): House number of the place, normalised
888 for lookup. To get the house number in its original spelling,
889 use `address['housenumber']`.
890 postcode (Optional[str]): Computed postcode for the place. To get
891 directly attributed postcodes, use `address['postcode']` instead.
892 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
893 The string has the format <language code>:<wikipedia title>.
894 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
895 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
896 importance (Optional[float]): Relative importance of the place. This is a measure
897 how likely the place will be searched for.
898 country_code (Optional[str]): Country the feature is in as
899 ISO 3166-1 alpha-2 country code.
900 address_rows (Optional[AddressLines]): List of places that make up the
901 computed address. `None` when `address_details` parameter was False.
902 linked_rows (Optional[AddressLines]): List of places that link to the object.
903 `None` when `linked_places` parameter was False.
904 parented_rows (Optional[AddressLines]): List of direct children of the place.
905 `None` when `parented_places` parameter was False.
906 name_keywords (Optional[WordInfos]): List of search words for the name of
907 the place. `None` when `keywords` parameter is set to False.
908 address_keywords (Optional[WordInfos]): List of search word for the address of
909 the place. `None` when `keywords` parameter is set to False.
910 bbox (Bbox): Bounding box of the full geometry of the place.
911 If the place is a single point, then the size of the bounding
912 box is guessed according to the type of place.
913 geometry (dict): Dictionary containing the full geometry of the place
914 in the formats requested in the `geometry_output` parameter.
916 return self._loop.run_until_complete(
917 self._async_api.search_category(categories, near_query, **params))