: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(search): shared trigram-search helper + SearchMatchTypeSerializerMixin (#62358)
Paul D'Ambra5ab76e916a52
diff --git a/posthog/api/shared.py b/posthog/api/shared.pyindex 9d04f99515a9..d3ba73772341 100644--- a/posthog/api/shared.py+++ b/posthog/api/shared.py@@ -5,12 +5,14 @@ This module contains serializers that are used across other serializers for nestimport copyfrom typing import Any, Optional+from drf_spectacular.utils import extend_schema_fieldfrom opentelemetry import tracefrom rest_framework import serializersfrom rest_framework.fields import SkipFieldfrom rest_framework.relations import PKOnlyObjectfrom rest_framework.utils import model_meta+from posthog.helpers.trigram_search import search_match_type_from_instancefrom posthog.models import Organization, Team, Userfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.project import Project@@ -18,6 +20,35 @@ from posthog.models.project import Projecttracer = trace.get_tracer(__name__)+# Adds the read-only `search_match_type` field to a saved-list serializer whose viewset runs+# `apply_trigram_search`. The helper annotates each matched row with `_is_exact`; this surfaces it+# as `exact` / `similar`, and strips the field entirely when the list was not filtered by `search`+# (no annotation present) so it never appears on retrieve or unfiltered lists. Mix it in before+# `ModelSerializer` in the bases so its `to_representation` runs in the super() chain — the+# `test_search_match_type_mixin` tests pin that ordering. Deliberately undocumented (no docstring):+# `inspect.getdoc` walks the MRO, so a docstring here would leak into every mixed-in serializer's+# public OpenAPI/MCP component description.+class SearchMatchTypeSerializerMixin(serializers.Serializer):+ search_match_type = serializers.SerializerMethodField(+ read_only=True,+ help_text=(+ "How this row matched the `search` query parameter: `exact` (the term is a "+ "case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match "+ "only). Results are ordered exact-first. Null when the list is not filtered by `search`."+ ),+ )++ @extend_schema_field(serializers.ChoiceField(choices=["exact", "similar"], allow_null=True))+ def get_search_match_type(self, instance: Any) -> Optional[str]:+ return search_match_type_from_instance(instance)++ def to_representation(self, instance: Any) -> Any:+ data = super().to_representation(instance)+ if getattr(instance, "_is_exact", None) is None:+ data.pop("search_match_type", None)+ return data++class UserBasicSerializer(serializers.ModelSerializer):hedgehog_config = serializers.SerializerMethodField()diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.pynew file mode 100644index 000000000000..62feaf66faff--- /dev/null+++ b/posthog/api/test/test_search_match_type_mixin.py@@ -0,0 +1,67 @@+from parameterized import parameterized+from rest_framework import serializers++from posthog.api.shared import SearchMatchTypeSerializerMixin++from products.product_analytics.backend.api.insight import InsightBasicSerializer, InsightSerializer++# Each product that migrates its saved-list search onto apply_trigram_search appends its+# serializer(s) here, so the MRO-ordering contract is pinned for every consumer.+SEARCH_LIST_SERIALIZERS = [+ ("insight_basic", InsightBasicSerializer),+ ("insight", InsightSerializer),+]+++class _DummySerializer(SearchMatchTypeSerializerMixin, serializers.Serializer):+ name = serializers.CharField()+++class _Exact:+ name = "x"+ _is_exact = 1+++class _Similar:+ name = "x"+ _is_exact = 0+++class _Unsearched:+ name = "x"+++class TestSearchMatchTypeSerializerMixin:+ @parameterized.expand(SEARCH_LIST_SERIALIZERS)+ def test_mixin_runs_before_model_serializer_in_mro(self, _name, serializer_class):+ mro = serializer_class.__mro__+ assert SearchMatchTypeSerializerMixin in mro, (+ f"{serializer_class.__name__} must mix in the search-match-type field"+ )+ assert mro.index(SearchMatchTypeSerializerMixin) < mro.index(serializers.ModelSerializer), (+ f"{serializer_class.__name__} must place SearchMatchTypeSerializerMixin before ModelSerializer so its "+ "to_representation runs in the super() chain and the field is stripped on non-search responses"+ )++ @parameterized.expand(SEARCH_LIST_SERIALIZERS)+ def test_field_is_declared(self, _name, serializer_class):+ assert "search_match_type" in serializer_class().fields++ @parameterized.expand(+ [+ ("exact match", _Exact(), "exact"),+ ("similar match", _Similar(), "similar"),+ ]+ )+ def test_field_present_and_labelled_on_search_results(self, _name, instance, expected):+ data = _DummySerializer().to_representation(instance)+ assert data["search_match_type"] == expected++ def test_field_stripped_when_not_a_search_result(self):+ data = _DummySerializer().to_representation(_Unsearched())+ assert "search_match_type" not in data++ def test_mixin_has_no_docstring_so_it_does_not_leak_into_component_descriptions(self):+ # inspect.getdoc walks the MRO; a docstring here would become every mixed-in serializer's+ # public OpenAPI/MCP component description.+ assert SearchMatchTypeSerializerMixin.__doc__ is Nonediff --git a/posthog/helpers/trigram_search.py b/posthog/helpers/trigram_search.pyindex f967207eeaca..22e84552dbb0 100644--- a/posthog/helpers/trigram_search.py+++ b/posthog/helpers/trigram_search.py@@ -1,3 +1,12 @@+from dataclasses import dataclass+from typing import Any++from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarity+from django.db.models import Case, F, IntegerField, Q, QuerySet, Value, When+from django.db.models.functions import Coalesce++from opentelemetry import trace+# Minimum trigram word similarity for a name match. Calibrated against the# `test_list_filter_by_search_*` tests in posthog/api/test/dashboards/test_dashboard.py.# Tighten it and typo cases stop matching, loosen it and unrelated rows leak in.@@ -14,6 +23,127 @@ DESCRIPTION_SCORE_WEIGHT = 0.5MAX_SEARCH_LENGTH = 200+@dataclass(frozen=True)+class TrigramSearchField:+ """One field a saved-list search scores and matches against.++ `field` is the ORM lookup path (e.g. `name`, `user__email`). `weight` scales the+ field's word-similarity contribution to `_search_score`. `threshold` is the minimum+ word similarity for the fuzzy match. `include_full` adds full-string similarity to+ the score so an exact-string hit outranks a row that merely contains the word.+ `literal` OR's an `icontains` predicate so substrings dense with non-alphanumerics+ (emails, UUIDs, dotted identifiers) — which pg_trgm tokenizes below threshold — still+ match, labelled `exact`."""++ field: str+ weight: float = 1.0+ threshold: float = MIN_NAME_TRIGRAM_SIMILARITY+ include_full: bool = False+ literal: bool = True++ @property+ def key(self) -> str:+ # Annotation aliases can't contain the `__` lookup separator.+ return self.field.replace("__", "_")+++# The common case: a `name` (word + full similarity) and a freeform `description`+# (word similarity only, down-weighted and held to a higher threshold).+NAME_FIELD = TrigramSearchField("name", include_full=True)+DESCRIPTION_FIELD = TrigramSearchField(+ "description", weight=DESCRIPTION_SCORE_WEIGHT, threshold=MIN_DESCRIPTION_TRIGRAM_SIMILARITY+)++def normalize_search_term(search: str) -> str:# Postgres rejects NUL bytes in text parameters; strip before they hit the query.return search.replace("\x00", "").strip()+++def search_match_type_from_instance(instance: Any) -> str | None:+ """Map the `_is_exact` annotation that `apply_trigram_search` leaves on each row to the+ `search_match_type` API value. Null when the list was not filtered by `search` (the+ annotation is absent), `exact` when the term is a literal substring of a searched field,+ `similar` when only the fuzzy trigram path matched."""+ is_exact = getattr(instance, "_is_exact", None)+ if is_exact is None:+ return None+ return "exact" if is_exact else "similar"+++def apply_trigram_search(+ queryset: QuerySet,+ search: str,+ *,+ span_prefix: str,+ fields: tuple[TrigramSearchField, ...],+ include_tag_search: bool = False,+ tiebreakers: tuple[str, ...] = (),+) -> QuerySet:+ """Apply trigram + literal-substring search across `fields`, then order exact-first.++ Two predicates select the rows. The literal `icontains` predicate (`exact_q`) catches+ tokens dense with non-alphanumerics — emails, UUIDs, dotted identifiers — where pg_trgm+ splits at punctuation and scores below threshold. The trigram word-similarity predicate+ (`similar_q`) catches typos and prefix-as-you-type. A row matching `exact_q` is flagged+ `_is_exact=1` and sorts ahead of fuzzy-only matches via the leading `-_is_exact` order key.++ Within each exactness tier, `_search_score` ranks rows by each field's weighted word+ similarity (plus full-string similarity where `include_full` is set). `tiebreakers` are+ appended after the score (e.g. `-pinned`, `name`).++ When `include_tag_search=True`, rows whose tag names contain the term also match (as+ `exact`), and `.distinct()` dedups the tag-join fan-out.++ Word/full annotations are coalesced to 0.0 so a row with a NULL field matched only on+ another field doesn't end up with a NULL `_search_score` (Postgres orders NULLS FIRST in+ DESC, putting such rows wrongly at the top)."""+ search = normalize_search_term(search)+ span = trace.get_current_span()+ span.set_attribute(f"{span_prefix}.length", len(search))+ if not search:+ return queryset++ zero = Value(0.0)++ word_annotations: dict[str, Any] = {}+ for f in fields:+ word_annotations[f"_word_{f.key}"] = Coalesce(TrigramWordSimilarity(search, f.field), zero)+ if f.include_full:+ word_annotations[f"_full_{f.key}"] = Coalesce(TrigramSimilarity(f.field, search), zero)++ exact_q = Q()+ for f in fields:+ if f.literal:+ # nosemgrep: orm-field-injection — f.field is a developer-defined TrigramSearchField path, not user input; only `search` is user-controlled and it is the bound value+ exact_q |= Q(**{f"{f.field}__icontains": search})+ if include_tag_search:+ matching_tag_ids = queryset.filter(tagged_items__tag__name__icontains=search).values("id")+ exact_q |= Q(id__in=matching_tag_ids)++ similar_q = Q()+ for f in fields:+ # nosemgrep: orm-field-injection — f.key derives from a developer-defined TrigramSearchField path, not user input+ similar_q |= Q(**{f"_word_{f.key}__gt": f.threshold})++ search_score: Any = None+ for f in fields:+ component: Any = F(f"_word_{f.key}") * f.weight+ if f.include_full:+ component = component + F(f"_full_{f.key}")+ search_score = component if search_score is None else search_score + component++ result = (+ queryset.annotate(**word_annotations)+ .annotate(+ _is_exact=Case(When(exact_q, then=Value(1)), default=Value(0), output_field=IntegerField()),+ _search_score=search_score,+ )+ .filter(exact_q | similar_q)+ .order_by("-_is_exact", "-_search_score", *tiebreakers)+ )++ if include_tag_search:+ result = result.distinct()++ return resultdiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex b916282048e8..6cbf4cbb2c40 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -7523,7 +7523,7 @@ export interface InsightApi {readonly alerts: readonly unknown[]/** @nullable */readonly last_viewed_at: string | null- /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */readonly search_match_type: SearchMatchTypeEnumApi | null}diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex de698bf1c6d4..dfc91ea46af8 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -5,23 +5,8 @@ from datetime import UTC, datetime, timedeltafrom functools import lru_cachefrom typing import Any, Union, cast-from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarityfrom django.db import transaction-from django.db.models import (- Case,- Count,- Exists,- F,- IntegerField,- Max,- OuterRef,- Prefetch,- QuerySet,- Subquery,- Value,- When,-)-from django.db.models.functions import Coalesce+from django.db.models import Count, Exists, F, Max, OuterRef, Prefetch, QuerySet, Subqueryfrom django.db.models.query_utils import Qfrom django.http import HttpResponsefrom django.utils.text import slugify@@ -66,7 +51,7 @@ from posthog.api.query_coalescer import QueryCoalescingMixinfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.services.query import process_query_dict, process_query_model-from posthog.api.shared import UserBasicSerializer+from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.api.utils import action, format_paginated_urlfrom posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication@@ -80,11 +65,11 @@ from posthog.event_usage import get_request_analytics_properties, report_user_acfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.multi_property_breakdown import protect_old_clients_from_multi_property_defaultfrom posthog.helpers.trigram_search import (- DESCRIPTION_SCORE_WEIGHT,+ DESCRIPTION_FIELD,MAX_SEARCH_LENGTH,- MIN_DESCRIPTION_TRIGRAM_SIMILARITY,- MIN_NAME_TRIGRAM_SIMILARITY,- normalize_search_term,+ NAME_FIELD,+ TrigramSearchField,+ apply_trigram_search,)from posthog.hogql_queries.apply_dashboard_filters import (WRAPPER_NODE_KINDS,@@ -328,6 +313,7 @@ class DashboardTileBasicSerializer(serializers.ModelSerializer):@extend_schema_serializer(exclude_fields=["filters", "saved"])class InsightBasicSerializer(+ SearchMatchTypeSerializerMixin,TaggedItemSerializerMixin,UserPermissionsSerializerMixin,serializers.ModelSerializer,@@ -341,14 +327,6 @@ class InsightBasicSerializer(dashboards = serializers.SerializerMethodField(read_only=True)created_by = UserBasicSerializer(read_only=True)last_viewed_at = serializers.SerializerMethodField(read_only=True)- search_match_type = serializers.SerializerMethodField(- read_only=True,- help_text=(- "How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the "- "name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are "- "ordered exact-first. Null when the list is not filtered by `search`."- ),- )class Meta:model = Insight@@ -389,13 +367,6 @@ class InsightBasicSerializer("""Get the last viewed timestamp for this insight by any user in the team."""return getattr(instance, "last_viewed_at", None)- @extend_schema_field(serializers.ChoiceField(choices=["exact", "similar"], allow_null=True))- def get_search_match_type(self, instance: Insight) -> str | None:- is_exact = getattr(instance, "_is_exact", None)- if is_exact is None:- return None- return "exact" if is_exact else "similar"-def to_representation(self, instance):representation = super().to_representation(instance)@@ -411,11 +382,6 @@ class InsightBasicSerializer(# upgrade the query to the latest versionrepresentation["query"] = upgrade(representation["query"])- # search_match_type is a per-row search annotation — only surface it on search results, not on- # every serialized insight (unfiltered lists, dashboard-embedded tiles, retrieve, etc.)- if getattr(instance, "_is_exact", None) is None:- representation.pop("search_match_type", None)-return representation@lru_cache(maxsize=1) # noqa: B019 - short-lived serializer@@ -1643,47 +1609,15 @@ class InsightViewSet(return Response({"count": len(data), "next": None, "previous": None, "results": data})@staticmethod- def _annotate_search_scores(queryset: QuerySet, search: str) -> QuerySet:- zero = Value(0.0)- return queryset.annotate(- _name_word=Coalesce(TrigramWordSimilarity(search, "name"), zero),- _name_full=Coalesce(TrigramSimilarity("name", search), zero),- _derived_name_word=Coalesce(TrigramWordSimilarity(search, "derived_name"), zero),- _description_word=Coalesce(TrigramWordSimilarity(search, "description"), zero),- ).annotate(- _search_score=F("_name_word")- + F("_name_full")- + F("_derived_name_word")- + F("_description_word") * DESCRIPTION_SCORE_WEIGHT- )-@tracer.start_as_current_span("InsightViewSet._apply_search")- def _apply_search(self, queryset: QuerySet, search: str) -> QuerySet:- search = normalize_search_term(search)- span = trace.get_current_span()- span.set_attribute("insight.search.length", len(search))- if not search:- return queryset-- scored = self._annotate_search_scores(queryset, search)- matching_tag_ids = queryset.filter(tagged_items__tag__name__icontains=search).values("id")- exact_q = (- Q(name__icontains=search)- | Q(derived_name__icontains=search)- | Q(description__icontains=search)- | Q(id__in=matching_tag_ids)- )- similar_q = (- Q(_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY)- | Q(_derived_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY)- | Q(_description_word__gt=MIN_DESCRIPTION_TRIGRAM_SIMILARITY)- )-- return (- scored.annotate(_is_exact=Case(When(exact_q, then=Value(1)), default=Value(0), output_field=IntegerField()))- .filter(exact_q | similar_q)- .order_by("-_is_exact", "-_search_score", "name")- .distinct()+ def _apply_search(queryset: QuerySet, search: str) -> QuerySet:+ return apply_trigram_search(+ queryset,+ search,+ span_prefix="insight.search",+ fields=(NAME_FIELD, TrigramSearchField("derived_name"), DESCRIPTION_FIELD),+ include_tag_search=True,+ tiebreakers=("name",),)def _filter_request(self, request: request.Request, queryset: QuerySet) -> QuerySet:diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 95d6fa4b7e7e..8b6ce16be23f 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -7273,7 +7273,7 @@ export interface InsightApi {readonly alerts: readonly unknown[]/** @nullable */readonly last_viewed_at: string | null- /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */readonly search_match_type: SearchMatchTypeEnumApi | null}@@ -7393,7 +7393,7 @@ export interface PatchedInsightApi {readonly alerts?: readonly unknown[]/** @nullable */readonly last_viewed_at?: string | null- /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */readonly search_match_type?: SearchMatchTypeEnumApi | null}@@ -7540,7 +7540,7 @@ export interface TrendingInsightApi {readonly user_access_level: string | null/** @nullable */readonly last_viewed_at: string | null- /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */readonly search_match_type: SearchMatchTypeEnumApi | null/** Number of distinct viewers in the time window. Higher values indicate insights that more people in the project actively look at, which is a strong proxy for which insights matter. */readonly view_count: numberdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a0289f37e648..694e1b4b2092 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7025,7 +7025,7 @@ export namespace Schemas {readonly alerts: readonly unknown[];/** @nullable */readonly last_viewed_at: string | null;- /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */readonly search_match_type: SearchMatchTypeEnum | null;}@@ -27633,7 +27633,7 @@ export namespace Schemas {readonly user_access_level: string | null;/** @nullable */readonly last_viewed_at: string | null;- /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */readonly search_match_type: SearchMatchTypeEnum | null;/** Number of distinct viewers in the time window. Higher values indicate insights that more people in the project actively look at, which is a strong proxy for which insights matter. */readonly view_count: number;@@ -30401,7 +30401,7 @@ export namespace Schemas {readonly alerts?: readonly unknown[];/** @nullable */readonly last_viewed_at?: string | null;- /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */readonly search_match_type?: SearchMatchTypeEnum | null;}