: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
perf(surveys): server-side fuzzy search via pg_trgm (#57441)
Paul D'Ambra11f33d3fd2d8
diff --git a/frontend/src/scenes/surveys/surveysLogic.test.ts b/frontend/src/scenes/surveys/surveysLogic.test.tsindex cfcacc33820d..9e6aeaffd2a7 100644--- a/frontend/src/scenes/surveys/surveysLogic.test.ts+++ b/frontend/src/scenes/surveys/surveysLogic.test.ts@@ -51,32 +51,11 @@ describe('surveysLogic', () => {await expectLogic(logic).toFinishAllListeners()})- it('performs frontend search immediately', async () => {- await expectLogic(logic, () => {- logic.actions.loadSurveysSuccess({- surveys: [- createTestSurvey('1', 'Test Survey 1'),- createTestSurvey('2', 'Another Survey'),- createTestSurvey('3', 'Test Survey 3'),- ],- surveysCount: 150,- searchSurveys: [],- searchSurveysCount: 0,- })- logic.actions.setSearchTerm('Test')- }).toMatchValues({- searchedSurveys: expect.arrayContaining([- expect.objectContaining({ id: '1' }),- expect.objectContaining({ id: '3' }),- ]),- })- })-- it('triggers backend search after debounce for large datasets', async () => {+ it('triggers backend search after debounce', async () => {await expectLogic(logic, () => {logic.actions.loadSurveysSuccess({surveys: [createTestSurvey('1', 'Test Survey')],- surveysCount: 150, // > SURVEY_PAGE_SIZE+ surveysCount: 150,searchSurveys: [],searchSurveysCount: 0,})@@ -86,22 +65,7 @@ describe('surveysLogic', () => {.toDispatchActions(['loadSearchResults'])})- it('performs only frontend search for small datasets', async () => {- await expectLogic(logic, () => {- logic.actions.loadSurveysSuccess({- surveys: [createTestSurvey('1', 'Test Survey')],- surveysCount: 50, // < SURVEY_PAGE_SIZE- searchSurveys: [],- searchSurveysCount: 0,- })- logic.actions.setSearchTerm('Test')- })- .delay(400)- .toNotHaveDispatchedActions(['loadSearchResults'])- })-- it('merges and deduplicates frontend and backend results', async () => {- // Set initial state with frontend results and trigger search+ it('searchedSurveys reflects backend results once loaded', async () => {await expectLogic(logic, () => {logic.actions.loadSurveysSuccess({surveys: [createTestSurvey('1', 'Test Survey'), createTestSurvey('2', 'Another Test')],@@ -110,26 +74,14 @@ describe('surveysLogic', () => {searchSurveysCount: 0,})logic.actions.setSearchTerm('Test')- }).toMatchValues({- // Verify frontend search results first- searchedSurveys: expect.arrayContaining([- expect.objectContaining({ id: '1' }),- expect.objectContaining({ id: '2' }),- ]),- })-- // Then simulate backend search completion- await expectLogic(logic, () => {logic.actions.loadSearchResultsSuccess({...logic.values.data,searchSurveys: [createTestSurvey('1', 'Test Survey'), createTestSurvey('3', 'New Test')],searchSurveysCount: 2,})}).toMatchValues({- // Verify merged resultssearchedSurveys: expect.arrayContaining([expect.objectContaining({ id: '1' }),- expect.objectContaining({ id: '2' }),expect.objectContaining({ id: '3' }),]),})diff --git a/frontend/src/scenes/surveys/surveysLogic.tsx b/frontend/src/scenes/surveys/surveysLogic.tsxindex d651159b8ba5..59169fc6ad45 100644--- a/frontend/src/scenes/surveys/surveysLogic.tsx+++ b/frontend/src/scenes/surveys/surveysLogic.tsx@@ -9,7 +9,6 @@ import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic as enabledFlagLogic } from 'lib/logic/featureFlagLogic'import { pluralize } from 'lib/utils'-import { createFuse } from 'lib/utils/fuseSearch'import { sceneConfigurations } from 'scenes/scenes'import { Scene } from 'scenes/sceneTypes'import { SURVEY_PAGE_SIZE } from 'scenes/surveys/constants'@@ -91,12 +90,11 @@ function mergeSearchSurveysData(response: CountedPaginatedResponse<Survey>,appendResults = false): SurveyDataState {- if (response.results.length === 0) {+ if (appendResults && response.results.length === 0) {return currentData}- const searchSurveys =- appendResults && response.results ? [...currentData.searchSurveys, ...response.results] : response.results+ const searchSurveys = appendResults ? [...currentData.searchSurveys, ...response.results] : response.resultsreturn {...currentData,@@ -175,11 +173,6 @@ export const surveysLogic = kea<surveysLogicType>([return mergeSearchSurveysData(values.data, { results: [], count: 0 })}- // Only do backend search if we have more total items than the page size- if (values.data.surveysCount <= SURVEY_PAGE_SIZE) {- return values.data- }-const response = await api.surveys.list({limit: SURVEY_PAGE_SIZE,search: trimmedSearchTerm,@@ -411,38 +404,16 @@ export const surveysLogic = kea<surveysLogicType>([router.actions.push(urls.survey(toolOutput.survey_id) + '?edit=true')}},- setSearchTerm: async ({ searchTerm }, breakpoint) => {- await breakpoint(300) // Debounce for 300ms- if (searchTerm && values.data.surveysCount > SURVEY_PAGE_SIZE) {- actions.loadSearchResults()- }+ setSearchTerm: async (_, breakpoint) => {+ await breakpoint(300)+ actions.loadSearchResults()},})),selectors({searchedSurveys: [(selectors) => [selectors.data, selectors.searchTerm, selectors.filters],(data, searchTerm, filters) => {- let searchedSurveys = data.surveys-- if (searchTerm) {- // Always do frontend search first for better UX- const fuseResults = createFuse(searchedSurveys, {- keys: ['key', 'name'],- ignoreLocation: true,- })- .search(searchTerm)- .map((result) => result.item)-- // If we have backend search results (triggered when total count > page size)- // merge them with frontend results, removing duplicates- if (data.searchSurveys.length > 0) {- const seenIds = new Set(fuseResults.map((s) => s.id))- const uniqueBackendResults = data.searchSurveys.filter((s) => !seenIds.has(s.id))- searchedSurveys = [...fuseResults, ...uniqueBackendResults]- } else {- searchedSurveys = fuseResults- }- }+ let searchedSurveys = searchTerm?.trim() ? data.searchSurveys : data.surveysconst { status, type, created_by, archived } = filtersif (status !== 'any') {diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 613d8a6f4440..fe4fbdc4ae91 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -1,4 +1,5 @@import re+import builtinsfrom contextlib import contextmanagerfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional, TypedDict, cast@@ -6,9 +7,11 @@ 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 Min+from django.db.models import F, Min, Q, QuerySet, Value+from django.db.models.functions import Coalescefrom django.http import HttpRequest, HttpResponsefrom django.shortcuts import renderfrom django.utils.text import slugify@@ -30,8 +33,9 @@ from drf_spectacular.utils import ()from loginas.utils import is_impersonated_sessionfrom nanoid import generate+from opentelemetry import tracefrom posthoganalytics import capture_exception-from rest_framework import exceptions, filters, request, serializers, status, viewsets+from rest_framework import exceptions, request, serializers, status, viewsetsfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -52,6 +56,13 @@ from 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.models import Actionfrom posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_response@@ -79,6 +90,7 @@ from ee.surveys.summaries.headline_summary import generate_survey_headline# Constants for better maintainabilitylogger = structlog.get_logger(__name__)+tracer = trace.get_tracer(__name__)CACHE_TIMEOUT_SECONDS = 300DISPLAY_LANGUAGE_QUERY_PARAM = "display_language"DISPLAY_LANGUAGE_RE = re.compile(r"^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,3}$")@@ -1631,15 +1643,23 @@ class SurveySerializerCreateUpdateOnlySchema(SurveySerializerCreateUpdateOnly):@extend_schema_view(create=extend_schema(request=SurveySerializerCreateUpdateOnlySchema),partial_update=extend_schema(request=SurveySerializerCreateUpdateOnlySchema),+ list=extend_schema(+ parameters=[+ OpenApiParameter(+ name="search",+ type=OpenApiTypes.STR,+ description="Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.",+ ),+ ],+ ),)class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):scope_object = "survey"queryset = Survey.objects.select_related("linked_flag", "linked_insight", "targeting_flag", "internal_targeting_flag").all()- filter_backends = [DjangoFilterBackend, filters.SearchFilter]+ filter_backends = [DjangoFilterBackend]filterset_fields = ["archived"]- search_fields = ["name", "description"]def get_serializer_class(self) -> type[serializers.Serializer]:if self.request.method == "POST" or self.request.method == "PATCH":@@ -1648,7 +1668,59 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.return SurveySerializerdef safely_get_queryset(self, queryset):- return queryset.exclude(product_tour__isnull=False)+ queryset = queryset.exclude(product_tour__isnull=False)+ if self.action == "list":+ search = self.request.GET.get("search")+ if search:+ if len(search) > MAX_SEARCH_LENGTH:+ raise serializers.ValidationError(+ {"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."}+ )+ queryset = self._apply_search(queryset, search)+ return queryset++ @tracer.start_as_current_span("SurveyViewSet.list")+ def list(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:+ response = super().list(request, *args, **kwargs)+ if request.query_params.get("search"):+ data = response.data if isinstance(response.data, dict) else {}+ results_len = data.get("count", len(data.get("results", [])))+ span = trace.get_current_span()+ span.set_attribute("survey.search.result_count", results_len)+ span.set_attribute("survey.search.empty", results_len == 0)+ return response++ @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")+ )def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:instance = self.get_object()@@ -1673,7 +1745,7 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.return super().destroy(request, *args, **kwargs)- def _get_partial_responses_filter(self, base_conditions_sql: list[str]) -> str:+ def _get_partial_responses_filter(self, base_conditions_sql: builtins.list[str]) -> str:unique_uuids_subquery = get_unique_survey_event_uuids_sql_subquery(base_conditions_sql=base_conditions_sql,)@@ -1795,7 +1867,7 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.)def _process_survey_results(- self, results: list[tuple[str, int, int, datetime | None, datetime | None]]+ self, results: builtins.list[tuple[str, int, int, datetime | None, datetime | None]]) -> SurveyStats:"""Process raw survey event results into stats format.diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 850bed6884fc..ba80aeae225a 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -19,6 +19,7 @@ from unittest.mock import ANY, patchfrom django.test import override_settingsfrom nanoid import generate+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTest@@ -2929,6 +2930,125 @@ class TestSurvey(APIBaseTest):activity_response = self.client.get(f"/api/projects/{self.team.pk}/surveys/{survey.id}/activity/")self.assertEqual(activity_response.status_code, status.HTTP_403_FORBIDDEN)+ @parameterized.expand(+ [+ (+ "exact match wins over partial matches",+ ["Ad Sales", "Email Sales", "Sales", "Sales Funnel", "Weekly Sales", "Unrelated"],+ "Sales",+ "Sales",+ ["Unrelated"],+ ),+ (+ "typo / transposition still matches via trigram",+ ["Customer feedback", "Unrelated"],+ "feeback",+ "Customer feedback",+ ["Unrelated"],+ ),+ (+ "prefix-as-you-type",+ ["Marketing survey", "Engineering survey"],+ "Marke",+ "Marketing survey",+ ["Engineering survey"],+ ),+ (+ "case-insensitive: lower",+ ["NPS Survey", "Engineering survey"],+ "nps",+ "NPS Survey",+ ["Engineering survey"],+ ),+ (+ "case-insensitive: upper",+ ["NPS Survey", "Engineering survey"],+ "NPS",+ "NPS Survey",+ ["Engineering survey"],+ ),+ ]+ )+ def test_list_filter_by_search_relevance(self, _name, survey_names, search, expected_first, excluded):+ 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}")+ assert response.status_code == status.HTTP_200_OK+ result_names = [r["name"] for r in response.json()["results"]]++ assert result_names, f"expected at least one match for {search!r}, got nothing"+ assert result_names[0] == expected_first, f"expected {expected_first!r} first, got {result_names}"+ for name in excluded:+ assert name not in result_names, f"expected {name!r} excluded, got {result_names}"++ def test_list_filter_by_search_matches_description_with_lower_rank_than_name(self):+ name_match = Survey.objects.create(team=self.team, name="revenue", type="popover", questions=[])+ description_match = Survey.objects.create(+ team=self.team,+ name="Q4 review",+ description="Quarterly revenue survey",+ type="popover",+ questions=[],+ )+ Survey.objects.create(team=self.team, name="Unrelated", type="popover", questions=[])++ response = self.client.get(f"/api/projects/{self.team.id}/surveys/?search=revenue")+ assert response.status_code == status.HTTP_200_OK+ result_ids = [r["id"] for r in response.json()["results"]]++ assert result_ids[:2] == [str(name_match.id), str(description_match.id)]+ assert all(r["name"] != "Unrelated" for r in response.json()["results"])++ @parameterized.expand(+ [+ ("whitespace-only", " "),+ ("empty", ""),+ ]+ )+ def test_list_filter_by_search_blank_returns_all(self, _name, search):+ 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}")+ assert response.status_code == status.HTTP_200_OK+ result_ids = {r["id"] for r in response.json()["results"]}++ assert {str(a.id), str(b.id)}.issubset(result_ids)++ @parameterized.expand(+ [+ ("plain symbols", "&|!"),+ ("sql-injection-shaped", "'; DROP TABLE--"),+ ]+ )+ def test_list_filter_by_search_pathological_input_does_not_500(self, _name, search):+ Survey.objects.create(team=self.team, name="Survey overview", type="popover", questions=[])++ response = self.client.get(f"/api/projects/{self.team.id}/surveys/", {"search": search})+ assert response.status_code == status.HTTP_200_OK++ def test_list_filter_by_search_nul_bytes_do_not_500(self):+ Survey.objects.create(team=self.team, name="Alpha", type="popover", questions=[])+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/", {"search": "\x00\x00\x00"})+ assert response.status_code == status.HTTP_200_OK++ @parameterized.expand(+ [+ ("at cap (200)", 200, status.HTTP_200_OK),+ ("just over cap (201)", 201, status.HTTP_400_BAD_REQUEST),+ ("very long (10k)", 10_000, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_list_filter_by_search_enforces_length_cap(self, _name, length, expected_status):+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/", {"search": "a" * length})+ assert response.status_code == expected_status++ if expected_status == status.HTTP_400_BAD_REQUEST:+ body = response.json()+ 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']}"+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 4601a539f2f5..68042922061e 100644--- a/products/surveys/frontend/generated/api.schemas.ts+++ b/products/surveys/frontend/generated/api.schemas.ts@@ -2005,7 +2005,7 @@ export type SurveysListParams = {*/offset?: number/**- * A search term.+ * Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.*/search?: string}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 660e68b427e8..39812b156d89 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45093,7 +45093,7 @@ export namespace Schemas {*/offset?: number;/**- * A search term.+ * Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.*/search?: string;};diff --git a/services/mcp/src/generated/surveys/api.ts b/services/mcp/src/generated/surveys/api.tsindex 7f23924cd9a6..bc44024145aa 100644--- a/services/mcp/src/generated/surveys/api.ts+++ b/services/mcp/src/generated/surveys/api.ts@@ -20,7 +20,12 @@ export const SurveysListQueryParams = /* @__PURE__ */ zod.object({archived: zod.boolean().optional(),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),- search: zod.string().optional().describe('A search term.'),+ search: zod+ .string()+ .optional()+ .describe(+ 'Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.'+ ),})export const SurveysCreateParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/surveys-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/surveys-get-all.jsonindex 6f10d1445173..72cef9ba35b0 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/surveys-get-all.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/surveys-get-all.json@@ -13,7 +13,7 @@"type": "number"},"search": {- "description": "A search term.",+ "description": "Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.","type": "string"}},