Skip to content

Commit

Permalink
Merge pull request #944 from materialsproject/enhancement/sort_field_…
Browse files Browse the repository at this point in the history
…config

Add config option to sort query op
  • Loading branch information
munrojm committed Apr 30, 2024
2 parents 56813b3 + 45d5ad3 commit ffd1929
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/maggma/api/query_operator/sorting.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,28 @@
from typing import Optional
from typing import List, Optional

from fastapi import Query
from fastapi.exceptions import HTTPException

from maggma.api.query_operator import QueryOperator
from maggma.api.utils import STORE_PARAMS


class SortQuery(QueryOperator):
"""
Method to generate the sorting portion of a query.
"""
"""Method to generate the sorting portion of a query."""

def __init__(self, fields: Optional[List[str]] = None, max_num: Optional[int] = None):
"""Sort query configuration.
Args:
fields (Optional[List[str]]): List of allowed fields to sort with
max_num (Optional[int]): Max number of fields to simultaneously sort with
"""
self.fields = fields or []
self.max_num = max_num or 0

if self.max_num < 0:
raise ValueError("Max number of fields should be larger than 0")

def query(
self,
Expand All @@ -22,7 +35,16 @@ def query(
sort = {}

if _sort_fields:
for sort_field in _sort_fields.split(","):
field_list = _sort_fields.split(",")
if self.max_num and len(field_list) > self.max_num:
raise HTTPException(
status_code=400, detail=f"Please provide at most {self.max_num} field(s) to sort with"
)

for sort_field in field_list:
if self.fields and sort_field not in self.fields:
continue

if sort_field[0] == "-":
sort.update({sort_field[1:]: -1})
else:
Expand Down

0 comments on commit ffd1929

Please sign in to comment.