Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable filtering on relationships with mongo #234

Merged
merged 5 commits into from
Apr 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions optimade/filtertransformers/mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def postprocess(self, query):
query = self._apply_length_aliases(query)
query = self._apply_aliases(query)

query = self._apply_relationship_filtering(query)
query = self._apply_length_operators(query)

return query
Expand Down Expand Up @@ -346,6 +347,48 @@ def apply_length_op(subdict, prop, expr):
filter_, check_for_length_op_filter, apply_length_op,
)

def _apply_relationship_filtering(self, filter_: dict) -> dict:
""" Check query for property names that match the entry
types, and transform them as relationship filters rather than
property filters.

"""

def check_for_entry_type(prop, expr):
return str(prop).count(".") == 1 and str(prop).split(".")[0] in (
"structures",
"references",
)

def replace_with_relationship(subdict, prop, expr):
_prop, _field = str(prop).split(".")
if _field != "id":
raise NotImplementedError(
f'Cannot filter relationships by field "{_field}", only "id" is supported.'
)

# in the case of HAS ONLY, the size operator needs to be applied
# one level up, i.e. excluding the field
if "$size" in expr:
if "$and" not in subdict:
subdict["$and"] = []
subdict["$and"].extend(
[
{f"relationships.{_prop}.data": {"$size": expr.pop("$size")}},
{f"relationships.{_prop}.data.{_field}": expr},
]
)
else:
subdict[f"relationships.{_prop}.data.{_field}"] = expr

subdict.pop(prop)

return subdict

return recursive_postprocessing(
filter_, check_for_entry_type, replace_with_relationship
)


def recursive_postprocessing(filter_, condition, replacement):
""" Recursively descend into the query, checking each dictionary
Expand Down
8 changes: 8 additions & 0 deletions optimade/server/exception_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,13 @@ def grammar_not_implemented_handler(request: Request, exc: VisitError):
return general_exception(request, exc, status_code=status, errors=[error])


def not_implemented_handler(request: Request, exc: NotImplementedError):
status = 501
title = "NotImplementedError"
detail = str(exc)
error = OptimadeError(detail=detail, status=status, title=title)
return general_exception(request, exc, status_code=status, errors=[error])


def general_exception_handler(request: Request, exc: Exception):
return general_exception(request, exc)
1 change: 1 addition & 0 deletions optimade/server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ def load_entries(endpoint_name: str, endpoint_collection: MongoCollection):
)
app.add_exception_handler(ValidationError, exc_handlers.validation_exception_handler)
app.add_exception_handler(VisitError, exc_handlers.grammar_not_implemented_handler)
app.add_exception_handler(NotImplementedError, exc_handlers.not_implemented_handler)
app.add_exception_handler(Exception, exc_handlers.general_exception_handler)


Expand Down
61 changes: 61 additions & 0 deletions tests/filtertransformers/test_mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,67 @@ def test_operators(self):
with self.assertRaises(VisitError):
self.transform('"some string" > "some other string"')

def test_filtering_on_relationships(self):
""" Test the nested properties with special names
like "structures", "references" etc. are applied
to the relationships field.

"""

self.assertEqual(
self.transform('references.id HAS "dummy/2019"'),
{"relationships.references.data.id": {"$in": ["dummy/2019"]}},
)

self.assertEqual(
self.transform('structures.id HAS ANY "dummy/2019", "dijkstra1968"'),
{
"relationships.structures.data.id": {
"$in": ["dummy/2019", "dijkstra1968"]
}
},
)

self.assertEqual(
self.transform('structures.id HAS ALL "dummy/2019", "dijkstra1968"'),
{
"relationships.structures.data.id": {
"$all": ["dummy/2019", "dijkstra1968"]
}
},
)

self.assertEqual(
self.transform('structures.id HAS ONLY "dummy/2019"'),
{
"$and": [
{"relationships.structures.data": {"$size": 1}},
{"relationships.structures.data.id": {"$all": ["dummy/2019"]}},
]
},
)

self.assertEqual(
self.transform(
'structures.id HAS ONLY "dummy/2019" AND structures.id HAS "dummy/2019"'
),
{
"$and": [
{
"$and": [
{"relationships.structures.data": {"$size": 1}},
{
"relationships.structures.data.id": {
"$all": ["dummy/2019"]
}
},
]
},
{"relationships.structures.data.id": {"$in": ["dummy/2019"]}},
],
},
)

def test_not_implemented(self):
""" Test that list properties that are currently not implemented
give a sensible response.
Expand Down
26 changes: 26 additions & 0 deletions tests/server/test_query_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,32 @@ def test_brackets(self):
expected_ids = ["mpf_1"]
self._check_response(request, expected_ids, len(expected_ids))

def test_filter_on_relationships(self):
request = '/structures?filter=references.id HAS "dummy/2019"'
expected_ids = ["mpf_3819"]
self._check_response(request, expected_ids, len(expected_ids))

request = (
'/structures?filter=references.id HAS ANY "dummy/2019", "dijkstra1968"'
)
expected_ids = ["mpf_1", "mpf_2", "mpf_3819"]
self._check_response(request, expected_ids, len(expected_ids))

request = '/structures?filter=references.id HAS ONLY "dijkstra1968"'
expected_ids = ["mpf_1", "mpf_2"]
self._check_response(request, expected_ids, len(expected_ids))

request = '/structures?filter=references.doi HAS ONLY "10/123"'
error_detail = (
'Cannot filter relationships by field "doi", only "id" is supported.'
)
self._check_error_response(
request,
expected_status=501,
expected_title="NotImplementedError",
expected_detail=error_detail,
)

def _check_response(
self, request: str, expected_ids: Union[List, Set], expected_return: int
):
Expand Down