: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 dashboards (#62382)
Paul D'Ambra93258e221080
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex c58c57184f42..999afeb65d45 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -306,6 +306,78 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):f"expected error detail to mention the cap, got {response['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 dashboard", "com.acme.billing"),+ ]+ )+ def test_list_filter_by_search_matches_literal_substring_below_trigram_threshold(+ self, _name, dashboard_name, search+ ):+ matching_id, _ = self.dashboard_api.create_dashboard({"name": dashboard_name})+ self.dashboard_api.create_dashboard({"name": "Totally unrelated"})++ response = self.dashboard_api.list_dashboards(query_params={"search": search})+ results = response["results"]++ match_type_by_id = {d["id"]: d["search_match_type"] for d in results}+ assert match_type_by_id.get(matching_id) == "exact", (+ "a literal substring must match and be labelled exact even when it scores below the trigram thresholds"+ )+ assert all(d["name"] != "Totally unrelated" for d in results)++ def test_list_filter_by_search_returns_exact_first_with_match_type(self):+ for name in ("dashboard overview", "sales dashboard", "dahsboard metrics", "Engineering metrics"):+ self.dashboard_api.create_dashboard({"name": name})++ response = self.dashboard_api.list_dashboards(query_params={"search": "dashboard"})+ results = response["results"]++ match_type_by_name = {d["name"]: d["search_match_type"] for d in results}+ assert match_type_by_name == {+ "dashboard overview": "exact",+ "sales dashboard": "exact",+ "dahsboard metrics": "similar",+ }++ match_types = [d["search_match_type"] for d 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):+ self.dashboard_api.create_dashboard({"name": "Alpha"})++ response = self.dashboard_api.list_dashboards()+ results = response["results"]++ assert results+ assert all("search_match_type" not in d for d in results)++ def test_list_filter_by_search_matches_tag_content(self):+ tagged_id, _ = self.dashboard_api.create_dashboard({"name": "Q4 review", "tags": ["revenue-forecast"]})+ self.dashboard_api.create_dashboard({"name": "Unrelated", "tags": ["marketing"]})++ response = self.dashboard_api.list_dashboards(query_params={"search": "revenue-forecast"})+ results = response["results"]++ match_type_by_id = {d["id"]: d["search_match_type"] for d in results}+ assert match_type_by_id.get(tagged_id) == "exact", "a dashboard whose tag name contains the term must match"+ assert all(d["name"] != "Unrelated" for d in results)++ def test_list_filter_by_search_does_not_duplicate_dashboard_with_multiple_matching_tags(self):+ target_id, _ = self.dashboard_api.create_dashboard(+ {"name": "needle", "tags": ["needle-tag-a", "needle-tag-b", "needle-tag-c"]}+ )++ response = self.dashboard_api.list_dashboards(query_params={"search": "needle"})+ matching = [d["id"] for d in response["results"] if d["id"] == target_id]++ assert len(matching) == 1, (+ f"search=needle must return the dashboard once even though three tags + the name match it; "+ f"got {len(matching)} copies."+ )+def test_list_includes_last_viewed_at_from_filesystem_logs(self):dashboard_recent_id, _ = self.dashboard_api.create_dashboard({"name": "Recently viewed"})dashboard_unseen_id, _ = self.dashboard_api.create_dashboard({"name": "Never viewed"})diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.pyindex 4b19d1cdb75a..a63843e3a93f 100644--- a/posthog/api/test/test_search_match_type_mixin.py+++ b/posthog/api/test/test_search_match_type_mixin.py@@ -4,6 +4,7 @@ from rest_framework import serializersfrom posthog.api.organization_member import OrganizationMemberSerializerfrom posthog.api.shared import SearchMatchTypeSerializerMixin+from products.dashboards.backend.api.dashboard import DashboardBasicSerializerfrom products.product_analytics.backend.api.insight import InsightBasicSerializer, InsightSerializer# Each product that migrates its saved-list search onto apply_trigram_search appends its@@ -12,6 +13,7 @@ SEARCH_LIST_SERIALIZERS = [("insight_basic", InsightBasicSerializer),("insight", InsightSerializer),("organization_member", OrganizationMemberSerializer),+ ("dashboard_basic", DashboardBasicSerializer),]diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 898397ca58af..ae315029b6c4 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -11,12 +11,11 @@ from enum import StrEnumfrom typing import Any, Optional, TypedDict, castfrom django.conf import settings-from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarityfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.core.validators import URLValidatorfrom django.db import IntegrityError, transactionfrom django.db.models import CharField, Count, DateTimeField, F, FilteredRelation, Prefetch, Q, QuerySet, Value-from django.db.models.functions import Cast, Coalesce+from django.db.models.functions import Castfrom django.http import StreamingHttpResponsefrom django.shortcuts import get_object_or_404from django.utils.timezone import now@@ -41,7 +40,7 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.monitoring import Feature, monitorfrom posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_paramfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.shared import UserBasicSerializer+from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.api.utils import actionfrom posthog.clickhouse.client.async_task_chain import task_chain_context@@ -50,13 +49,7 @@ from posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers import create_dashboard_from_templatefrom posthog.helpers.dashboard_templates import create_from_template, dashboard_template_from_creation_payload-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 ActivityScope, Detail, changes_between, log_activityfrom posthog.models.file_system.file_system import create_or_update_file, delete_filefrom posthog.models.quick_filter import QuickFilter@@ -818,6 +811,7 @@ class AddDashboardWidgetsBatchResponseSerializer(serializers.Serializer):class DashboardBasicSerializer(+ SearchMatchTypeSerializerMixin,TaggedItemSerializerMixin,serializers.ModelSerializer,UserPermissionsSerializerMixin,@@ -852,6 +846,7 @@ class DashboardBasicSerializer("access_control_version","last_refresh","team_id",+ "search_match_type",]read_only_fields = fieldsextra_kwargs = {@@ -1787,11 +1782,12 @@ class DashboardSerializer(DashboardMetadataSerializer):OpenApiTypes.STR,location=OpenApiParameter.QUERY,description=(- "Optional. Fuzzy match against dashboard `name` and `description` using Postgres trigram "- "word similarity (handles typos, transpositions, and prefix-as-you-type). `name` matches "- "rank above `description` matches. Results are ordered by relevance, then pinned status, "- "then name. When omitted, dashboards are ordered by pinned status then alphabetical name. "- "Capped at 200 characters; longer queries return a 400 error."+ "Optional. Match against dashboard `name`, `description`, and tag names. Returns "+ "case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, "+ "prefix-as-you-type) together, ordered exact-first, then pinned status, then name; each "+ "result's `search_match_type` is `exact` or `similar`. When omitted, dashboards are ordered "+ "by pinned status then alphabetical name. Capped at 200 characters; longer queries return a "+ "400 error."),),],@@ -1858,39 +1854,13 @@ class DashboardsViewSet(@staticmethod@tracer.start_as_current_span("DashboardViewSet._apply_search")def _apply_search(queryset: QuerySet, search: str) -> QuerySet:- search = normalize_search_term(search)- span = trace.get_current_span()- span.set_attribute("dashboard.search.length", len(search))- if not search:- return queryset-- # Word similarity (`<%`) drives match/no-match — it's index-accelerated and handles- # prefix-as-you-type and substring matches. Full-string similarity is added as a- # tiebreak so an exact name match outranks rows that merely *contain* the search word.- # `Dashboard.name` is nullable; coalesce each component to 0.0 so a NULL-name row- # matched only on description doesn't end up with a NULL `_search_score` (which- # Postgres orders NULLS FIRST in DESC, putting unnamed rows wrongly at the top).- 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", "-pinned", "name")+ return apply_trigram_search(+ queryset,+ search,+ span_prefix="dashboard.search",+ fields=(NAME_FIELD, DESCRIPTION_FIELD),+ include_tag_search=True,+ tiebreakers=("-pinned", "name"),)@tracer.start_as_current_span("DashboardViewSet.dangerously_get_queryset")diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 824e13fd0270..899d3ea336fb 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -208,6 +208,13 @@ export const EffectivePrivilegeLevelEnumApi = {Number37: 37,} as const+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]++export const SearchMatchTypeEnumApi = {+ Exact: 'exact',+ Similar: 'similar',+} as const+/*** Serializer mixin that handles tags for objects.*/@@ -248,6 +255,8 @@ export interface DashboardBasicApi {/** @nullable */readonly last_refresh: string | nullreadonly team_id: number+ /** 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 PaginatedDashboardBasicListApi {@@ -7554,13 +7563,6 @@ export interface DashboardTileBasicApi {deleted?: boolean | null}-export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]--export const SearchMatchTypeEnumApi = {- Exact: 'exact',- Similar: 'similar',-} as const-/*** @nullable*/@@ -8157,7 +8159,7 @@ export type DashboardsListParams = {*/offset?: number/**- * Optional. Fuzzy match against dashboard `name` and `description` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). `name` matches rank above `description` matches. Results are ordered by relevance, then pinned status, then name. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.+ * Optional. Match against dashboard `name`, `description`, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered exact-first, then pinned status, then name; each result's `search_match_type` is `exact` or `similar`. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.*/search?: string}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex bac527b32e2b..ad5d0273f2f3 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12465,6 +12465,8 @@ export namespace Schemas {/** @nullable */readonly last_refresh: string | null;readonly team_id: number;+ /** 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 DashboardCollaborator {@@ -43059,7 +43061,7 @@ export namespace Schemas {*/offset?: number;/**- * Optional. Fuzzy match against dashboard `name` and `description` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). `name` matches rank above `description` matches. Results are ordered by relevance, then pinned status, then name. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.+ * Optional. Match against dashboard `name`, `description`, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered exact-first, then pinned status, then name; each result's `search_match_type` is `exact` or `similar`. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.*/search?: string;};@@ -48473,7 +48475,7 @@ export namespace Schemas {*/offset?: number;/**- * Optional. Fuzzy match against dashboard `name` and `description` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). `name` matches rank above `description` matches. Results are ordered by relevance, then pinned status, then name. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.+ * Optional. Match against dashboard `name`, `description`, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered exact-first, then pinned status, then name; each result's `search_match_type` is `exact` or `similar`. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.*/search?: string;};diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.tsindex 0e7b8b6e1e92..9994d7741b3c 100644--- a/services/mcp/src/generated/dashboards/api.ts+++ b/services/mcp/src/generated/dashboards/api.ts@@ -24,7 +24,7 @@ export const DashboardsListQueryParams = /* @__PURE__ */ zod.object({.string().optional().describe(- 'Optional. Fuzzy match against dashboard `name` and `description` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). `name` matches rank above `description` matches. Results are ordered by relevance, then pinned status, then name. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.'+ "Optional. Match against dashboard `name`, `description`, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered exact-first, then pinned status, then name; each result's `search_match_type` is `exact` or `similar`. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error."),})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-get-all.jsonindex ac20b9ffd7a1..1eb7b62a21e6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-get-all.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-get-all.json@@ -10,7 +10,7 @@"type": "number"},"search": {- "description": "Optional. Fuzzy match against dashboard `name` and `description` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). `name` matches rank above `description` matches. Results are ordered by relevance, then pinned status, then name. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.",+ "description": "Optional. Match against dashboard `name`, `description`, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered exact-first, then pinned status, then name; each result's `search_match_type` is `exact` or `similar`. When omitted, dashboards are ordered by pinned status then alphabetical name. Capped at 200 characters; longer queries return a 400 error.","type": "string"}},