Skip to content

Commit 158f256

Browse files
committed
paginate, sort collections
1 parent 4e69ba0 commit 158f256

File tree

2 files changed

+21
-28
lines changed

2 files changed

+21
-28
lines changed

stac_fastapi/elasticsearch/stac_fastapi/elasticsearch/core.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
11
"""Item crud client."""
22
import json
33
import logging
4+
from base64 import urlsafe_b64encode
45
from datetime import datetime as datetime_type
56
from datetime import timezone
67
from typing import Any, Dict, List, Optional, Set, Type, Union
7-
from base64 import urlsafe_b64encode
8+
from urllib.parse import urljoin
89

910
import attr
1011
import stac_pydantic
1112
from fastapi import HTTPException
1213
from overrides import overrides
1314
from pydantic import ValidationError
14-
from starlette.requests import Request
1515
from stac_pydantic.links import Relations
1616
from stac_pydantic.shared import MimeTypes
17-
from urllib.parse import urljoin
17+
from starlette.requests import Request
1818

1919
from stac_fastapi.elasticsearch import serializers
2020
from stac_fastapi.elasticsearch.config import ElasticsearchSettings
@@ -71,12 +71,7 @@ class CoreClient(AsyncBaseCoreClient):
7171
database = DatabaseLogic()
7272

7373
@overrides
74-
async def all_collections(
75-
self,
76-
limit: Optional[int] = 10,
77-
token: Optional[str] = None,
78-
**kwargs
79-
) -> Collections:
74+
async def all_collections(self, **kwargs) -> Collections:
8075
"""Read all collections from the database.
8176
8277
Returns:
@@ -89,20 +84,23 @@ async def all_collections(
8984
request: Request = kwargs["request"]
9085
base_url = str(kwargs["request"].base_url)
9186

92-
hits = self.database.get_all_collections(limit=limit, token=token)
87+
limit = int(request.query_params["limit"]) if "limit" in request.query_params else 10
88+
token = request.query_params["token"] if "token" in request.query_params else None
89+
90+
hits = await self.database.get_all_collections(limit=limit, token=token)
9391

9492
next_search_after = None
9593
next_link = None
9694
if len(hits) == limit:
9795
last_hit = hits[-1]
98-
next_search_after = last_hit['sort']
99-
next_token = urlsafe_b64encode(','.join(map(str, next_search_after)).encode()).decode()
100-
paging_links = PagingLinks(
101-
next=next_token, request=request
102-
)
96+
next_search_after = last_hit["sort"]
97+
next_token = urlsafe_b64encode(
98+
",".join(map(str, next_search_after)).encode()
99+
).decode()
100+
paging_links = PagingLinks(next=next_token, request=request)
103101
next_link = paging_links.link_next()
104102

105-
links=[
103+
links = [
106104
{
107105
"rel": Relations.root.value,
108106
"type": MimeTypes.json,
@@ -117,18 +115,18 @@ async def all_collections(
117115
"rel": Relations.self.value,
118116
"type": MimeTypes.json,
119117
"href": urljoin(base_url, "collections"),
120-
}
118+
},
121119
]
122120

123121
if next_link:
124122
links.append(next_link)
125-
123+
126124
return Collections(
127125
collections=[
128126
self.collection_serializer.db_to_stac(c["_source"], base_url=base_url)
129127
for c in hits
130128
],
131-
links=links
129+
links=links,
132130
)
133131

134132
@overrides

stac_fastapi/elasticsearch/stac_fastapi/elasticsearch/database_logic.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
from stac_fastapi.types.errors import ConflictError, NotFoundError
1919
from stac_fastapi.types.stac import Collection, Item
2020

21-
2221
logger = logging.getLogger(__name__)
2322

2423
NumType = Union[float, int]
@@ -297,31 +296,27 @@ class DatabaseLogic:
297296
"""CORE LOGIC"""
298297

299298
async def get_all_collections(
300-
self,
301-
token: Optional[str],
302-
limit: int
299+
self, token: Optional[str], limit: int
303300
) -> Iterable[Dict[str, Any]]:
304301
"""Retrieve a list of all collections from the database.
305302
306303
Args:
307304
token (Optional[str]): The token used to return the next set of results.
308-
limit (int): Number of results to return
305+
limit (int): Number of results to return
309306
310307
Returns:
311308
collections (Iterable[Dict[str, Any]]): A list of dictionaries containing the source data for each collection.
312309
313310
Notes:
314311
The collections are retrieved from the Elasticsearch database using the `client.search` method,
315-
with the `COLLECTIONS_INDEX` as the target index and `size=1000` to retrieve up to 1000 records.
312+
with the `COLLECTIONS_INDEX` as the target index and `size=limit` to retrieve records.
316313
The result is a generator of dictionaries containing the source data for each collection.
317314
"""
318315
search_after = None
319316
if token:
320317
search_after = urlsafe_b64decode(token.encode()).decode().split(",")
321318
collections = await self.client.search(
322-
index=COLLECTIONS_INDEX,
323-
search_after=search_after,
324-
size=limit
319+
index=COLLECTIONS_INDEX, search_after=search_after, size=limit, sort={"id": {"order": "asc"}}
325320
)
326321
hits = collections["hits"]["hits"]
327322
return hits

0 commit comments

Comments
 (0)