11import os
2+ from functools import lru_cache
23from typing import Any , Dict , List , Optional , Protocol
34
45from stac_fastapi .types .stac import Item
@@ -14,6 +15,7 @@ class Geometry(Protocol): # noqa
1415
1516COLLECTIONS_INDEX = os .getenv ("STAC_COLLECTIONS_INDEX" , "collections" )
1617ITEMS_INDEX_PREFIX = os .getenv ("STAC_ITEMS_INDEX_PREFIX" , "items_" )
18+
1719ES_INDEX_NAME_UNSUPPORTED_CHARS = {
1820 "\\ " ,
1921 "/" ,
@@ -29,6 +31,10 @@ class Geometry(Protocol): # noqa
2931 ":" ,
3032}
3133
34+ _ES_INDEX_NAME_UNSUPPORTED_CHARS_TABLE = str .maketrans (
35+ "" , "" , "" .join (ES_INDEX_NAME_UNSUPPORTED_CHARS )
36+ )
37+
3238ITEM_INDICES = f"{ ITEMS_INDEX_PREFIX } *,-*kibana*,-{ COLLECTIONS_INDEX } *"
3339
3440DEFAULT_SORT = {
@@ -131,6 +137,7 @@ class Geometry(Protocol): # noqa
131137}
132138
133139
140+ @lru_cache (256 )
134141def index_by_collection_id (collection_id : str ) -> str :
135142 """
136143 Translate a collection id into an Elasticsearch index name.
@@ -141,9 +148,13 @@ def index_by_collection_id(collection_id: str) -> str:
141148 Returns:
142149 str: The index name derived from the collection id.
143150 """
144- return f"{ ITEMS_INDEX_PREFIX } { '' .join (c for c in collection_id .lower () if c not in ES_INDEX_NAME_UNSUPPORTED_CHARS )} _{ collection_id .encode ('utf-8' ).hex ()} "
151+ cleaned = collection_id .translate (_ES_INDEX_NAME_UNSUPPORTED_CHARS_TABLE )
152+ return (
153+ f"{ ITEMS_INDEX_PREFIX } { cleaned .lower ()} _{ collection_id .encode ('utf-8' ).hex ()} "
154+ )
145155
146156
157+ @lru_cache (256 )
147158def index_alias_by_collection_id (collection_id : str ) -> str :
148159 """
149160 Translate a collection id into an Elasticsearch index alias.
@@ -154,7 +165,8 @@ def index_alias_by_collection_id(collection_id: str) -> str:
154165 Returns:
155166 str: The index alias derived from the collection id.
156167 """
157- return f"{ ITEMS_INDEX_PREFIX } { '' .join (c for c in collection_id if c not in ES_INDEX_NAME_UNSUPPORTED_CHARS )} "
168+ cleaned = collection_id .translate (_ES_INDEX_NAME_UNSUPPORTED_CHARS_TABLE )
169+ return f"{ ITEMS_INDEX_PREFIX } { cleaned } "
158170
159171
160172def indices (collection_ids : Optional [List [str ]]) -> str :
@@ -165,12 +177,13 @@ def indices(collection_ids: Optional[List[str]]) -> str:
165177 collection_ids: A list of collection ids.
166178
167179 Returns:
168- A string of comma-separated index names. If `collection_ids` is None , returns the default indices.
180+ A string of comma-separated index names. If `collection_ids` is empty , returns the default indices.
169181 """
170- if not collection_ids :
171- return ITEM_INDICES
172- else :
173- return "," .join ([index_alias_by_collection_id (c ) for c in collection_ids ])
182+ return (
183+ "," .join (map (index_alias_by_collection_id , collection_ids ))
184+ if collection_ids
185+ else ITEM_INDICES
186+ )
174187
175188
176189def mk_item_id (item_id : str , collection_id : str ) -> str :
0 commit comments