Skip to content

Commit

Permalink
feat(core): add meta intersection filter
Browse files Browse the repository at this point in the history
  • Loading branch information
Yelinz committed Aug 14, 2023
1 parent 935e7a9 commit 1a54a7f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
24 changes: 18 additions & 6 deletions caluma/caluma_core/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.contrib.postgres.fields.hstore import KeyTransform
from django.contrib.postgres.search import SearchVector
from django.db import models
from django.db.models import Q
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import OrderBy
from django.db.models.fields.json import KeyTextTransform
Expand Down Expand Up @@ -378,6 +379,7 @@ class JSONLookupMode(Enum):
CONTAINS = "contains"
ICONTAINS = "icontains"
IN = "in"
INTERSECTS = "intersects"
GTE = "gte"
GT = "gt"
LTE = "lte"
Expand Down Expand Up @@ -423,13 +425,23 @@ def filter(self, qs, value):
KeyTextTransform(expr["key"], self.field_name),
models.CharField(),
),
)
lookup = {f"field_val__{lookup_expr}": expr["value"]}
).filter(**{f"field_val__{lookup_expr}": expr["value"]})
elif lookup_expr == JSONLookupMode.INTERSECTS:
exprs = [
Q(**{f"{self.field_name}__{expr['key']}__contains": val})
for val in expr["value"]
]
# connect all expressions with OR
qs = qs.filter(reduce(lambda a, b: a | b, exprs))
else:
lookup = {
f"{self.field_name}__{expr['key']}__{lookup_expr}": expr["value"]
}
qs = qs.filter(**lookup)
qs = qs.filter(
**{
f"{self.field_name}__{expr['key']}__{lookup_expr}": expr[
"value"
]
}
)

return qs

@staticmethod
Expand Down
9 changes: 9 additions & 0 deletions caluma/caluma_core/tests/test_meta_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
("CONTAINS", "bar", ["contains", "starts", "exact"]),
("ICONTAINS", "bar", ["icontains", "contains", "starts", "exact"]),
("IN", [1, 2], ["in"]),
(
"INTERSECTS",
[2, "with"],
["intersects_mixed", "intersects_string", "intersects_int"],
),
(None, True, ["bool"]),
(None, 123, ["int"]),
(None, 123.456, ["float"]),
Expand All @@ -30,6 +35,10 @@ def test_meta_value_filter(
"bool": document_factory(meta={"foo": True}),
"int": document_factory(meta={"foo": 123}),
"float": document_factory(meta={"foo": 123.456}),
"intersects_none": document_factory(meta={"foo": ["none"]}),
"intersects_mixed": document_factory(meta={"foo": [2, 3, "with"]}),
"intersects_string": document_factory(meta={"foo": ["start", "with"]}),
"intersects_int": document_factory(meta={"foo": [1, 2, 3]}),
}

query = """
Expand Down
1 change: 1 addition & 0 deletions caluma/tests/__snapshots__/test_schema.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -1671,6 +1671,7 @@
CONTAINS
ICONTAINS
IN
INTERSECTS
GTE
GT
LTE
Expand Down

0 comments on commit 1a54a7f

Please sign in to comment.