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.

feat(cohorts): fuzzy trigram search on cohort list endpoint (#66999)

Paul D'Ambraaa9eea440622
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 18c8d76b316c..9ad5ef8b274d 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -37,7 +37,7 @@ from posthog.hogql.property import property_to_expr
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.services.flags_service import FlagVersionConflictError, batch_evaluate_flag_for_team
-from posthog.api.shared import UserBasicSerializer
+from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.api.utils import action
from posthog.cdp.filters import build_behavioral_event_expr
from posthog.clickhouse.query_tagging import Feature, tag_queries
@@ -45,6 +45,7 @@ from posthog.constants import LIMIT, OFFSET
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
+from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH, NAME_FIELD, apply_trigram_search, normalize_search_term
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.metrics import LABEL_TEAM_ID
@@ -515,7 +516,7 @@ class CohortFiltersField(serializers.JSONField):
pass
-class CohortSerializer(serializers.ModelSerializer):
+class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
earliest_timestamp_func = earliest_timestamp_func
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
@@ -553,6 +554,7 @@ class CohortSerializer(serializers.ModelSerializer):
"is_static",
"cohort_type",
"experiment_set",
+ "search_match_type",
"_create_in_folder",
"_create_static_person_ids",
]
@@ -1374,6 +1376,18 @@ def get_cohorts_using_cohort(cohort: Cohort) -> QuerySet[Cohort]:
@extend_schema_view(
list=extend_schema(
parameters=[
+ OpenApiParameter(
+ name="search",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ description=(
+ "Optional. Match against cohort `name`. Returns case-insensitive substring matches and "
+ "fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered "
+ "exact-first then by relevance; each result's `search_match_type` is `exact` or `similar`. "
+ "When omitted, cohorts are ordered newest-first. Capped at 200 characters; longer queries "
+ "return a 400 error."
+ ),
+ ),
OpenApiParameter(
name="hide_behavioral_cohorts",
type=OpenApiTypes.BOOL,
@@ -1409,8 +1423,12 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
context["basic_cohort_list"] = self._is_basic_list_request()
return context
- def _filter_request(self, request: Request, queryset: QuerySet) -> QuerySet:
+ def _filter_request(self, request: Request, queryset: QuerySet) -> tuple[QuerySet, bool]:
+ # Returns (queryset, search_ordered). `search_ordered` is True only when a non-blank
+ # search applied trigram relevance ordering, so the caller knows not to re-impose the
+ # default ordering on top of it.
filters = request.GET.dict()
+ search_ordered = False
for key in filters:
if key == "type":
@@ -1422,11 +1440,25 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
elif key == "created_by_id":
queryset = queryset.filter(created_by_id=request.GET["created_by_id"])
elif key == "search":
- queryset = queryset.filter(name__icontains=request.GET["search"])
+ search = request.GET["search"]
+ if len(search) > MAX_SEARCH_LENGTH:
+ raise serializers.ValidationError(
+ {"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."}
+ )
+ if normalize_search_term(search):
+ queryset = apply_trigram_search(
+ queryset,
+ search,
+ span_prefix="cohort.search",
+ fields=(NAME_FIELD,),
+ tiebreakers=("-created_at",),
+ )
+ search_ordered = True
- return queryset
+ return queryset, search_ordered
def safely_get_queryset(self, queryset) -> QuerySet:
+ search_ordered = False
if self.action == "list":
queryset = queryset.filter(deleted=False)
@@ -1447,7 +1479,7 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
queryset = queryset.exclude(id__in=behavioral_cohort_ids)
# add additional filters provided by the client
- queryset = self._filter_request(self.request, queryset)
+ queryset, search_ordered = self._filter_request(self.request, queryset)
# `?basic=true` callers never read these columns, so skip reading them
# off disk (the serializer drops them too; see CohortSerializer.__init__).
@@ -1467,13 +1499,17 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
# `created_by` and `team` are forward FKs, so `select_related` JOINs them in
# one query instead of the two extra round-trips `prefetch_related` costs.
# `experiment_set` is a reverse relation, so it stays prefetched.
- return (
+ queryset = (
queryset.annotate(last_error_code=last_error_code_subquery)
.select_related("created_by", "team")
.prefetch_related("experiment_set")
- .order_by("-created_at")
)
+ if not search_ordered:
+ queryset = queryset.order_by("-created_at")
+
+ return queryset
+
@extend_schema(
parameters=[
OpenApiParameter(
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 87033f5fb2be..46436af5af05 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -1586,32 +1586,76 @@ [email protected],
self.assertEqual(response.status_code, 200)
self.assertEqual(patch_calculate_cohort.call_count, 1)
- def test_cohort_list_with_search(self):
- self.team.app_urls = ["http://somewebsite.com"]
- self.team.save()
+ @parameterized.expand(
+ [
+ ("exact substring", "Power users", "Power users"),
+ ("partial word", "Power users", "Power"),
+ ("typo / transposition via trigram", "Power users", "Pwoer users"),
+ ("prefix-as-you-type", "Power users", "Pow"),
+ ("case-insensitive lower", "Power users", "power users"),
+ ("case-insensitive upper", "Power users", "POWER"),
+ ]
+ )
+ def test_cohort_list_search_matches(self, _name, cohort_name, search):
+ Cohort.objects.create(team=self.team, name=cohort_name, created_by=self.user)
+ Cohort.objects.create(team=self.team, name="Totally unrelated", created_by=self.user)
- create_person(team=self.team, properties={"prop": 5})
- create_person(team=self.team, properties={"prop": 6})
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts?search={search}").json()
+ result_names = [c["name"] for c in response["results"]]
- self.client.post(
- f"/api/projects/{self.team.id}/cohorts",
- data={"name": "cohort1", "groups": [{"properties": {"prop": 5}}]},
- )
+ assert cohort_name in result_names, f"expected {cohort_name!r} for search {search!r}, got {result_names}"
+ assert "Totally unrelated" not in result_names
- self.client.post(
- f"/api/projects/{self.team.id}/cohorts",
- data={"name": "cohort2", "groups": [{"properties": {"prop": 6}}]},
- )
+ def test_cohort_list_search_no_match_returns_empty(self):
+ Cohort.objects.create(team=self.team, name="Power users", created_by=self.user)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts?search=zzzznomatch").json()
+
+ assert response["results"] == []
+
+ def test_cohort_list_search_orders_exact_before_similar_and_labels_match_type(self):
+ exact = Cohort.objects.create(team=self.team, name="marketing", created_by=self.user)
+ similar = Cohort.objects.create(team=self.team, name="markteing", created_by=self.user)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts?search=marketing").json()
+ results = response["results"]
+ by_id = {c["id"]: c for c in results}
+
+ assert [c["id"] for c in results][:2] == [exact.id, similar.id]
+ assert by_id[exact.id]["search_match_type"] == "exact"
+ assert by_id[similar.id]["search_match_type"] == "similar"
+
+ def test_cohort_list_omits_search_match_type_when_not_searching(self):
+ Cohort.objects.create(team=self.team, name="Power users", created_by=self.user)
response = self.client.get(f"/api/projects/{self.team.id}/cohorts").json()
- self.assertEqual(len(response["results"]), 2)
- response = self.client.get(f"/api/projects/{self.team.id}/cohorts?search=cohort1").json()
- self.assertEqual(len(response["results"]), 1)
- self.assertEqual(response["results"][0]["name"], "cohort1")
+ assert all("search_match_type" not in c for c in response["results"])
- response = self.client.get(f"/api/projects/{self.team.id}/cohorts?search=nomatch").json()
- self.assertEqual(len(response["results"]), 0)
+ @parameterized.expand(
+ [
+ ("at cap", 200, status.HTTP_200_OK),
+ ("just over cap", 201, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_cohort_list_search_enforces_length_cap(self, _name, length, expected_status):
+ Cohort.objects.create(team=self.team, name="Power users", created_by=self.user)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts?search={'a' * length}")
+
+ assert response.status_code == expected_status
+ if expected_status == status.HTTP_400_BAD_REQUEST:
+ assert "200 characters" in response.json()["detail"]
+
+ @parameterized.expand([("whitespace", "%20%20"), ("empty", "")])
+ def test_cohort_list_blank_search_keeps_default_ordering(self, _name, search):
+ older = Cohort.objects.create(team=self.team, name="older", created_by=self.user)
+ newer = Cohort.objects.create(team=self.team, name="newer", created_by=self.user)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts?search={search}").json()
+
+ assert [c["id"] for c in response["results"]] == [newer.id, older.id]
+ assert all("search_match_type" not in c for c in response["results"])
def test_cohort_list_with_type_filter(self):
create_person(team=self.team, properties={"prop": 5})
diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.py
index 3a75a4feff6e..9098fb3adc49 100644
--- a/posthog/api/test/test_search_match_type_mixin.py
+++ b/posthog/api/test/test_search_match_type_mixin.py
@@ -1,6 +1,7 @@
from parameterized import parameterized
from rest_framework import serializers
+from posthog.api.cohort import CohortSerializer
from posthog.api.organization_member import OrganizationMemberSerializer
from posthog.api.shared import SearchMatchTypeSerializerMixin
@@ -23,6 +24,7 @@ SEARCH_LIST_SERIALIZERS = [
("survey", SurveySerializer),
("product_tour", ProductTourSerializer),
("alert", AlertSerializer),
+ ("cohort", CohortSerializer),
]
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index f685eed916bb..a96fb21d8f59 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -163,6 +163,13 @@ export const CohortTypeEnumApi = {
Analytical: 'analytical',
} as const
+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]
+
+export const SearchMatchTypeEnumApi = {
+ Exact: 'exact',
+ Similar: 'similar',
+} as const
+
export interface CohortApi {
readonly id: number
/**
@@ -203,6 +210,8 @@ export interface CohortApi {
* * `analytical` - analytical */
cohort_type?: CohortTypeEnumApi | BlankEnumApi | null
readonly experiment_set: readonly 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
_create_in_folder?: string
_create_static_person_ids?: string[]
}
@@ -256,6 +265,8 @@ export interface PatchedCohortApi {
* * `analytical` - analytical */
cohort_type?: CohortTypeEnumApi | BlankEnumApi | null
readonly experiment_set?: readonly 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
_create_in_folder?: string
_create_static_person_ids?: string[]
}
@@ -391,6 +402,10 @@ export type CohortsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * Optional. Match against cohort `name`. Returns case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered exact-first then by relevance; each result's `search_match_type` is `exact` or `similar`. When omitted, cohorts are ordered newest-first. Capped at 200 characters; longer queries return a 400 error.
+ */
+ search?: string
}
export type CohortsPersonsRetrieveParams = {
diff --git a/products/cohorts/mcp/tools.yaml b/products/cohorts/mcp/tools.yaml
index 44861b988241..f0ab63f7010a 100644
--- a/products/cohorts/mcp/tools.yaml
+++ b/products/cohorts/mcp/tools.yaml
@@ -124,8 +124,10 @@ tools:
description: >
List all cohorts in the project. Returns a summary of each cohort including id, name, description, count
- (person count), is_static (cohort type), and created_at timestamp. Use 'cohorts-retrieve' with the cohort ID
- to get full details including filters, calculation status,
+ (person count), is_static (cohort type), and created_at timestamp. To find a cohort by name, pass 'search'
+ rather than listing everything and filtering client-side — it matches the cohort name with fuzzy trigram
+ search (tolerates typos and partial words) and orders exact matches first. Use 'cohorts-retrieve' with the
+ cohort ID to get full details including filters, calculation status,
and query definition.
param_overrides:
@@ -133,6 +135,8 @@ tools:
cast: string-int
offset:
cast: string-int
+ search:
+ description: Find cohorts by name. Fuzzy trigram match (tolerates typos and partial words), exact matches ordered first.
hide_behavioral_cohorts:
description: Set true to exclude behavioral (event-based) cohorts — not usable in batch workflow audiences.
ui_app: cohort-list
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 641a6db06aea..40c2c8b0a345 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1520,7 +1520,7 @@
}
},
"cohorts-list": {
- "description": "List all cohorts in the project. Returns a summary of each cohort including id, name, description, count (person count), is_static (cohort type), and created_at timestamp. Use 'cohorts-retrieve' with the cohort ID to get full details including filters, calculation status,\nand query definition.",
+ "description": "List all cohorts in the project. Returns a summary of each cohort including id, name, description, count (person count), is_static (cohort type), and created_at timestamp. To find a cohort by name, pass 'search' rather than listing everything and filtering client-side — it matches the cohort name with fuzzy trigram search (tolerates typos and partial words) and orders exact matches first. Use 'cohorts-retrieve' with the cohort ID to get full details including filters, calculation status,\nand query definition.",
"category": "Cohorts",
"feature": "cohorts",
"summary": "List all cohorts",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c420ee325d5f..f1ffe783fc14 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1550,7 +1550,7 @@
}
},
"cohorts-list": {
- "description": "List all cohorts in the project. Returns a summary of each cohort including id, name, description, count (person count), is_static (cohort type), and created_at timestamp. Use 'cohorts-retrieve' with the cohort ID to get full details including filters, calculation status,\nand query definition.",
+ "description": "List all cohorts in the project. Returns a summary of each cohort including id, name, description, count (person count), is_static (cohort type), and created_at timestamp. To find a cohort by name, pass 'search' rather than listing everything and filtering client-side — it matches the cohort name with fuzzy trigram search (tolerates typos and partial words) and orders exact matches first. Use 'cohorts-retrieve' with the cohort ID to get full details including filters, calculation status,\nand query definition.",
"category": "Cohorts",
"feature": "cohorts",
"summary": "List all cohorts",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index aa7cd2f46047..838973b06abb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13002,6 +13002,8 @@ export namespace Schemas {
* * `analytical` - analytical */
cohort_type?: CohortTypeEnum | BlankEnum | null;
readonly experiment_set: readonly 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;
_create_in_folder?: string;
_create_static_person_ids?: string[];
}
@@ -35876,6 +35878,8 @@ export namespace Schemas {
* * `analytical` - analytical */
cohort_type?: CohortTypeEnum | BlankEnum | null;
readonly experiment_set?: readonly 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;
_create_in_folder?: string;
_create_static_person_ids?: string[];
}
@@ -60318,6 +60322,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Optional. Match against cohort `name`. Returns case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered exact-first then by relevance; each result's `search_match_type` is `exact` or `similar`. When omitted, cohorts are ordered newest-first. Capped at 200 characters; longer queries return a 400 error.
+ */
+ search?: string;
};
export type CohortsPersonsRetrieveParams = {
diff --git a/services/mcp/src/generated/cohorts/api.ts b/services/mcp/src/generated/cohorts/api.ts
index 0025720438bb..8b841ad7d7a1 100644
--- a/services/mcp/src/generated/cohorts/api.ts
+++ b/services/mcp/src/generated/cohorts/api.ts
@@ -31,6 +31,12 @@ export const CohortsListQueryParams = /* @__PURE__ */ zod.object({
),
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(
+ "Optional. Match against cohort `name`. Returns case-insensitive substring matches and fuzzy trigram matches (typos, transpositions, prefix-as-you-type) together, ordered exact-first then by relevance; each result's `search_match_type` is `exact` or `similar`. When omitted, cohorts are ordered newest-first. Capped at 200 characters; longer queries return a 400 error."
+ ),
})
export const CohortsCreateParams = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/tools/generated/cohorts.ts b/services/mcp/src/tools/generated/cohorts.ts
index f6f3bad6f856..b5142fad8aba 100644
--- a/services/mcp/src/tools/generated/cohorts.ts
+++ b/services/mcp/src/tools/generated/cohorts.ts
@@ -82,6 +82,9 @@ const cohortsCreate = (): ToolBase<typeof CohortsCreateSchema, WithPostHogUrl<Sc
const CohortsListSchema = CohortsListQueryParams.extend({
limit: z.preprocess(castStringToInt, CohortsListQueryParams.shape['limit']).optional(),
offset: z.preprocess(castStringToInt, CohortsListQueryParams.shape['offset']).optional(),
+ search: CohortsListQueryParams.shape['search'].describe(
+ 'Find cohorts by name. Fuzzy trigram match (tolerates typos and partial words), exact matches ordered first.'
+ ),
hide_behavioral_cohorts: CohortsListQueryParams.shape['hide_behavioral_cohorts'].describe(
'Set true to exclude behavioral (event-based) cohorts — not usable in batch workflow audiences.'
),
@@ -101,6 +104,7 @@ const cohortsList = (): ToolBase<typeof CohortsListSchema, WithPostHogUrl<Schema
hide_behavioral_cohorts: params.hide_behavioral_cohorts,
limit: params.limit,
offset: params.offset,
+ search: params.search,
},
})
const filtered = {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json
index 275fc29b5981..c9b052c3a794 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json
@@ -16,6 +16,10 @@
"offset": {
"description": "The initial index from which to return the results.",
"type": "number"
+ },
+ "search": {
+ "description": "Find cohorts by name. Fuzzy trigram match (tolerates typos and partial words), exact matches ordered first.",
+ "type": "string"
}
},
"type": "object"