Skip to content

Commit

Permalink
fix(trends): session duration property filters (#21210)
Browse files Browse the repository at this point in the history
  • Loading branch information
mariusandra authored Mar 28, 2024
1 parent 02c596c commit df6c124
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
31 changes: 21 additions & 10 deletions posthog/hogql/property.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ def property_to_expr(
or property.type == "person"
or property.type == "group"
or property.type == "data_warehouse"
or property.type == "session"
):
if scope == "person" and property.type != "person":
raise NotImplementedException(
Expand All @@ -154,8 +155,14 @@ def property_to_expr(
chain = []
else:
chain = ["properties"]

properties_field = ast.Field(chain=chain)
field = ast.Field(chain=chain + [property.key])

if property.type == "session" and property.key == "$session_duration":
field = ast.Field(chain=["session", "duration"])
properties_field = field

if isinstance(value, list):
if len(value) == 0:
return ast.Constant(value=True)
Expand Down Expand Up @@ -185,8 +192,6 @@ def property_to_expr(
return ast.And(exprs=exprs)
return ast.Or(exprs=exprs)

properties_field = ast.Field(chain=chain)

if operator == PropertyOperator.is_set:
return ast.CompareOperation(
op=ast.CompareOperationOp.NotEq,
Expand All @@ -200,14 +205,20 @@ def property_to_expr(
op=ast.CompareOperationOp.Eq,
left=field,
right=ast.Constant(value=None),
),
ast.Not(
expr=ast.Call(
name="JSONHas",
args=[properties_field, ast.Constant(value=property.key)],
)
),
)
]
+ (
[]
if properties_field == field
else [
ast.Not(
expr=ast.Call(
name="JSONHas",
args=[properties_field, ast.Constant(value=property.key)],
)
)
]
)
)
elif operator == PropertyOperator.icontains:
return ast.CompareOperation(
Expand Down Expand Up @@ -334,7 +345,7 @@ def property_to_expr(
right=ast.Constant(value=cohort.pk),
)

# TODO: Add support for these types "recording", "behavioral", and "session" types
# TODO: Add support for these types: "recording", "behavioral"

raise NotImplementedException(
f"property_to_expr not implemented for filter type {type(property).__name__} and {property.type}"
Expand Down
9 changes: 9 additions & 0 deletions posthog/hogql/test/test_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,3 +656,12 @@ def test_entity_to_expr_default_case(self):
right=ast.Constant(value="default_event"),
)
self.assertEqual(result, expected)

def test_session_duration(self):
self.assertEqual(
self._property_to_expr(
{"type": "session", "key": "$session_duration", "value": 10, "operator": "exact"},
scope="event",
),
self._parse_expr("session.duration = 10"),
)

0 comments on commit df6c124

Please sign in to comment.