: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
feat(search): explain keyword matches and link to tabs in cmd+k (#111991)
Thiago Salvatore624fb27cdddd
diff --git a/frontend/src/lib/components/Search/Search.tsx b/frontend/src/lib/components/Search/Search.tsxindex b82ff95eab16..b6d0b72d4665 100644--- a/frontend/src/lib/components/Search/Search.tsx+++ b/frontend/src/lib/components/Search/Search.tsx@@ -986,13 +986,30 @@ function SearchResults({)}</span>)}+ {item.parentName && (+ <span className="text-xs text-tertiary shrink-0 mt-[2px]">+ {`in ${item.parentName}`}+ </span>+ )}{item.productCategory && (<span className="text-xs text-tertiary shrink-0 mt-[2px]">{item.productCategory}</span>)}+ {item.matchedSearchKeyword && (+ <span className="ml-auto text-xxs text-tertiary truncate mt-[2px]">+ {`Matches "${item.matchedSearchKeyword}"`}+ </span>+ )}{item.lastViewedAt && (- <span className="ml-auto text-xs text-tertiary whitespace-nowrap shrink-0 mt-[2px]">+ <span+ className={cn(+ 'text-xs text-tertiary whitespace-nowrap shrink-0 mt-[2px]',+ item.matchedSearchKeyword+ ? 'ml-2'+ : 'ml-auto'+ )}+ >{formatRelativeTimeShort(item.lastViewedAt)}diff --git a/frontend/src/lib/components/Search/searchLogic.test.ts b/frontend/src/lib/components/Search/searchLogic.test.tsindex 54afd265b81f..97d23090a397 100644--- a/frontend/src/lib/components/Search/searchLogic.test.ts+++ b/frontend/src/lib/components/Search/searchLogic.test.ts@@ -173,14 +173,53 @@ describe('searchLogic', () => {})it.each([- ['data quality', 'dataManagementItems', 'Models'],+ ['materialized views', 'dataManagementItems', 'Models'],['batch exports', 'dataManagementItems', 'Destinations'],['insights', 'productsItems', 'Product analytics'],+ ['semantic layer', 'productsItems', 'Data catalog'],+ ['Semantic Layer', 'productsItems', 'Data catalog'],+ ['semanticlayer', 'productsItems', 'Data catalog'],+ ['semantic-layer', 'productsItems', 'Data catalog'],+ ['featureflags', 'productsItems', 'Feature flags'],+ ['Feature Flags', 'productsItems', 'Feature flags'],] as const)('finds an item by a manifest search keyword: %s', (search, selector, itemName) => {const matches = filterSearchItems(logic.values[selector], search)expect(matches.map((item) => item.name)).toContain(itemName)})+ it.each([+ ['data quality', true, true],+ ['dataquality', true, true],+ ['Data-Quality', true, true],+ ['models data quality', true, true],+ ['data quality', false, false],+ ['', true, false],+ ])('lists the Models data quality tab for search %j with the flag on=%s: %s', (search, flagEnabled, listed) => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DATA_QUALITY_CHECKS]: flagEnabled })+ logic.actions.setSearch(search)++ const dataManagement = logic.values.allCategories.find((category) => category.key === 'data-management')+ const tabRow = dataManagement?.items.find((item) => item.href === urls.models('data-quality'))+ expect(tabRow ? { displayName: tabRow.displayName, parentName: tabRow.parentName } : undefined).toEqual(+ listed ? { displayName: 'Data quality', parentName: 'Models' } : undefined+ )+ })++ it.each([+ ['newflag', 'New Feature flag'],+ ['new flag', 'New Feature flag'],+ ['New Feature Flag', 'New Feature flag'],+ ['newfeatureflag', 'New Feature flag'],+ ['create flag', 'New Feature flag'],+ ['new site app', 'New Web script'],+ ['new site_app', 'New Web script'],+ ])('puts the right item first in the create category for %j', (search, expectedFirst) => {+ logic.actions.setSearch(search)++ const create = logic.values.allCategories.find((category) => category.key === 'create')+ expect(create?.items[0]?.name).toBe(expectedFirst)+ })+it('maps matching support tickets into their own category', async () => {useMocks({get: {diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsxindex 0ff934d8522b..a43d30d4dbba 100644--- a/frontend/src/lib/components/Search/searchLogic.tsx+++ b/frontend/src/lib/components/Search/searchLogic.tsx@@ -121,6 +121,35 @@ const fileSystemEntryToSearchItem = (}}+const isEnabledByFlag = (flag: string | undefined, featureFlags: FeatureFlagsSet): boolean =>+ !flag || !!(featureFlags as Record<string, boolean>)[flag]++const displayNameOf = (item: SearchItem): string => item.displayName || item.name++const toSearchTabItems = (+ parents: SearchItem[],+ sources: FileSystemImport[],+ featureFlags: FeatureFlagsSet+): SearchItem[] => {+ const tabsByPath = new Map(sources.map((source) => [source.path, source.searchTabs ?? []]))+ return parents.flatMap((parent) =>+ (tabsByPath.get(parent.name) ?? [])+ .filter((tab) => isEnabledByFlag(tab.flag, featureFlags))+ .map((tab) => ({+ id: `${parent.id}-tab-${tab.name}`,+ name: `${displayNameOf(parent)} ${tab.name}`,+ displayName: tab.name,+ category: parent.category,+ parentName: displayNameOf(parent),+ href: tab.href,+ itemType: parent.itemType,+ searchKeywords: tab.searchKeywords,+ disabledReason: parent.disabledReason,+ record: parent.record,+ }))+ )+}+// Types for command search resultsexport interface SearchItem {id: string@@ -137,6 +166,9 @@ export interface SearchItem {groupNoun?: string | nullitemType?: string | nullsearchKeywords?: string[]+ hiddenSearchText?: string+ matchedSearchKeyword?: string | null+ parentName?: stringrecord?: Record<string, unknown>rank?: number | null // PostgreSQL full-text search rank (from unified search API)/** When set, the item is shown greyed out and non-clickable, with this reason as tooltip@@ -158,6 +190,7 @@ export const RECENTS_LIMIT = 5/** Max starred shortcuts shown in quick search (folders excluded). */export const STARRED_LIMIT = 20const SEARCH_LIMIT = 5+const LEADING_CREATE_WORD = /^\s*create\b/i/** Safely extract a string — returns undefined for objects/arrays to avoid rendering [object Object]. */const safeString = (val: unknown): string | undefined => (typeof val === 'string' ? val : undefined)@@ -905,7 +938,7 @@ export const searchLogic = kea<searchLogicType>([if (!isDev && !user?.is_staff && product.category === 'Unreleased') {return false}- if (product.flag && !(featureFlags as Record<string, boolean>)[product.flag]) {+ if (!isEnabledByFlag(product.flag, featureFlags)) {return false}return true@@ -944,6 +977,7 @@ export const searchLogic = kea<searchLogicType>([iconColor: undefined,},})+ items.push(...toSearchTabItems(items, filteredProducts, featureFlags))// Sort by lastViewedAt (most recent first), items without lastViewedAt go to the endreturn items.sort((a, b) => {@@ -973,7 +1007,7 @@ export const searchLogic = kea<searchLogicType>([if (!isDev && !user?.is_staff && item.category === 'Unreleased') {return false}- if (item.flag && !(featureFlags as Record<string, boolean>)[item.flag]) {+ if (!isEnabledByFlag(item.flag, featureFlags)) {return false}return true@@ -983,7 +1017,7 @@ export const searchLogic = kea<searchLogicType>([CDP: ['data pipelines', 'data pipeline', 'pipeline'],}- const items = filteredMetadata.map((item) => ({+ const items: SearchItem[] = filteredMetadata.map((item) => ({id: `data-management-${item.path}`,name: item.path,displayName: item.path,@@ -1004,6 +1038,8 @@ export const searchLogic = kea<searchLogicType>([},}))+ items.push(...toSearchTabItems(items, filteredMetadata, featureFlags))+// Sort by lastViewedAt (most recent first), items without lastViewedAt go to the endreturn items.sort((a, b) => {if (!a.lastViewedAt && !b.lastViewedAt) {@@ -1032,7 +1068,7 @@ export const searchLogic = kea<searchLogicType>([if (!isDev && !user?.is_staff && item.category === 'Unreleased') {return false}- if (item.flag && !(featureFlags as Record<string, boolean>)[item.flag]) {+ if (!isEnabledByFlag(item.flag, featureFlags)) {return false}return true@@ -1063,6 +1099,7 @@ export const searchLogic = kea<searchLogicType>([productCategory: item.category || null,href: item.href || PLACEHOLDER_HREF,itemType: item.iconType || item.type || null,+ hiddenSearchText: [displayName, item.path, item.type, item.iconType].filter(Boolean).join(' '),record: {type: item.type || item.iconType,iconType: item.iconType,@@ -1666,8 +1703,10 @@ export const searchLogic = kea<searchLogicType>([})// Filter products and data management by search- const filteredProducts = filterBySearch(productsItems)- const filteredDataManagement = filterBySearch(dataManagementItems)+ const filterCatalogBySearch = (items: SearchItem[]): SearchItem[] =>+ hasSearch ? filterSearchItems(items, search) : items.filter((item) => !item.parentName)+ const filteredProducts = filterCatalogBySearch(productsItems)+ const filteredDataManagement = filterCatalogBySearch(dataManagementItems)// Show products if not searching or has matching resultsif (!hasSearch || filteredProducts.length > 0) {@@ -1729,38 +1768,7 @@ export const searchLogic = kea<searchLogicType>([// Show "create" category only when searching and matching "new" or relevant keywordsif (hasSearch) {- const searchLower = search.toLowerCase()- const searchChunks = searchLower.split(' ').filter((s) => s)-- // Filter new items - ALL search chunks must match- const filteredNewItems = newItems.filter((item) => {- const nameLower = (item.displayName || item.name || '').toLowerCase()- const typeLower = (item.itemType || '').toLowerCase()- // Also search against the original path (stored in id as "new-{path}")- const idLower = item.id.toLowerCase()-- // Every chunk must match either "new"/"create" or be found in the item name/type/id- return searchChunks.every((chunk) => {- if (- chunk === 'new' ||- chunk === 'create' ||- chunk.startsWith('new') ||- chunk.startsWith('create')- ) {- return true- }- if (nameLower.includes(chunk)) {- return true- }- if (typeLower.includes(chunk)) {- return true- }- if (idLower.includes(chunk)) {- return true- }- return false- })- })+ const filteredNewItems = filterSearchItems(newItems, search.replace(LEADING_CREATE_WORD, 'new'))if (filteredNewItems.length > 0) {categories.push({diff --git a/frontend/src/lib/components/Search/utils.test.ts b/frontend/src/lib/components/Search/utils.test.tsindex 78fd224c35c5..baea3803a930 100644--- a/frontend/src/lib/components/Search/utils.test.ts+++ b/frontend/src/lib/components/Search/utils.test.ts@@ -7,6 +7,7 @@ interface TestItem {displayName?: stringcategory: stringsearchKeywords?: string[]+ matchedSearchKeyword?: string | null}const makeItem = (name: string, category = 'tools', extra: Partial<TestItem> = {}): TestItem => ({@@ -89,6 +90,15 @@ describe('filterSearchItems', () => {const results = filterSearchItems(items, 'database')expect(names(results)).toContain('Data warehouse')})++ it.each([+ ['sql', 'sql'],+ ['DATABASE', 'database'],+ ['data warehouse', null],+ ])('reports the keyword that matched %s', (query, expectedKeyword) => {+ const match = filterSearchItems(items, query).find((item) => item.name === 'Data warehouse')+ expect(match?.matchedSearchKeyword).toBe(expectedKeyword)+ })})describe('category matching', () => {diff --git a/frontend/src/lib/components/Search/utils.ts b/frontend/src/lib/components/Search/utils.tsindex 2755723d5094..b634efd4777b 100644--- a/frontend/src/lib/components/Search/utils.ts+++ b/frontend/src/lib/components/Search/utils.ts@@ -1,5 +1,5 @@import { Dayjs, dayjs } from 'lib/dayjs'-import { createFuse } from 'lib/utils/fuseSearch'+import { FuseResultMatch, createFuse } from 'lib/utils/fuseSearch'import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'import { pluralize } from 'lib/utils/strings'@@ -11,17 +11,31 @@ interface FuseSearchable {displayName?: stringcategory: stringsearchKeywords?: string[]+ hiddenSearchText?: string+ matchedSearchKeyword?: string | null}+const SEARCH_KEYWORDS_KEY = 'searchKeywords'+const NAME_KEYS = new Set(['name', 'displayName'])+const FUSE_OPTIONS = {keys: [{ name: 'name', weight: 2 },{ name: 'displayName', weight: 2 },{ name: 'category', weight: 0.5 },- { name: 'searchKeywords', weight: 1.5 },+ { name: SEARCH_KEYWORDS_KEY, weight: 1.5 },+ { name: 'hiddenSearchText', weight: 1 },],ignoreLocation: true,useExtendedSearch: true,+ includeMatches: true,+}++const keywordOnlyMatch = (matches: readonly FuseResultMatch[] = []): string | null => {+ if (matches.some((match) => match.key && NAME_KEYS.has(match.key))) {+ return null+ }+ return matches.find((match) => match.key === SEARCH_KEYWORDS_KEY)?.value ?? null}/**@@ -34,7 +48,10 @@ export function filterSearchItems<T extends FuseSearchable>(items: T[], query: sreturn items}const fuse = createFuse<T>(items, FUSE_OPTIONS)- return fuse.search(trimmed).map((r) => r.item)+ return fuse.search(trimmed).map((result) => ({+ ...result.item,+ matchedSearchKeyword: keywordOnlyMatch(result.matches),+ }))}/** Structural so this module avoids importing searchLogic, which imports this one. */diff --git a/frontend/src/lib/utils/fuseSearch.ts b/frontend/src/lib/utils/fuseSearch.tsindex f0b8de0a712e..e16e35d09229 100644--- a/frontend/src/lib/utils/fuseSearch.ts+++ b/frontend/src/lib/utils/fuseSearch.ts@@ -1,7 +1,7 @@-import FuseClass, { IFuseOptions } from 'fuse.js'+import FuseClass, { FuseResultMatch, IFuseOptions } from 'fuse.js'export type Fuse<T> = FuseClass<T>-export type { IFuseOptions }+export type { FuseResultMatch, IFuseOptions }const FUSE_DEFAULTS = {threshold: 0.3,diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 2f13a4080110..aa08008a8e67 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -2302,7 +2302,11 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [iconType: 'data_catalog',iconColor: ['var(--color-product-data-catalog-light)', 'var(--color-product-data-catalog-dark)'],href: urls.dataCatalog(),- searchKeywords: ['semantic layer', 'metrics', 'certification'],+ searchKeywords: ['semantic layer', 'metrics'],+ searchTabs: [+ { name: 'Relationships', href: urls.dataCatalog('relationships') },+ { name: 'Certifications', href: urls.dataCatalog('certifications') },+ ],tags: ['beta'],sceneKey: 'DataCatalog',sceneKeys: ['DataCatalog', 'DataCatalogMetric'],@@ -3060,7 +3064,16 @@ export const getTreeItemsMetadata = (): FileSystemImport[] => [iconType: 'data_modeling',iconColor: ['var(--color-product-models-light)', 'var(--color-product-models-dark)'],href: urls.models(),- searchKeywords: ['data quality', 'lineage', 'materialized views', 'materialization', 'tests'],+ searchKeywords: ['materialized views', 'materialization'],+ searchTabs: [+ { name: 'Lineage', href: urls.models('lineage') },+ {+ name: 'Data quality',+ href: urls.models('data-quality'),+ flag: FEATURE_FLAGS.DATA_QUALITY_CHECKS,+ searchKeywords: ['tests'],+ },+ ],sceneKey: 'Models',sceneKeys: ['Models'],},diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 4a00ba9bc5ff..39db5638ba80 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -27359,6 +27359,13 @@},"type": "array"},+ "searchTabs": {+ "description": "Tabs of this item that search lists as their own results",+ "items": {+ "$ref": "#/definitions/FileSystemSearchTab"+ },+ "type": "array"+ },"shortcut": {"description": "Whether this is a shortcut or the actual item","type": "boolean"@@ -27387,6 +27394,28 @@"required": ["path"],"type": "object"},+ "FileSystemSearchTab": {+ "additionalProperties": false,+ "properties": {+ "flag": {+ "type": "string"+ },+ "href": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "searchKeywords": {+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["name", "href"],+ "type": "object"+ },"FileSystemViewLogEntry": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 1de103128415..a463aa4cbec2 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5544,6 +5544,15 @@ export interface FileSystemImport extends Omit<FileSystemEntry, 'id'> {displayLabel?: string/** Other terms that find this item in search, for example the names of its tabs or common synonyms */searchKeywords?: string[]+ /** Tabs of this item that search lists as their own results */+ searchTabs?: FileSystemSearchTab[]+}++export interface FileSystemSearchTab {+ name: string+ href: string+ flag?: string+ searchKeywords?: string[]}export interface FileSystemViewLogEntry {diff --git a/posthog/schema.py b/posthog/schema.pyindex c5449e34f920..b11abc2a3d89 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -1638,6 +1638,16 @@ class FileSystemEntry(BaseModel):visualOrder: float | None = Field(default=None, description="Order of object in tree")+class FileSystemSearchTab(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ flag: str | None = None+ href: str+ name: str+ searchKeywords: list[str] | None = None++class FileSystemViewLogEntry(BaseModel):model_config = ConfigDict(extra="forbid",@@ -5638,6 +5648,10 @@ class FileSystemImport(BaseModel):default=None,description=("Other terms that find this item in search, for example the names of its tabs or common synonyms"),)+ searchTabs: list[FileSystemSearchTab] | None = Field(+ default=None,+ description="Tabs of this item that search lists as their own results",+ )shortcut: bool | None = Field(default=None, description="Whether this is a shortcut or the actual item")tags: list[Tag] | None = Field(default=None, description="Tag for the product 'beta' / 'alpha'")type: str | None = Field(diff --git a/products/data_catalog/manifest.tsx b/products/data_catalog/manifest.tsxindex 79a451714b54..ea03fbccab9b 100644--- a/products/data_catalog/manifest.tsx+++ b/products/data_catalog/manifest.tsx@@ -41,7 +41,11 @@ export const manifest: ProductManifest = {iconType: 'data_catalog',iconColor: ['var(--color-product-data-catalog-light)', 'var(--color-product-data-catalog-dark)'],href: urls.dataCatalog(),- searchKeywords: ['semantic layer', 'metrics', 'certification'],+ searchKeywords: ['semantic layer', 'metrics'],+ searchTabs: [+ { name: 'Relationships', href: urls.dataCatalog('relationships') },+ { name: 'Certifications', href: urls.dataCatalog('certifications') },+ ],tags: ['beta'],sceneKey: 'DataCatalog',},diff --git a/products/data_modeling/manifest.tsx b/products/data_modeling/manifest.tsxindex 19179e53a02b..1d826d51c906 100644--- a/products/data_modeling/manifest.tsx+++ b/products/data_modeling/manifest.tsx@@ -1,3 +1,4 @@+import { FEATURE_FLAGS } from 'lib/constants'import { urls } from 'scenes/urls'import { ProductManifest } from '~/types'@@ -38,7 +39,16 @@ export const manifest: ProductManifest = {iconType: 'data_modeling',iconColor: ['var(--color-product-models-light)', 'var(--color-product-models-dark)'],href: urls.models(),- searchKeywords: ['data quality', 'lineage', 'materialized views', 'materialization', 'tests'],+ searchKeywords: ['materialized views', 'materialization'],+ searchTabs: [+ { name: 'Lineage', href: urls.models('lineage') },+ {+ name: 'Data quality',+ href: urls.models('data-quality'),+ flag: FEATURE_FLAGS.DATA_QUALITY_CHECKS,+ searchKeywords: ['tests'],+ },+ ],sceneKey: 'Models',sceneKeys: ['Models'],},