stac-fastapi-opensearch 4.2.0__py3-none-any.whl → 5.0.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,14 +11,12 @@ from stac_fastapi.api.models import create_get_request_model, create_post_reques
11
11
  from stac_fastapi.core.core import (
12
12
  BulkTransactionsClient,
13
13
  CoreClient,
14
- EsAsyncBaseFiltersClient,
15
14
  TransactionsClient,
16
15
  )
17
16
  from stac_fastapi.core.extensions import QueryExtension
18
17
  from stac_fastapi.core.extensions.aggregation import (
19
18
  EsAggregationExtensionGetRequest,
20
19
  EsAggregationExtensionPostRequest,
21
- EsAsyncAggregationClient,
22
20
  )
23
21
  from stac_fastapi.core.extensions.fields import FieldsExtension
24
22
  from stac_fastapi.core.rate_limit import setup_rate_limit
@@ -40,6 +38,8 @@ from stac_fastapi.opensearch.database_logic import (
40
38
  create_collection_index,
41
39
  create_index_templates,
42
40
  )
41
+ from stac_fastapi.sfeos_helpers.aggregation import EsAsyncBaseAggregationClient
42
+ from stac_fastapi.sfeos_helpers.filter import EsAsyncBaseFiltersClient
43
43
 
44
44
  logging.basicConfig(level=logging.INFO)
45
45
  logger = logging.getLogger(__name__)
@@ -60,7 +60,7 @@ filter_extension.conformance_classes.append(
60
60
  )
61
61
 
