Skip to content

Commit

Permalink
Use $nor when $or -> $not chain is found
Browse files Browse the repository at this point in the history
  • Loading branch information
ml-evs committed Mar 6, 2020
1 parent 9bd4bcb commit 8e7078d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 26 deletions.
3 changes: 3 additions & 0 deletions optimade/filtertransformers/mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ def expression_phrase(self, arg):
# without NOT
return arg[0]

if list(arg[1].keys()) == ["$or"]:
return {"$nor": arg[1]["$or"]}

# with NOT
# TODO: This implementation probably fails in the case of `"(" expression ")"`
return {prop: {"$not": expr} for prop, expr in arg[1].items()}
Expand Down
48 changes: 22 additions & 26 deletions tests/filtertransformers/test_mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,30 +114,28 @@ def test_operators(self):
self.assertEqual(self.transform("NOT a<3"), {"a": {"$not": {"$lt": 3}}})

# TODO: {'$not': {'$eq': 'Ti'}} can be simplified to {'$ne': 'Ti'}
# TODO: THIS IS NOT A VALID MONGO QUERY!!! We should switch to $nor, but
# that may break the defined optimade operator precendence
self.assertEqual(
self.transform(
'NOT ( chemical_formula_hill = "Al" AND chemical_formula_anonymous = "A" OR '
'chemical_formula_anonymous = "H2O" AND NOT chemical_formula_hill = "Ti" )'
"NOT ( "
'chemical_formula_hill = "Al" AND chemical_formula_anonymous = "A" OR '
'chemical_formula_anonymous = "H2O" AND NOT chemical_formula_hill = "Ti"'
")"
),
{
"$or": {
"$not": [
{
"$and": [
{"chemical_formula_hill": {"$eq": "Al"}},
{"chemical_formula_anonymous": {"$eq": "A"}},
]
},
{
"$and": [
{"chemical_formula_anonymous": {"$eq": "H2O"}},
{"chemical_formula_hill": {"$not": {"$eq": "Ti"}}},
]
},
]
}
"$nor": [
{
"$and": [
{"chemical_formula_hill": {"$eq": "Al"}},
{"chemical_formula_anonymous": {"$eq": "A"}},
]
},
{
"$and": [
{"chemical_formula_anonymous": {"$eq": "H2O"}},
{"chemical_formula_hill": {"$not": {"$eq": "Ti"}}},
]
},
]
},
)

Expand Down Expand Up @@ -166,12 +164,10 @@ def test_operators(self):
"$and": [
{"nelements": {"$gte": 10}},
{
"$or": {
"$not": [
{"_exmpl_x": {"$ne": "Some string"}},
{"_exmpl_a": {"$not": {"$eq": 7}}},
]
}
"$nor": [
{"_exmpl_x": {"$ne": "Some string"}},
{"_exmpl_a": {"$not": {"$eq": 7}}},
]
},
]
},
Expand Down

0 comments on commit 8e7078d

Please sign in to comment.