: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
fix(search): literal-substring matching for surveys (#62386)
Paul D'Ambraeb97c831bbe5
diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.pyindex 9644b47583cd..01ed3c95d640 100644--- a/posthog/api/test/test_search_match_type_mixin.py+++ b/posthog/api/test/test_search_match_type_mixin.py@@ -7,6 +7,7 @@ from posthog.api.shared import SearchMatchTypeSerializerMixinfrom products.cdp.backend.api.hog_function import HogFunctionMinimalSerializer, HogFunctionSerializerfrom products.dashboards.backend.api.dashboard import DashboardBasicSerializerfrom products.product_analytics.backend.api.insight import InsightBasicSerializer, InsightSerializer+from products.surveys.backend.api.survey import SurveySerializer# 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.@@ -17,6 +18,7 @@ SEARCH_LIST_SERIALIZERS = [("dashboard_basic", DashboardBasicSerializer),("hog_function_minimal", HogFunctionMinimalSerializer),("hog_function", HogFunctionSerializer),+ ("survey", SurveySerializer),]diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 4159502b121c..75fc82e04253 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -7,11 +7,9 @@ from urllib.parse import urlparsefrom uuid import UUIDfrom django.conf import settings-from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarityfrom django.core.cache import cachefrom django.db import transaction-from django.db.models import F, Min, Q, QuerySet, Value-from django.db.models.functions import Coalesce+from django.db.models import Min, QuerySetfrom django.http import HttpRequest, HttpResponsefrom django.shortcuts import renderfrom django.utils.text import slugify@@ -43,20 +41,14 @@ from posthog.schema import ProductKeyfrom posthog.api.documentation import FeatureFlagFiltersSchemaSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.shared import UserBasicSerializer+from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.cloud_utils import is_cloudfrom posthog.constants import SURVEY_TARGETING_FLAG_PREFIX, AvailableFeaturefrom posthog.event_usage import report_user_action-from posthog.helpers.trigram_search import (- DESCRIPTION_SCORE_WEIGHT,- MAX_SEARCH_LENGTH,- MIN_DESCRIPTION_TRIGRAM_SIMILARITY,- MIN_NAME_TRIGRAM_SIMILARITY,- normalize_search_term,-)+from posthog.helpers.trigram_search import DESCRIPTION_FIELD, MAX_SEARCH_LENGTH, NAME_FIELD, apply_trigram_searchfrom posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.team.team import Team@@ -755,7 +747,7 @@ class SurveyResponsesListSerializer(serializers.Serializer):offset = serializers.IntegerField(help_text="The offset applied to this query (echoed back for pagination).")-class SurveySerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):+class SurveySerializer(SearchMatchTypeSerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer):linked_flag_id = serializers.IntegerField(required=False, allow_null=True, source="linked_flag.id")linked_flag = MinimalFeatureFlagSerializer(read_only=True)linked_insight_id = serializers.IntegerField(required=False, allow_null=True, source="linked_insight.id")@@ -839,6 +831,7 @@ class SurveySerializer(UserAccessControlSerializerMixin, serializers.ModelSerial"translations","user_access_level","form_content",+ "search_match_type",]read_only_fields = ["id", "created_at", "created_by"]@@ -2057,33 +2050,12 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.@staticmethod@tracer.start_as_current_span("SurveyViewSet._apply_search")def _apply_search(queryset: QuerySet, search: str) -> QuerySet:- search = normalize_search_term(search)- span = trace.get_current_span()- span.set_attribute("survey.search.length", len(search))- if not search:- return queryset-- zero = Value(0.0)- name_word_score = Coalesce(TrigramWordSimilarity(search, "name"), zero)- name_full_score = Coalesce(TrigramSimilarity("name", search), zero)- description_word_score = Coalesce(TrigramWordSimilarity(search, "description"), zero)-- return (- queryset.annotate(- _name_word=name_word_score,- _name_full=name_full_score,- _description_word=description_word_score,- )- .filter(- Q(_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY)- | Q(_description_word__gt=MIN_DESCRIPTION_TRIGRAM_SIMILARITY)- )- .annotate(- _name_match_score=F("_name_word") + F("_name_full"),- _description_match_score=F("_description_word"),- )- .annotate(_search_score=F("_name_match_score") + F("_description_match_score") * DESCRIPTION_SCORE_WEIGHT)- .order_by("-_search_score", "name")+ return apply_trigram_search(+ queryset,+ search,+ span_prefix="survey.search",+ fields=(NAME_FIELD, DESCRIPTION_FIELD),+ tiebreakers=("name",),)def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 930879df5dfa..9c8497528893 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -3440,7 +3440,7 @@ class TestSurvey(APIBaseTest):for name in survey_names:Survey.objects.create(team=self.team, name=name, type="popover", questions=[])- response = self.client.get(f"/api/projects/{self.team.id}/surveys/?search={search}")+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/", {"search": search})assert response.status_code == status.HTTP_200_OKresult_names = [r["name"] for r in response.json()["results"]]@@ -3477,7 +3477,7 @@ class TestSurvey(APIBaseTest):a = Survey.objects.create(team=self.team, name="Alpha", type="popover", questions=[])b = Survey.objects.create(team=self.team, name="Beta", type="popover", questions=[])- response = self.client.get(f"/api/projects/{self.team.id}/surveys/?search={search}")+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/", {"search": search})assert response.status_code == status.HTTP_200_OKresult_ids = {r["id"] for r in response.json()["results"]}@@ -3516,6 +3516,55 @@ class TestSurvey(APIBaseTest):assert body["attr"] == "search", f"expected error scoped to 'search', got {body}"assert "200 characters" in body["detail"], f"expected error detail to mention the cap, got {body['detail']}"+ @parameterized.expand(+ [+ ("email in name", "[email protected]", "[email protected]"),+ ("uuid in name", "run 1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"),+ ("dotted identifier", "com.acme.billing survey", "com.acme.billing"),+ ]+ )+ def test_list_filter_by_search_matches_literal_substring_below_trigram_threshold(self, _name, survey_name, search):+ matching = Survey.objects.create(team=self.team, name=survey_name, type="popover", questions=[])+ Survey.objects.create(team=self.team, name="Totally unrelated", type="popover", questions=[])++ response = self.client.get(f"/api/projects/{self.team.id}/surveys/", {"search": search})+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ match_type_by_id = {r["id"]: r["search_match_type"] for r in results}+ assert match_type_by_id.get(str(matching.id)) == "exact", (+ "a literal substring must match and be labelled exact even when it scores below the trigram thresholds"+ )+ assert all(r["name"] != "Totally unrelated" for r in results)++ def test_list_filter_by_search_returns_exact_first_with_match_type(self):+ for name in ("feedback survey", "survey feedback", "feeback form", "Engineering survey"):+ Survey.objects.create(team=self.team, name=name, type="popover", questions=[])++ response = self.client.get(f"/api/projects/{self.team.id}/surveys/?search=feedback")+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ match_type_by_name = {r["name"]: r["search_match_type"] for r in results}+ assert match_type_by_name == {+ "feedback survey": "exact",+ "survey feedback": "exact",+ "feeback form": "similar",+ }++ match_types = [r["search_match_type"] for r in results]+ assert match_types == ["exact", "exact", "similar"], f"exact matches must rank first, got {match_types}"++ def test_list_filter_by_search_match_type_absent_without_search(self):+ Survey.objects.create(team=self.team, name="Alpha", type="popover", questions=[])++ response = self.client.get(f"/api/projects/{self.team.id}/surveys/")+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ assert results+ assert all("search_match_type" not in r for r in results)+class TestMultipleChoiceQuestions(APIBaseTest):def test_create_survey_has_open_choice(self):diff --git a/products/surveys/frontend/generated/api.schemas.ts b/products/surveys/frontend/generated/api.schemas.tsindex 8db0bb59e7ba..eaacffb1aca4 100644--- a/products/surveys/frontend/generated/api.schemas.ts+++ b/products/surveys/frontend/generated/api.schemas.ts@@ -148,6 +148,13 @@ export const ResponseSamplingIntervalTypeEnumApi = {Month: 'month',} as const+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]++export const SearchMatchTypeEnumApi = {+ Exact: 'exact',+ Similar: 'similar',+} as const+/*** @nullable*/@@ -357,6 +364,8 @@ export interface SurveyApi {*/readonly user_access_level: string | nullform_content?: unknown+ /** 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}export interface PaginatedSurveyListApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2673adefdb84..988abd775739 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27751,6 +27751,8 @@ export namespace Schemas {*/readonly user_access_level: string | null;form_content?: unknown;+ /** 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;}export interface PaginatedSurveyList {