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(taxonomy): offer fuzzy event matches after empty search (#119223)

Paul D'Ambra2b13ae2c0d26
diff --git a/docs/internal/taxonomic-filter-search.md b/docs/internal/taxonomic-filter-search.md
index 5d301105e2ed..e06dd671a4d4 100644
--- a/docs/internal/taxonomic-filter-search.md
+++ b/docs/internal/taxonomic-filter-search.md
@@ -17,6 +17,8 @@ A failed search does not offer an uncaptured event name, and it does not change
When a caller allows custom event names, a successful empty search offers "Use event name".
Pressing Enter in the search input selects that custom event name.
The classic picker does not infer ingestion history from a filtered definition list.
+Event and Custom Events searches keep case-insensitive substring matches first. If the filtered event-definition search has no matches, it can return similar event names. The pickers ask for similar names only while the `taxonomic-filter-fuzzy-event-search` feature flag is on. Hidden and excluded events stay out of both match sets.
+A picker that allows custom event names does not ask for similar names, because "Use event name" shows only when nothing matches.
Scoped property searches return properties associated with the selected events. A separate unscoped request counts matches across the project so the picker can offer an expansion to other properties.
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
index 44af9aa98400..268ba6ab0d3c 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
@@ -323,6 +323,7 @@ export function useTaxonomicFilter(opts: UseTaxonomicFilterOptions): TaxonomicFi
suggestedFiltersLabel,
excludedProperties,
includeHiddenEvents,
+ allowNonCapturedEvents,
propertyAllowList,
showNumericalPropsOnly,
selectedProperties,
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.test.tsx
index 63672826e0d6..dd44ab577449 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.test.tsx
@@ -2,6 +2,9 @@ import { cleanup, renderHook } from '@testing-library/react'
import { Provider } from 'kea'
import { ReactNode } from 'react'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { useMocks } from '~/mocks/jest'
import { actionsModel } from '~/models/actionsModel'
import { groupsModel } from '~/models/groupsModel'
@@ -168,6 +171,26 @@ describe('useTaxonomicGroupsContext', () => {
expect(types.has(TaxonomicFilterGroupType.SuggestedFilters)).toBe(true)
})
+ it.each([
+ [TaxonomicFilterGroupType.Events, true, false, 'true'],
+ [TaxonomicFilterGroupType.CustomEvents, true, false, 'true'],
+ [TaxonomicFilterGroupType.Events, true, true, 'false'],
+ [TaxonomicFilterGroupType.CustomEvents, true, true, 'false'],
+ [TaxonomicFilterGroupType.Events, false, false, 'false'],
+ [TaxonomicFilterGroupType.CustomEvents, false, false, 'false'],
+ ])(
+ 'for %s with the flag %p and allowNonCapturedEvents %p, fuzzy_search is %p',
+ (groupType, flagEnabled, allowNonCapturedEvents, expected) => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.TAXONOMIC_FILTER_FUZZY_EVENT_SEARCH]: flagEnabled,
+ })
+ const { result } = renderHook(() => useTaxonomicGroupsContext({ allowNonCapturedEvents }), { wrapper })
+ const group = buildTaxonomicGroups(result.current).find((item) => item.type === groupType)
+ expect(new URL(group!.endpoint!, 'http://localhost').searchParams.get('fuzzy_search')).toBe(expected)
+ }
+ )
+
it('makes exception properties commit as event property filters', () => {
const { result } = renderHook(() => useTaxonomicGroupsContext({}), { wrapper })
const exceptionGroup = buildTaxonomicGroups(result.current).find(
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts
index 3ddf29643396..de7919a57f83 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts
@@ -41,6 +41,7 @@ import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joins
* `TaxonomicFilterProps` — only the fields that affect group definitions.
*/
export interface UseTaxonomicGroupsContextInput {
+ allowNonCapturedEvents?: boolean
eventNames?: string[]
/** Requested group types — read by group definitions that adapt to which tabs are present. */
taxonomicGroupTypes?: TaxonomicFilterGroupType[]
@@ -161,6 +162,7 @@ export function useTaxonomicGroupsContext(input: UseTaxonomicGroupsContextInput)
// taxonomic-groups builder accepts.
featureFlags: featureFlags as unknown as BuildTaxonomicGroupsContext['featureFlags'],
includeHiddenEvents: input.includeHiddenEvents,
+ allowNonCapturedEvents: input.allowNonCapturedEvents ?? false,
}
}, [
currentTeam,
@@ -184,6 +186,7 @@ export function useTaxonomicGroupsContext(input: UseTaxonomicGroupsContextInput)
input.suggestedFiltersLabel,
input.excludedProperties,
input.includeHiddenEvents,
+ input.allowNonCapturedEvents,
input.propertyAllowList,
input.showNumericalPropsOnly,
input.maxContextOptions,
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
index f1004f0e480d..d4f62c611fcf 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
@@ -17,6 +17,7 @@ import {
} from 'lib/components/TaxonomicFilter/taxonomicFilterLogic'
import { TaxonomicFilterGroupType, TaxonomicFilterLogicProps } from 'lib/components/TaxonomicFilter/types'
import { getMCPPropertyFilterOptions } from 'lib/components/TaxonomicFilter/utils/mcpProperties'
+import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -122,6 +123,30 @@ describe('taxonomicFilterLogic', () => {
).toBeFalsy()
})
+ it.each([
+ [TaxonomicFilterGroupType.Events, true, false, 'true'],
+ [TaxonomicFilterGroupType.CustomEvents, true, false, 'true'],
+ [TaxonomicFilterGroupType.Events, true, true, 'false'],
+ [TaxonomicFilterGroupType.CustomEvents, true, true, 'false'],
+ [TaxonomicFilterGroupType.Events, false, false, 'false'],
+ [TaxonomicFilterGroupType.CustomEvents, false, false, 'false'],
+ ])(
+ 'for %s with the flag %p and allowNonCapturedEvents %p, fuzzy_search is %p',
+ (groupType, flagEnabled, allowNonCapturedEvents, expected) => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.TAXONOMIC_FILTER_FUZZY_EVENT_SEARCH]: flagEnabled,
+ })
+ const fuzzyLogic = taxonomicFilterLogic({
+ taxonomicFilterLogicKey: `fuzzy-${groupType}-${flagEnabled}-${allowNonCapturedEvents}`,
+ taxonomicGroupTypes: [groupType],
+ allowNonCapturedEvents,
+ })
+ fuzzyLogic.mount()
+ const group = fuzzyLogic.values.taxonomicGroups.find((item) => item.type === groupType)
+ expect(new URL(group!.endpoint!, 'http://localhost').searchParams.get('fuzzy_search')).toBe(expected)
+ }
+ )
+
it('loads actions when a taxonomic filter mounts', async () => {
await expectLogic(actionsModel).toDispatchActions(['loadActionsSuccess'])
expect(actionRequestCount).toBe(1)
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
index da8efc10c1fc..84f9c2a23fab 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
@@ -574,6 +574,7 @@ export interface taxonomicFilterLogicValues {
ownsSearchInput: boolean
propertyAllowList: TaxonomicFilterGroupValueMap | undefined
propertyFilters: {
+ allowNonCapturedEvents: boolean
excludedProperties: TaxonomicFilterGroupValueMap
includeHiddenEvents: boolean | undefined
propertyAllowList: TaxonomicFilterGroupValueMap | undefined
@@ -703,8 +704,10 @@ export interface taxonomicFilterLogicMeta {
excludedProperties: TaxonomicFilterGroupValueMap,
propertyAllowList: TaxonomicFilterGroupValueMap | undefined,
arg: any,
- arg2: any
+ arg2: any,
+ allowNonCapturedEvents: boolean
) => {
+ allowNonCapturedEvents: boolean
excludedProperties: TaxonomicFilterGroupValueMap
includeHiddenEvents: boolean | undefined
propertyAllowList: TaxonomicFilterGroupValueMap | undefined
@@ -750,6 +753,7 @@ export interface taxonomicFilterLogicMeta {
metadataSource: AnyDataNode,
suggestedFiltersLabel: any,
propertyFilters: {
+ allowNonCapturedEvents: boolean
excludedProperties: TaxonomicFilterGroupValueMap
includeHiddenEvents: boolean | undefined
propertyAllowList: TaxonomicFilterGroupValueMap | undefined
@@ -1107,6 +1111,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
s.propertyAllowList,
(_, props) => props.includeHiddenEvents,
(_, props) => props.showNumericalPropsOnly,
+ s.allowNonCapturedEvents,
],
(
excludedProperties: import('lib/components/TaxonomicFilter/types').TaxonomicFilterGroupValueMap,
@@ -1114,8 +1119,15 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
| import('lib/components/TaxonomicFilter/types').TaxonomicFilterGroupValueMap
| undefined,
includeHiddenEvents: boolean | undefined,
- showNumericalPropsOnly: boolean | undefined
- ) => ({ excludedProperties, propertyAllowList, includeHiddenEvents, showNumericalPropsOnly }),
+ showNumericalPropsOnly: boolean | undefined,
+ allowNonCapturedEvents: boolean
+ ) => ({
+ excludedProperties,
+ propertyAllowList,
+ includeHiddenEvents,
+ showNumericalPropsOnly,
+ allowNonCapturedEvents,
+ }),
{ resultEqualityCheck: objectsEqual },
],
allowNonCapturedEvents: [
@@ -1202,6 +1214,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
propertyAllowList:
| import('lib/components/TaxonomicFilter/types').TaxonomicFilterGroupValueMap
| undefined
+ allowNonCapturedEvents: boolean
includeHiddenEvents: boolean | undefined
showNumericalPropsOnly: boolean | undefined
},
@@ -1230,8 +1243,15 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
const { eventNames, primaryPropertiesForContextEvents, mcpExcludedEventProperties } =
eventNamesWithPrimaryProperties
const { id: teamId } = currentTeam
- const { excludedProperties, propertyAllowList, includeHiddenEvents, showNumericalPropsOnly } =
- propertyFilters
+ const {
+ excludedProperties,
+ propertyAllowList,
+ includeHiddenEvents,
+ showNumericalPropsOnly,
+ allowNonCapturedEvents,
+ } = propertyFilters
+ const fuzzyEventSearch =
+ !!featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_FUZZY_EVENT_SEARCH] && !allowNonCapturedEvents
const groups: TaxonomicFilterGroup[] = [
{
name: 'Events',
@@ -1243,6 +1263,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
endpoint: combineUrl(`api/projects/${projectId}/event_definitions`, {
event_type: EventDefinitionType.Event,
exclude_hidden: true,
+ fuzzy_search: fuzzyEventSearch,
}).url,
excludedProperties: [
...(excludedProperties?.[TaxonomicFilterGroupType.Events]?.filter(isString) ?? []),
@@ -1995,6 +2016,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
endpoint: combineUrl(`api/projects/${projectId}/event_definitions`, {
event_type: EventDefinitionType.EventCustom,
exclude_hidden: true,
+ fuzzy_search: fuzzyEventSearch,
}).url,
getName: (eventDefinition: EventDefinition) => eventDefinition.name,
getValue: (eventDefinition: EventDefinition) => eventDefinition.name,
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
index e3da5b60c4d0..521e6893fb70 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
@@ -183,6 +183,8 @@ export interface BuildTaxonomicGroupsContext {
featureFlags: Record<string, boolean | string | undefined>
/** Keep offering events whose data is moving out of the `events` table. See `TaxonomicFilterProps`. */
includeHiddenEvents?: boolean
+ /** The picker offers "Use event name" for a search with no matches. See `TaxonomicFilterProps`. */
+ allowNonCapturedEvents?: boolean
}
export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): TaxonomicFilterGroup[] {
@@ -207,8 +209,11 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomi
hogQLExpressionComponentProps,
featureFlags,
includeHiddenEvents,
+ allowNonCapturedEvents,
} = ctx
const { id: teamId } = currentTeam
+ const fuzzyEventSearch =
+ !!featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_FUZZY_EVENT_SEARCH] && !allowNonCapturedEvents
const { excludedProperties, propertyAllowList, showNumericalPropsOnly } = propertyFilters
// Opt the cohort picker into the trimmed `?basic=true` payload (drops the
// query/groups/last_error_message/experiment_set fields the picker never reads;
@@ -226,6 +231,7 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomi
endpoint: combineUrl(`api/projects/${projectId}/event_definitions`, {
event_type: EventDefinitionType.Event,
exclude_hidden: true,
+ fuzzy_search: fuzzyEventSearch,
}).url,
// The caller's record already carries the hidden names. Appending them again keeps the
// group hiding them even if some future caller passes a record that skipped the fold,
@@ -923,6 +929,7 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomi
endpoint: combineUrl(`api/projects/${projectId}/event_definitions`, {
event_type: EventDefinitionType.EventCustom,
exclude_hidden: true,
+ fuzzy_search: fuzzyEventSearch,
}).url,
getName: (eventDefinition: EventDefinition) => eventDefinition.name,
getValue: (eventDefinition: EventDefinition) => eventDefinition.name,
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index fb1cdc749698..6932b8974826 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -537,6 +537,7 @@ export const FEATURE_FLAGS = {
TASK_TOOL: 'phai-task-tool', // owner: @kappa90 #team-posthog-ai
TASKS: 'tasks', // owner: #team-ai-observability
TAXONOMIC_FILTER_EVENT_MATCH: 'taxonomic-filter-event-match', // owner: @pauldambra multivariate=control,test, experiment: test asks the decision model which core events an events search with no results describes, then suggests them or says why there are none; control asks nothing
+ TAXONOMIC_FILTER_FUZZY_EVENT_SEARCH: 'taxonomic-filter-fuzzy-event-search', // owner: @pauldambra, Events and Custom events searches with no match ask the API for similar event names
TAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)
TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model. control changes nothing, banner suggests the right tab, promote moves the predicted group to the top of the All tab
TAXONOMIC_FILTER_VALUE_SEARCH_GATING: 'taxonomic-filter-value-search-gating', // owner: @pauldambra
diff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.py
index d3f71aa017f7..586a4e941ffb 100644
--- a/posthog/api/event_definition.py
+++ b/posthog/api/event_definition.py
@@ -437,6 +437,7 @@ class EventDefinitionViewSet(
search = self.request.GET.get("search", None)
has_search_terms = bool(search and search.strip())
+ fuzzy_search = self.request.GET.get("fuzzy_search", "false").lower() == "true"
exclude_stale = self.request.GET.get("exclude_stale", "false").lower() == "true"
verified_param = self.request.GET.get("verified") if EE_AVAILABLE else None
names = [name for value in self.request.query_params.getlist("names") for name in value.split(",") if name]
@@ -473,33 +474,31 @@ class EventDefinitionViewSet(
"count_cap": LARGE_PROJECT_COUNT_CAP,
**search_kwargs,
}
+ filter_query = ""
exclude_hidden = self.request.GET.get("exclude_hidden", "false").lower() == "true"
if exclude_hidden and EE_AVAILABLE:
- search_query = search_query + " AND (hidden IS NULL OR hidden = false)"
+ filter_query += " AND (hidden IS NULL OR hidden = false)"
if exclude_stale:
# `last_seen_at` is not indexed: the predicate runs after the project-scoped
# pre-filter in `create_event_definitions_sql` has already narrowed the row
# set per tenant, and the response is paginated. Worth re-checking with
# EXPLAIN if the largest tenants start showing this in slow-query logs.
- search_query = (
- search_query
- + " AND (posthog_eventdefinition.last_seen_at IS NULL"
+ filter_query += (
+ " AND (posthog_eventdefinition.last_seen_at IS NULL"
+ " OR posthog_eventdefinition.last_seen_at > NOW() - %(stale_interval)s::interval)"
)
params["stale_interval"] = f"{STALE_EVENT_DAYS} days"
if verified_param is not None:
if verified_param.lower() == "true":
- search_query = (
- search_query + " AND (verified = true OR posthog_eventdefinition.name = ANY(%(core_events)s))"
- )
+ filter_query += " AND (verified = true OR posthog_eventdefinition.name = ANY(%(core_events)s))"
params["core_events"] = CORE_EVENTS
else:
- search_query = (
- search_query
- + " AND (verified IS NULL OR verified = false) AND NOT posthog_eventdefinition.name = ANY(%(core_events)s)"
+ filter_query += (
+ " AND (verified IS NULL OR verified = false)"
+ " AND NOT posthog_eventdefinition.name = ANY(%(core_events)s)"
)
params["core_events"] = CORE_EVENTS
@@ -507,19 +506,18 @@ class EventDefinitionViewSet(
if excluded_properties:
excluded_list = list(set(orjson.loads(excluded_properties)))
- search_query = search_query + " AND NOT name = ANY(%(excluded_list)s)"
+ filter_query += " AND NOT name = ANY(%(excluded_list)s)"
params["excluded_list"] = excluded_list
if names:
- search_query = search_query + " AND posthog_eventdefinition.name = ANY(%(names)s)"
+ filter_query += " AND posthog_eventdefinition.name = ANY(%(names)s)"
params["names"] = list(set(names))
if tags_list:
# EXISTS, not a join: it keeps one row per definition, so the page stays a page and
# the count stays a count, with no DISTINCT over the whole result set.
- search_query = (
- search_query
- + " AND EXISTS (SELECT 1 FROM posthog_taggeditem"
+ filter_query += (
+ " AND EXISTS (SELECT 1 FROM posthog_taggeditem"
+ " JOIN posthog_tag ON posthog_tag.id = posthog_taggeditem.tag_id"
+ " WHERE posthog_taggeditem.content_type_id = %(tagged_content_type_id)s"
+ " AND posthog_taggeditem.object_uuid = posthog_eventdefinition.id"
@@ -546,33 +544,47 @@ class EventDefinitionViewSet(
if has_search_terms and "ordering" not in self.request.GET:
order_expressions = [("length(name)", "ASC"), *order_expressions]
- sql = create_event_definitions_sql(
- event_type,
- is_enterprise=EE_AVAILABLE,
- conditions=search_query,
- order_expressions=order_expressions,
- )
-
paginator = cast(CappedCountLimitOffsetPagination, self.paginator)
query = EventDefinitionQuerySerializer(data=self.request.query_params)
query.is_valid(raise_exception=True)
params["limit"] = query.validated_data["limit"]
params["offset"] = query.validated_data["offset"]
- count_sql = create_event_definitions_count_sql(
- event_type,
- is_enterprise=EE_AVAILABLE,
- conditions=search_query,
- bounded=bounded,
- )
+ conditions = search_query + filter_query
# The count has to run on the connection the page fetch will use, or it describes a
# different row set than the one it bounds.
with connections[read_db_alias()].cursor() as cursor:
+ count_sql = create_event_definitions_count_sql(
+ event_type, is_enterprise=EE_AVAILABLE, conditions=conditions, bounded=bounded
+ )
cursor.execute(count_sql, params)
definition_count = cursor.fetchone()[0]
+ fuzzy_term = search.replace("\x00", "").strip() if search else ""
+ if fuzzy_search and definition_count == 0 and 3 <= len(fuzzy_term) <= 200:
+ params["fuzzy_search"] = fuzzy_term
+ # `%` can use the global trigram index; the function form keeps a small project on its own index.
+ fuzzy_predicate = (
+ "posthog_eventdefinition.name %% %(fuzzy_search)s"
+ if large_project
+ else "similarity(posthog_eventdefinition.name, %(fuzzy_search)s) >= show_limit()"
+ )
+ conditions = f" AND {fuzzy_predicate}" + filter_query
+ count_sql = create_event_definitions_count_sql(
+ event_type, is_enterprise=EE_AVAILABLE, conditions=conditions
+ )
+ cursor.execute(count_sql, params)
+ definition_count = cursor.fetchone()[0]
+ if "ordering" not in self.request.GET:
+ order_expressions = [("similarity(name, %(fuzzy_search)s)", "DESC"), *order_expressions]
# Only a count that reached the cap is a lower bound; a filtered large project can be under it.
paginator.set_count(definition_count, is_capped=bounded and definition_count >= LARGE_PROJECT_COUNT_CAP)
+ sql = create_event_definitions_sql(
+ event_type,
+ is_enterprise=EE_AVAILABLE,
+ conditions=conditions,
+ order_expressions=order_expressions,
+ )
return event_definition_object_manager.raw(sql, params=params)
def _tags_filter_from_request(self) -> list[str]:
@@ -656,6 +668,13 @@ class EventDefinitionViewSet(
required=False,
description="Case-insensitive match on the event name. Every whitespace-separated term has to match.",
),
+ OpenApiParameter(
+ "fuzzy_search",
+ OpenApiTypes.BOOL,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="When true, find similar event names only if the filtered search has no matches.",
+ ),
OpenApiParameter(
"event_type",
OpenApiTypes.STR,
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index fadbaed39f64..a29f00f1e4d8 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -105,6 +105,57 @@ class TestEventDefinitionAPI(APIBaseTest):
assert "installed_app" not in result_names
assert "purchase" not in result_names
+ @parameterized.expand(
+ [
+ (f"{name}_{'large' if large_project else 'small'}", search, filters, expected_names, large_project)
+ for name, search, filters, expected_names in [
+ ("disabled", "pgeview", {}, []),
+ ("fallback", "pgeview", {"fuzzy_search": "true"}, ["$pageview"]),
+ (
+ "excluded",
+ "pgeview",
+ {"fuzzy_search": "true", "excluded_properties": '["$pageview"]'},
+ [],
+ ),
+ ("exact_first", "page", {"fuzzy_search": "true"}, ["$pageview"]),
+ ("event_type", "pgeview", {"fuzzy_search": "true", "event_type": "event_custom"}, []),
+ ]
+ for large_project in (False, True)
+ ]
+ )
+ def test_list_event_definitions_fuzzy_fallback(
+ self, _name: str, search: str, filters: dict[str, str], expected_names: list[str], large_project: bool
+ ) -> None:
+ cache.clear()
+ with (
+ patch.object(
+ definition_search,
+ "PROJECT_SCAN_MAX_DEFINITIONS",
+ 2 if large_project else definition_search.PROJECT_SCAN_MAX_DEFINITIONS,
+ ),
+ CaptureQueriesContext(connection) as captured,
+ ):
+ response = self.client.get("/api/projects/@current/event_definitions/", data={"search": search, **filters})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count"] == len(expected_names)
+ assert [item["name"] for item in response.json()["results"]] == expected_names
+ # The global trigram index reads every tenant's posting lists, so only a large project may use it.
+ if filters.get("fuzzy_search") and search == "pgeview":
+ fuzzy_sql = " ".join(q["sql"] for q in captured.captured_queries if "pgeview" in q["sql"])
+ assert ("show_limit()" in fuzzy_sql) is not large_project
+
+ def test_list_event_definitions_fuzzy_fallback_scopes_by_project(self) -> None:
+ other_project_team = create_team(organization=self.organization)
+ EventDefinition.objects.create(team=other_project_team, name="pgeview")
+
+ response = self.client.get(
+ "/api/projects/@current/event_definitions/", data={"search": "pgeview", "fuzzy_search": "true"}
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [item["name"] for item in response.json()["results"]] == ["$pageview"]
+
@parameterized.expand(
[
("boolean", "true"),
@@ -458,6 +509,19 @@ class TestEventDefinitionAPI(APIBaseTest):
assert len(response.json()["results"]) == (100 if i < 2 else 6) # Each page has 100 except the last one
assert response.json()["results"][0]["name"] == f"z_event_{event_checkpoints[i]}"
+ EventDefinition.objects.bulk_create(
+ [
+ EventDefinition(team=self.demo_team, name="checkout_step_alpha"),
+ EventDefinition(team=self.demo_team, name="checkout_step_beta"),
+ ]
+ )
+ response = self.client.get(
+ "/api/projects/@current/event_definitions/",
+ data={"search": "checkuot_step", "fuzzy_search": "true", "limit": "1", "offset": "1"},
+ )
+ assert response.json()["count"] == 2
+ assert len(response.json()["results"]) == 1
+
def test_list_reads_only_the_requested_page_from_postgres(self):
EventDefinition.objects.bulk_create(
[EventDefinition(team=self.demo_team, name=f"z_event_{i}") for i in range(1, 301)]
diff --git a/products/event_definitions/frontend/generated/api.schemas.ts b/products/event_definitions/frontend/generated/api.schemas.ts
index 95517fcda318..dcf2da843eb8 100644
--- a/products/event_definitions/frontend/generated/api.schemas.ts
+++ b/products/event_definitions/frontend/generated/api.schemas.ts
@@ -307,6 +307,10 @@ export type EventDefinitionsListParams = {
* JSON-encoded list of event names to omit. The name matches the property definitions endpoint that shares it.
*/
excluded_properties?: string
+ /**
+ * When true, find similar event names only if the filtered search has no matches.
+ */
+ fuzzy_search?: boolean
/**
* Number of results to return per page.
* @minimum 1
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 166804156d5c..204b9bfe4229 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -132402,6 +132402,10 @@ export namespace Schemas {
* JSON-encoded list of event names to omit. The name matches the property definitions endpoint that shares it.
*/
excluded_properties?: string;
+ /**
+ * When true, find similar event names only if the filtered search has no matches.
+ */
+ fuzzy_search?: boolean;
/**
* Number of results to return per page.
* @minimum 1