Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(customer-analytics): speed up account table sort by custom property (#122195)

Arthur Moreira de Deus88bce38cc745
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 8a8412ae89cf..ce4a0e47487b 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -35,11 +35,10 @@ from django.db.models import (
BooleanField,
CharField,
Count,
- DateTimeField,
Exists,
ExpressionWrapper,
F,
- Field,
+ FilteredRelation,
FloatField,
IntegerField,
Max,
@@ -50,7 +49,6 @@ from django.db.models import (
QuerySet,
Subquery,
Sum,
- TextField,
Value,
)
from django.db.models.fields.json import KeyTextTransform
@@ -3336,15 +3334,6 @@ def _apply_account_table_filters(
raise InvalidAccountTableColumn(str(error)) from error
-def _custom_property_sort_output_field(display_type: DisplayType) -> Field:
- return {
- DataType.STRING: TextField(),
- DataType.NUMERIC: FloatField(),
- DataType.BOOLEAN: BooleanField(),
- DataType.DATETIME: DateTimeField(),
- }[DATA_TYPE_BY_DISPLAY_TYPE[display_type]]
-
-
def _apply_account_table_sort(
queryset: QuerySet[Account],
*,
@@ -3417,14 +3406,16 @@ def _apply_account_table_sort(
DataType.BOOLEAN: "value_bool",
DataType.DATETIME: "value_datetime",
}[DATA_TYPE_BY_DISPLAY_TYPE[display_type]]
- custom_property_value = CustomPropertyValue.objects.for_team(team_id).filter(
- account_id=OuterRef("pk"), definition_id=sort.definition_id, is_deleted=False
- )
queryset = queryset.annotate(
- _account_table_sort=Subquery(
- custom_property_value.values(value_field)[:1],
- output_field=_custom_property_sort_output_field(display_type),
- )
+ _custom_property_sort_value=FilteredRelation(
+ "custom_property_values",
+ condition=Q(
+ custom_property_values__team_id=team_id,
+ custom_property_values__definition_id=sort.definition_id,
+ custom_property_values__is_deleted=False,
+ ),
+ ),
+ _account_table_sort=F(f"_custom_property_sort_value__{value_field}"),
)
order = F("_account_table_sort")
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
index 6d9a0fa04e60..70330bad3ec3 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
@@ -1095,6 +1095,9 @@ class TestAccountsTableQueryRunner(BaseTest):
CustomPropertyValue.objects.unscoped().create(
team=self.team, account=beta, definition=custom_property_definition, value_num=5
)
+ CustomPropertyValue.objects.unscoped().create(
+ team=self.team, account=beta, definition=custom_property_definition, value_num=50, is_deleted=True
+ )
paginated = self._run(
AccountsTableQuery(
diff --git a/products/customer_analytics/backend/migrations/0062_custompropertyvalue_active_team_definition_index.py b/products/customer_analytics/backend/migrations/0062_custompropertyvalue_active_team_definition_index.py
new file mode 100644
index 000000000000..0c238353ba0e
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0062_custompropertyvalue_active_team_definition_index.py
@@ -0,0 +1,22 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("customer_analytics", "0061_announcement_send_as"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="custompropertyvalue",
+ index=models.Index(
+ condition=models.Q(("is_deleted", False)),
+ fields=["team", "definition", "account"],
+ name="cpv_active_team_definition_idx",
+ ),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index e575e1ba50bb..7448e430a1ce 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0061_announcement_send_as
+0062_custompropertyvalue_active_team_definition_index
diff --git a/products/customer_analytics/backend/models/custom_property_value.py b/products/customer_analytics/backend/models/custom_property_value.py
index 7029b8c12f0f..9c76ed76110a 100644
--- a/products/customer_analytics/backend/models/custom_property_value.py
+++ b/products/customer_analytics/backend/models/custom_property_value.py
@@ -31,6 +31,13 @@ class CustomPropertyValue(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
value_datetime = models.DateTimeField(null=True, blank=True)
class Meta:
+ indexes = [
+ models.Index(
+ fields=["team", "definition", "account"],
+ condition=Q(is_deleted=False),
+ name="cpv_active_team_definition_idx",
+ ),
+ ]
constraints = [
models.UniqueConstraint(
fields=["team", "account", "definition"],