62
62
  aggregation_extension = AggregationExtension(
63
- client=EsAsyncAggregationClient(
63
+ client=EsAsyncBaseAggregationClient(
64
64
  database=database_logic, session=session, settings=settings
65
65
  )
66
66
  )
@@ -107,7 +107,7 @@ post_request_model = create_post_request_model(search_extensions)
107
107
  api = StacApi(
108
108
  title=os.getenv("STAC_FASTAPI_TITLE", "stac-fastapi-opensearch"),
109
109
  description=os.getenv("STAC_FASTAPI_DESCRIPTION", "stac-fastapi-opensearch"),
110
- api_version=os.getenv("STAC_FASTAPI_VERSION", "4.2.0"),
110
+ api_version=os.getenv("STAC_FASTAPI_VERSION", "5.0.0a1"),
111
111
  settings=settings,
112
112
  extensions=extensions,
113
113
  client=CoreClient(
@@ -8,7 +8,8 @@ import certifi
8
8
  from opensearchpy import AsyncOpenSearch, OpenSearch
9
9
 
10
10
  from stac_fastapi.core.base_settings import ApiBaseSettings
11
- from stac_fastapi.core.utilities import get_bool_env, validate_refresh
11
+ from stac_fastapi.core.utilities import get_bool_env
12
+ from stac_fastapi.sfeos_helpers.database import validate_refresh
12
13
  from stac_fastapi.types.config import ApiSettings
13
14
 
14
15
 
@@ -39,18 +40,6 @@ def _es_config() -> Dict[str, Any]:
39
40
  if http_compress:
40
41
  config["http_compress"] = True
41
42
 
42
- # Explicitly exclude SSL settings when not using SSL
43
- if not use_ssl:
44
- return config
45
-
46
- # Include SSL settings if using https
47
- config["ssl_version"] = ssl.PROTOCOL_SSLv23
48
- config["verify_certs"] = get_bool_env("ES_VERIFY_CERTS", default=True)
49
-
50
- # Include CA Certificates if verifying certs
51
- if config["verify_certs"]:
52
- config["ca_certs"] = os.getenv("CURL_CA_BUNDLE", certifi.where())
53
-
54
43
  # Handle authentication
55
44
  if (u := os.getenv("ES_USER")) and (p := os.getenv("ES_PASS")):
56
45
  config["http_auth"] = (u, p)
@@ -64,6 +53,18 @@ def _es_config() -> Dict[str, Any]:
64
53
 
65
54
  config["headers"] = headers
66
55
 
56
+ # Explicitly exclude SSL settings when not using SSL
57
+ if not use_ssl:
58
+ return config
59
+
60
+ # Include SSL settings if using https
61
+ config["ssl_version"] = ssl.PROTOCOL_SSLv23
62
+ config["verify_certs"] = get_bool_env("ES_VERIFY_CERTS", default=True)
63
+
64
+ # Include CA Certificates if verifying certs
65
+ if config["verify_certs"]:
66
+ config["ca_certs"] = os.getenv("CURL_CA_BUNDLE", certifi.where())
67
+
67
68
  return config
68
69
 
69
70
 
@@ -5,7 +5,7 @@ import json
5
5
  import logging
6
6
  from base64 import urlsafe_b64decode, urlsafe_b64encode
7
7
  from copy import deepcopy
8
- from typing import Any, Dict, Iterable, List, Optional, Tuple, Type
8
+ from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union
9
9
 
10
10
  import attr
11
11
  from opensearchpy import exceptions, helpers
@@ -14,7 +14,30 @@ from opensearchpy.helpers.search import Search
14
14
  from starlette.requests import Request
15
15
 
16
16
  from stac_fastapi.core.base_database_logic import BaseDatabaseLogic
17
- from stac_fastapi.core.database_logic import (
17
+ from stac_fastapi.core.serializers import CollectionSerializer, ItemSerializer
18
+ from stac_fastapi.core.utilities import MAX_LIMIT, bbox2polygon
19
+ from stac_fastapi.opensearch.config import (
20
+ AsyncOpensearchSettings as AsyncSearchSettings,
21
+ )
22
+ from stac_fastapi.opensearch.config import OpensearchSettings as SyncSearchSettings
23
+ from stac_fastapi.sfeos_helpers import filter
24
+ from stac_fastapi.sfeos_helpers.database import (
25
+ apply_free_text_filter_shared,
26
+ apply_intersects_filter_shared,
27
+ create_index_templates_shared,
28
+ delete_item_index_shared,
29
+ get_queryables_mapping_shared,
30
+ index_alias_by_collection_id,
31
+ index_by_collection_id,
32
+ indices,
33
+ mk_actions,
34
+ mk_item_id,
35
+ populate_sort_shared,
36
+ return_date,
37
+ validate_refresh,
38
+ )
39
+ from stac_fastapi.sfeos_helpers.mappings import (
40
+ AGGREGATION_MAPPING,
18
41
  COLLECTIONS_INDEX,
19
42
  DEFAULT_SORT,
20
43
  ES_COLLECTIONS_MAPPINGS,
@@ -23,20 +46,9 @@ from stac_fastapi.core.database_logic import (
23
46
  ITEM_INDICES,
24
47
  ITEMS_INDEX_PREFIX,
25
48
  Geometry,
26
- index_alias_by_collection_id,
27
- index_by_collection_id,
28
- indices,
29
- mk_actions,
30
- mk_item_id,
31
49
  )
32
- from stac_fastapi.core.extensions import filter
33
- from stac_fastapi.core.serializers import CollectionSerializer, ItemSerializer
34
- from stac_fastapi.core.utilities import MAX_LIMIT, bbox2polygon, validate_refresh
35
- from stac_fastapi.opensearch.config import (
36
- AsyncOpensearchSettings as AsyncSearchSettings,
37
- )
38
- from stac_fastapi.opensearch.config import OpensearchSettings as SyncSearchSettings
39
50
  from stac_fastapi.types.errors import ConflictError, NotFoundError
51
+ from stac_fastapi.types.rfc3339 import DateTimeType
40
52
  from stac_fastapi.types.stac import Collection, Item
41
53
 
42
54
  logger = logging.getLogger(__name__)
@@ -50,23 +62,7 @@ async def create_index_templates() -> None:
50
62
  None
51
63
 
52
64
  """
53
- client = AsyncSearchSettings().create_client
54
- await client.indices.put_template(
55
- name=f"template_{COLLECTIONS_INDEX}",
56
- body={
57
- "index_patterns": [f"{COLLECTIONS_INDEX}*"],
58
- "mappings": ES_COLLECTIONS_MAPPINGS,
59
- },
60
- )
61
- await client.indices.put_template(
62
- name=f"template_{ITEMS_INDEX_PREFIX}",
63
- body={
64
- "index_patterns": [f"{ITEMS_INDEX_PREFIX}*"],
65
- "settings": ES_ITEMS_SETTINGS,
66
- "mappings": ES_ITEMS_MAPPINGS,
67
- },
68
- )
69
- await client.close()
65
+ await create_index_templates_shared(settings=AsyncSearchSettings())
70
66
 
71
67
 
72
68
  async def create_collection_index() -> None:
@@ -125,18 +121,13 @@ async def delete_item_index(collection_id: str) -> None:
125
121
 
126
122
  Args:
127
123
  collection_id (str): The ID of the collection whose items index will be deleted.
128
- """
129
- client = AsyncSearchSettings().create_client
130
124
 
131
- name = index_alias_by_collection_id(collection_id)
132
- resolved = await client.indices.resolve_index(name=name)
133
- if "aliases" in resolved and resolved["aliases"]:
134
- [alias] = resolved["aliases"]
135
- await client.indices.delete_alias(index=alias["indices"], name=alias["name"])
136
- await client.indices.delete(index=alias["indices"])
137
- else:
138
- await client.indices.delete(index=name)
139
- await client.close()
125
+ Notes:
126
+ This function delegates to the shared implementation in delete_item_index_shared.
127
+ """
128
+ await delete_item_index_shared(
129
+ settings=AsyncSearchSettings(), collection_id=collection_id
130
+ )
140
131
 
141
132
 
142
133
  @attr.s
@@ -161,76 +152,7 @@ class DatabaseLogic(BaseDatabaseLogic):
161
152
 
162
153
  extensions: List[str] = attr.ib(default=attr.Factory(list))
163
154
 
164
- aggregation_mapping: Dict[str, Dict[str, Any]] = {
165
- "total_count": {"value_count": {"field": "id"}},
166
- "collection_frequency": {"terms": {"field": "collection", "size": 100}},
167
- "platform_frequency": {"terms": {"field": "properties.platform", "size": 100}},
168
- "cloud_cover_frequency": {
169
- "range": {
170
- "field": "properties.eo:cloud_cover",
171
- "ranges": [
172
- {"to": 5},
173
- {"from": 5, "to": 15},
174
- {"from": 15, "to": 40},
175
- {"from": 40},
176
- ],
177
- }
178
- },
179
- "datetime_frequency": {
180
- "date_histogram": {
181
- "field": "properties.datetime",
182
- "calendar_interval": "month",
183
- }
184
- },
185
- "datetime_min": {"min": {"field": "properties.datetime"}},
186
- "datetime_max": {"max": {"field": "properties.datetime"}},
187
- "grid_code_frequency": {
188
- "terms": {
189
- "field": "properties.grid:code",
190
- "missing": "none",
191
- "size": 10000,
192
- }
193
- },
194
- "sun_elevation_frequency": {
195
- "histogram": {"field": "properties.view:sun_elevation", "interval": 5}
196
- },
197
- "sun_azimuth_frequency": {
198
- "histogram": {"field": "properties.view:sun_azimuth", "interval": 5}
199
- },
200
- "off_nadir_frequency": {
201
- "histogram": {"field": "properties.view:off_nadir", "interval": 5}
202
- },
203
- "centroid_geohash_grid_frequency": {
204
- "geohash_grid": {
205
- "field": "properties.proj:centroid",
206
- "precision": 1,
207
- }
208
- },
209
- "centroid_geohex_grid_frequency": {
210
- "geohex_grid": {
211
- "field": "properties.proj:centroid",
212
- "precision": 0,
213
- }
214
- },
215
- "centroid_geotile_grid_frequency": {
216
- "geotile_grid": {
217
- "field": "properties.proj:centroid",
218
- "precision": 0,
219
- }
220
- },
221
- "geometry_geohash_grid_frequency": {
222
- "geohash_grid": {
223
- "field": "geometry",
224
- "precision": 1,
225
- }
226
- },
227
- "geometry_geotile_grid_frequency": {
228
- "geotile_grid": {
229
- "field": "geometry",
230
- "precision": 0,
231
- }
232
- },
233
- }
155
+ aggregation_mapping: Dict[str, Dict[str, Any]] = AGGREGATION_MAPPING
234
156
 
235
157
  """CORE LOGIC"""
236
158
 
@@ -317,23 +239,12 @@ class DatabaseLogic(BaseDatabaseLogic):
317
239
  Returns:
318
240
  dict: A dictionary containing the Queryables mappings.
319
241
  """
320
- queryables_mapping = {}
321
-
322
242
  mappings = await self.client.indices.get_mapping(
323
243
  index=f"{ITEMS_INDEX_PREFIX}{collection_id}",
324
244
  )
325
-
326
- for mapping in mappings.values():
327
- fields = mapping["mappings"].get("properties", {})
328
- properties = fields.pop("properties", {}).get("properties", {}).keys()
329
-
330
- for field_key in fields:
331
- queryables_mapping[field_key] = field_key
332
-
333
- for property_key in properties:
334
- queryables_mapping[property_key] = f"properties.{property_key}"
335
-
336
- return queryables_mapping
245
+ return await get_queryables_mapping_shared(
246
+ collection_id=collection_id, mappings=mappings
247
+ )
337
248
 
338
249
  @staticmethod
339
250
  def make_search():
@@ -352,27 +263,37 @@ class DatabaseLogic(BaseDatabaseLogic):
352
263
 
353
264
  @staticmethod
354
265
  def apply_free_text_filter(search: Search, free_text_queries: Optional[List[str]]):
355
- """Database logic to perform query for search endpoint."""
356
- if free_text_queries is not None:
357
- free_text_query_string = '" OR properties.\\*:"'.join(free_text_queries)
358
- search = search.query(
359
- "query_string", query=f'properties.\\*:"{free_text_query_string}"'
360
- )
266
+ """Create a free text query for OpenSearch queries.
361
267
 
362
- return search
268
+ This method delegates to the shared implementation in apply_free_text_filter_shared.
269
+
270
+ Args:
271
+ search (Search): The search object to apply the query to.
272
+ free_text_queries (Optional[List[str]]): A list of text strings to search for in the properties.
273
+
274
+ Returns:
275
+ Search: The search object with the free text query applied, or the original search
276
+ object if no free_text_queries were provided.
277
+ """
278
+ return apply_free_text_filter_shared(
279
+ search=search, free_text_queries=free_text_queries
280
+ )
363
281
 
364
282
  @staticmethod
365
- def apply_datetime_filter(search: Search, datetime_search):
283
+ def apply_datetime_filter(
284
+ search: Search, interval: Optional[Union[DateTimeType, str]]
285
+ ):
366
286
  """Apply a filter to search based on datetime field, start_datetime, and end_datetime fields.
367
287
 
368
288
  Args:
369
289
  search (Search): The search object to filter.
370
- datetime_search (dict): The datetime filter criteria.
290
+ interval: Optional[Union[DateTimeType, str]]
371
291
 
372
292
  Returns:
373
293
  Search: The filtered search object.
374
294
  """
375
295
  should = []
296
+ datetime_search = return_date(interval)
376
297
 
377
298
  # If the request is a single datetime return
378
299
  # items with datetimes equal to the requested datetime OR
@@ -525,21 +446,8 @@ class DatabaseLogic(BaseDatabaseLogic):
525
446
  Notes:
526
447
  A geo_shape filter is added to the search object, set to intersect with the specified geometry.
527
448
  """
528
- return search.filter(
529
- Q(
530
- {
531
- "geo_shape": {
532
- "geometry": {
533
- "shape": {
534
- "type": intersects.type.lower(),
535
- "coordinates": intersects.coordinates,
536
- },
537
- "relation": "intersects",
538
- }
539
- }
540
- }
541
- )
542
- )
449
+ filter = apply_intersects_filter_shared(intersects=intersects)
450
+ return search.filter(Q(filter))
543
451
 
544
452
  @staticmethod
545
453
  def apply_stacql_filter(search: Search, op: str, field: str, value: float):
@@ -592,11 +500,18 @@ class DatabaseLogic(BaseDatabaseLogic):
592
500
 
593
501
  @staticmethod
594
502
  def populate_sort(sortby: List) -> Optional[Dict[str, Dict[str, str]]]:
595
- """Database logic to sort search instance."""
596
- if sortby:
597
- return {s.field: {"order": s.direction} for s in sortby}
598
- else:
599
- return None
503
+ """Create a sort configuration for OpenSearch queries.
504
+
505
+ This method delegates to the shared implementation in populate_sort_shared.
506
+
507
+ Args:
508
+ sortby (List): A list of sort specifications, each containing a field and direction.
509
+
510
+ Returns:
511
+ Optional[Dict[str, Dict[str, str]]]: A dictionary mapping field names to sort direction
512
+ configurations, or None if no sort was specified.
513
+ """
514
+ return populate_sort_shared(sortby=sortby)
600
515
 
601
516
  async def execute_search(
602
517
  self,
@@ -1,2 +1,2 @@
1
1
  """library version."""
2
- __version__ = "4.2.0"
2
+ __version__ = "5.0.0a1"