]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/api/core.py
enable search for sqlite conversion by default
[nominatim.git] / nominatim / api / core.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Implementation of classes for API access via libraries.
9 """
10 from typing import Mapping, Optional, Any, AsyncIterator, Dict, Sequence, List, Tuple
11 import asyncio
12 import sys
13 import contextlib
14 from pathlib import Path
15
16 import sqlalchemy as sa
17 import sqlalchemy.ext.asyncio as sa_asyncio
18
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
31
32
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.
37
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.
41     """
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.
46
47             Parameters:
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.
58         """
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
64
65         if sys.version_info >= (3, 10):
66             self._engine_lock = asyncio.Lock()
67         else:
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}
72
73
74     async def setup_database(self) -> None:
75         """ Set up the SQL engine and connections.
76
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.
80         """
81         async with self._engine_lock:
82             if self._engine:
83                 return
84
85             extra_args: Dict[str, Any] = {'future': True,
86                                           'echo': self.config.get_bool('DEBUG_SQL')}
87
88             if self.config.get_int('API_POOL_SIZE') == 0:
89                 extra_args['poolclass'] = sa.pool.NullPool
90             else:
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')
94
95
96             is_sqlite = self.config.DATABASE_DSN.startswith('sqlite:')
97
98             if is_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'))
103
104             else:
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')}
108
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,
116                            query=query)
117
118             engine = sa_asyncio.create_async_engine(dburl, **extra_args)
119
120             if is_sqlite:
121                 server_version = 0
122
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))
131             else:
132                 try:
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):
137                     server_version = 0
138
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()
147
148             self._property_cache['DB:server_version'] = server_version
149
150             self._tables = SearchTables(sa.MetaData()) # pylint: disable=no-member
151             self._engine = engine
152
153
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.
158         """
159         if self._engine is not None:
160             await self._engine.dispose()
161
162
163     @contextlib.asynccontextmanager
164     async def begin(self) -> AsyncIterator[SearchConnection]:
165         """ Create a new connection with automatic transaction handling.
166
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.
170         """
171         if self._engine is None:
172             await self.setup_database()
173
174         assert self._engine is not None
175         assert self._tables is not None
176
177         async with self._engine.begin() as conn:
178             yield SearchConnection(conn, self._tables, self._property_cache)
179
180
181     async def status(self) -> StatusResult:
182         """ Return the status of the database.
183         """
184         try:
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')
190
191         return status
192
193
194     async def details(self, place: ntyp.PlaceRef, **params: Any) -> Optional[DetailedResult]:
195         """ Get detailed information about a place in the database.
196
197             Returns None if there is no entry under the given ID.
198         """
199         details = ntyp.LookupDetails.from_kwargs(params)
200         async with self.begin() as conn:
201             conn.set_query_timeout(self.query_timeout)
202             if details.keywords:
203                 await make_query_analyzer(conn)
204             return await get_detailed_place(conn, place, details)
205
206
207     async def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
208         """ Get simple information about a list of places.
209
210             Returns a list of place information for all IDs that were found.
211         """
212         details = ntyp.LookupDetails.from_kwargs(params)
213         async with self.begin() as conn:
214             conn.set_query_timeout(self.query_timeout)
215             if details.keywords:
216                 await make_query_analyzer(conn)
217             return SearchResults(filter(None,
218                                         [await get_simple_place(conn, p, details) for p in places]))
219
220
221     async def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
222         """ Find a place by its coordinates. Also known as reverse geocoding.
223
224             Returns the closest result that can be found or None if
225             no place matches the given criteria.
226         """
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.
230             return None
231
232         details = ntyp.ReverseDetails.from_kwargs(params)
233         async with self.begin() as conn:
234             conn.set_query_timeout(self.query_timeout)
235             if details.keywords:
236                 await make_query_analyzer(conn)
237             geocoder = ReverseGeocoder(conn, details,
238                                        self.reverse_restrict_to_country_area)
239             return await geocoder.lookup(coord)
240
241
242     async def search(self, query: str, **params: Any) -> SearchResults:
243         """ Find a place by free-text search. Also known as forward geocoding.
244         """
245         query = query.strip()
246         if not query:
247             raise UsageError('Nothing to search for.')
248
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)
256
257
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.
268         """
269         async with self.begin() as conn:
270             conn.set_query_timeout(self.query_timeout)
271             details = ntyp.SearchDetails.from_kwargs(params)
272
273             phrases: List[Phrase] = []
274
275             if amenity:
276                 phrases.append(Phrase(PhraseType.AMENITY, amenity))
277             if street:
278                 phrases.append(Phrase(PhraseType.STREET, street))
279             if city:
280                 phrases.append(Phrase(PhraseType.CITY, city))
281             if county:
282                 phrases.append(Phrase(PhraseType.COUNTY, county))
283             if state:
284                 phrases.append(Phrase(PhraseType.STATE, state))
285             if postalcode:
286                 phrases.append(Phrase(PhraseType.POSTCODE, postalcode))
287             if country:
288                 phrases.append(Phrase(PhraseType.COUNTRY, country))
289
290             if not phrases:
291                 raise UsageError('Nothing to search for.')
292
293             if amenity or street:
294                 details.restrict_min_max_rank(26, 30)
295             elif city:
296                 details.restrict_min_max_rank(13, 25)
297             elif county:
298                 details.restrict_min_max_rank(10, 12)
299             elif state:
300                 details.restrict_min_max_rank(5, 9)
301             elif postalcode:
302                 details.restrict_min_max_rank(5, 11)
303             else:
304                 details.restrict_min_max_rank(4, 4)
305
306             if 'layers' not in params:
307                 details.layers = ntyp.DataLayer.ADDRESS
308                 if amenity:
309                     details.layers |= ntyp.DataLayer.POI
310
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)
315
316
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.
323         """
324         if not categories:
325             return SearchResults()
326
327         details = ntyp.SearchDetails.from_kwargs(params)
328         async with self.begin() as conn:
329             conn.set_query_timeout(self.query_timeout)
330             if near_query:
331                 phrases = [Phrase(PhraseType.NONE, p) for p in near_query.split(',')]
332             else:
333                 phrases = []
334                 if details.keywords:
335                     await make_query_analyzer(conn)
336
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)
341
342
343
344 class NominatimAPI:
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.
348     """
349
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.
353
354             Parameters:
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.
362         """
363         self._loop = asyncio.new_event_loop()
364         self._async_api = NominatimAPIAsync(project_dir, environ, loop=self._loop)
365
366
367     def close(self) -> None:
368         """ Close all active connections to the database.
369
370             This function also closes the asynchronous worker loop making
371             the NominatimAPI object unusuable.
372         """
373         self._loop.run_until_complete(self._async_api.close())
374         self._loop.close()
375
376
377     @property
378     def config(self) -> Configuration:
379         """ Provide read-only access to the [configuration](#Configuration)
380             used by the API.
381         """
382         return self._async_api.config
383
384     def status(self) -> StatusResult:
385         """ Return the status of the database as a dataclass object
386             with the fields described below.
387
388             Returns:
389               status(int): A status code as described on the status page.
390               message(str): Either 'OK' or a human-readable message of the
391                   problem encountered.
392               software_version(tuple): A tuple with the version of the
393                   Nominatim library consisting of (major, minor, patch, db-patch)
394                   version.
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.
399         """
400         return self._loop.run_until_complete(self._async_api.status())
401
402
403     def details(self, place: ntyp.PlaceRef, **params: Any) -> Optional[DetailedResult]:
404         """ Get detailed information about a place in the database.
405
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.
408
409             Parameters:
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.
413
414             Other parameters:
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
431                 used for this place.
432
433             Returns:
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
436                   and value.
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
442                   rank_address of 30).
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.
482         """
483         return self._loop.run_until_complete(self._async_api.details(place, **params))
484
485
486     def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
487         """ Get simple information about a list of places.
488
489             Returns a list of place information for all IDs that were found.
490             Each result is a dataclass with the fields detailed below.
491
492             Parameters:
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.
496
497             Other parameters:
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
514                 used for this place.
515
516             Returns:
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
519                   and value.
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.
559         """
560         return self._loop.run_until_complete(self._async_api.lookup(places, **params))
561
562
563     def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
564         """ Find a place by its coordinates. Also known as reverse geocoding.
565
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.
569
570             Parameters:
571               coord: Coordinate to lookup the place for as a Point
572                      or a tuple (x, y). Must be in WGS84 projection.
573
574             Other parameters:
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
595                 used for this place.
596
597             Returns:
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
600                   and value.
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.
641         """
642         return self._loop.run_until_complete(self._async_api.reverse(coord, **params))
643
644
645     def search(self, query: str, **params: Any) -> SearchResults:
646         """ Find a place by free-text search. Also known as forward geocoding.
647
648             Parameters:
649               query: Free-form text query searching for a place.
650
651             Other parameters:
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)
658                 is used.
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
667                 from the search.
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
675                 `near` is not set.
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
695                 used for this place.
696
697             Returns:
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
700                   and value.
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.
740         """
741         return self._loop.run_until_complete(
742                    self._async_api.search(query, **params))
743
744
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.
755
756             Parameters:
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
762                 jurisdictions.
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.
767
768             Other parameters:
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)
775                 is used.
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
783                 is used.
784               excluded (list[int]): A list of internal IDs of places to exclude
785                 from the search.
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
793                 `near` is not set.
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
813                 used for this place.
814
815             Returns:
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
818                   and value.
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.
858         """
859         return self._loop.run_until_complete(
860                    self._async_api.search_address(amenity, street, city, county,
861                                                   state, country, postalcode, **params))
862
863
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.
868
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.
872
873             Parameters:
874               categories: Restrict search to places of the given
875                 categories. The category is the main OSM tag assigned to each
876                 place.
877               near_query: Optional free-text query to define the are to
878                 restrict search to.
879
880             Other parameters:
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)
887                 is used.
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
896                 from the search.
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
904                 `near` is not set.
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
921                 used for this place.
922
923             Returns:
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
926                   and value.
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.
966         """
967         return self._loop.run_until_complete(
968                    self._async_api.search_category(categories, near_query, **params))