: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(bi): find json properties from the data pane (#112134)
Marius Andra6a7f99ef8d63
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex db037b0b9157..16f30681430e 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -48,6 +48,8 @@ Direct connections group tables by schema. Search matches table and folder names**Related tables** exposes existing lazy joins, virtual tables, and configured warehouse joins as expandable nodes. Fields reached through a relation keep the original source and a qualified path, so adding a customer's field to a charges worksheet does not switch tables. PostHog property fields, including `person.properties` under events, expand into searchable, paginated property definitions. Numeric definitions become measures; other definitions become dimensions. Restricted and hidden properties are excluded. Warehouse relationships use the existing join configuration; the worksheet does not create joins or infer arbitrary JSON keys.+**Search fields** also searches property definitions in the selected table and expanded related tables. Search for `$browser`, `$pathname`, or a custom property name to open matching property groups, then drag or double-click a property onto a shelf. Clearing the search restores each group's previous expansion and local search. Searching for a group's name, such as `properties`, shows all its definitions.+## Calculated measures in BI modeWith `SQL_EDITOR_BI_MODE` enabled, open **Business intelligence**, select a table and choose **Add calculated measure** in the data pane.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 01d15b0b91c4..06d01390b8cd 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9591,9 +9591,9 @@ snapshots:scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:hash: v1.k794b7964.e23f5b15f3c99bf3064768fd3a048a436e9b443117cfc0a00c4d73a3f4ba2f22.nxKhSmvyyrnC7kdphG8cL24MkT9I2nGDK4vfruY2Vw0scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:- hash: v1.k794b7964.7e42ca6aa089cac5248ca5ef9344fdd857999f0719cd845ccb7ddc528f28ef15.TTDCOg_BKAoQ1kEvU5M7Awe_RT1Kep8feCfO6DNCArk+ hash: v1.k794b7964.be1c7af3ea56ab263804c40dc88ee390b48279b51f0843223572c4a6d6e3dd6e.NAhufubM0yajuhGMw8mZOiSJwNwAX5nSIXUDvx7SVhcscenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:- hash: v1.k794b7964.82d19296d65f2c10ad57794c4b1f93ee51f12ec1c8a1fa50d566792cf313ff60.WxJmjeoJlfxXKbIjA3n8xHc2_FhQrl4KpxnMTBDqQWI+ hash: v1.k794b7964.dbe9d7e7f469dfb7eb4ec9109b10d1fba19239b46bfee80ea915daf4532c935b.ZLFZ6KVb6v80JYsVv68pSmtqkFJE0pBnxW4FvOnvm08scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:hash: v1.k794b7964.a396976c1ac19d1018d181cb7a1a45b9094c1afae27b09ce5c47370dbd32719e.8W7iOXmHeV_jCUjH5EIjAg3Le0HCj-m8Uf0zVxal0icscenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:diff --git a/products/business_intelligence/frontend/BIDataPaneSection.tsx b/products/business_intelligence/frontend/BIDataPaneSection.tsxindex 9c8bc87b3740..2dcf7cfb92a3 100644--- a/products/business_intelligence/frontend/BIDataPaneSection.tsx+++ b/products/business_intelligence/frontend/BIDataPaneSection.tsx@@ -1,4 +1,4 @@-import { useMountedLogic } from 'kea'+import { useMountedLogic, useValues } from 'kea'import { BIField } from '~/queries/schema/schema-business-intelligence'@@ -21,13 +21,20 @@ export function BIDataPaneSection({path?: string[]}): JSX.Element {const logic = useMountedLogic(biEditorLogic)+ const { dataPaneSearch } = useValues(logic)return (<div className="flex flex-col">{title ? <div className="px-2 pb-1 pt-2 text-xs font-semibold text-secondary">{title}</div> : null}{fields.length === 0 ? <span className="px-2 text-xs text-tertiary">{emptyText}</span> : null}{fields.map((field) =>getBIPropertyTarget(field) ? (- <BIPropertyFieldGroup key={field.id} field={field} path={path} tabId={logic.props.tabId} />+ <BIPropertyFieldGroup+ key={field.id}+ field={field}+ path={path}+ tabId={logic.props.tabId}+ dataPaneSearch={dataPaneSearch}+ />) : (<BIDataPaneField key={field.id} field={field} measure={measure} path={path} />)diff --git a/products/business_intelligence/frontend/BIPropertyFieldGroup.tsx b/products/business_intelligence/frontend/BIPropertyFieldGroup.tsxindex 42f890ec67d6..20c767ad5e52 100644--- a/products/business_intelligence/frontend/BIPropertyFieldGroup.tsx+++ b/products/business_intelligence/frontend/BIPropertyFieldGroup.tsx@@ -15,38 +15,46 @@ export function BIPropertyFieldGroup({field,tabId,path,+ dataPaneSearch,}: {field: BIFieldtabId: stringpath: string[]+ dataPaneSearch: string}): JSX.Element {- const logic = biPropertyFieldsLogic({ field, tabId })+ const logic = biPropertyFieldsLogic({ field, tabId, dataPaneSearch })const { expanded, page, pageLoading, fields, error, search } = useValues(logic)const { toggleExpanded, loadPage, setSearch } = useActions(logic)return (<div className="min-w-0" data-attr="bi-editor-property-group"><div className="flex min-w-0 items-center">- <LemonButton- size="xxsmall"- type="tertiary"- icon={<IconChevronRight className={cn(expanded && 'rotate-90')} />}- aria-label={`Browse ${field.name}`}- aria-expanded={expanded}- loading={pageLoading}- onClick={toggleExpanded}- />+ {dataPaneSearch.trim() ? (+ <IconChevronRight className="m-1 shrink-0 rotate-90" />+ ) : (+ <LemonButton+ size="xxsmall"+ type="tertiary"+ icon={<IconChevronRight className={cn(expanded && 'rotate-90')} />}+ aria-label={`Browse ${field.name}`}+ aria-expanded={expanded}+ loading={pageLoading}+ onClick={toggleExpanded}+ />+ )}<BIDataPaneField field={{ ...field, type: 'json' }} measure={false} path={path} /></div>{expanded ? (<div className="ml-2 min-w-0 border-l pl-1">- <LemonInput- size="small"- type="search"- value={search}- onChange={setSearch}- placeholder="Search properties"- aria-label={`Search ${field.name}`}- />+ {!dataPaneSearch.trim() ? (+ <LemonInput+ size="small"+ type="search"+ value={search}+ onChange={setSearch}+ placeholder="Search properties"+ aria-label={`Search ${field.name}`}+ />+ ) : null}{fields.map((property) => (<BIDataPaneFieldkey={property.id}diff --git a/products/business_intelligence/frontend/biConnectionTree.test.ts b/products/business_intelligence/frontend/biConnectionTree.test.tsindex 34c599998429..f315d57cd193 100644--- a/products/business_intelligence/frontend/biConnectionTree.test.ts+++ b/products/business_intelligence/frontend/biConnectionTree.test.ts@@ -104,6 +104,20 @@ describe('BI connections', () => {})+ it('keeps native property groups searchable without treating warehouse JSON as PostHog properties', () => {+ const catalog = {+ ...tables,+ persons: table('persons', [field('properties', 'json'), field('email', 'string')]),+ }+ for (const rootSource of [{ table: 'events' }, source]) {+ const connections = buildBIConnections(rootSource, catalog, ['["person"]'], {}, true)+ const filtered = filterBIConnections(connections, '$browser')+ expect(filtered.flatMap((connection) => connection.fields.dimensions.map((field) => field.name))).toEqual(+ rootSource.connectionId ? [] : ['person.properties']+ )+ }+ })+it('uses the PostHog table ID for hydration and status', () => {const catalog = { ...tables, persons: { ...table('persons', []), id: 'person-table-id' } }const expanded = ['["person"]']diff --git a/products/business_intelligence/frontend/biConnectionTree.ts b/products/business_intelligence/frontend/biConnectionTree.tsindex af8ba6c46164..e5b4d8389b19 100644--- a/products/business_intelligence/frontend/biConnectionTree.ts+++ b/products/business_intelligence/frontend/biConnectionTree.ts@@ -6,6 +6,8 @@ import { DatabaseSchemaField, DatabaseSchemaTable } from '~/queries/schema/schemimport { BIDataPaneFields, getBIDataPaneFields } from 'products/business_intelligence/frontend/biEditorTypes'import { resolveFieldTraverserTarget } from 'products/data_warehouse/frontend/shared/fieldTraversal'+import { matchesBIFieldSearch } from './biPropertyFields'+export interface BIConnection {id: stringname: string@@ -174,8 +176,8 @@ export function filterBIConnections(connections: BIConnection[], search: string)return [connection]}const fields = {- dimensions: connection.fields.dimensions.filter((field) => field.name.toLowerCase().includes(term)),- measures: connection.fields.measures.filter((field) => field.name.toLowerCase().includes(term)),+ dimensions: connection.fields.dimensions.filter((field) => matchesBIFieldSearch(field, term)),+ measures: connection.fields.measures.filter((field) => matchesBIFieldSearch(field, term)),}const children = filterBIConnections(connection.connections, term)return !connection.expanded ||diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.tsindex 34fedfd6d634..786de61ddbc6 100644--- a/products/business_intelligence/frontend/biEditorLogic.ts+++ b/products/business_intelligence/frontend/biEditorLogic.ts@@ -41,6 +41,7 @@ import {normalizeBIConfig,} from 'products/business_intelligence/frontend/biEditorTypes'+import { matchesBIFieldSearch } from './biPropertyFields'import { getBIDateField } from './biQueryFilters'export interface BIEditorLogicProps {@@ -795,7 +796,7 @@ export const biEditorLogic = kea<biEditorLogicType>([if (!needle) {return dataPaneFields}- const matches = (field: BIField): boolean => field.name.toLowerCase().includes(needle)+ const matches = (field: BIField): boolean => matchesBIFieldSearch(field, needle)return {dimensions: dataPaneFields.dimensions.filter(matches),measures: dataPaneFields.measures.filter(matches),diff --git a/products/business_intelligence/frontend/biPropertyFields.ts b/products/business_intelligence/frontend/biPropertyFields.tsindex 43a31975d680..5a7939e50fd2 100644--- a/products/business_intelligence/frontend/biPropertyFields.ts+++ b/products/business_intelligence/frontend/biPropertyFields.ts@@ -36,3 +36,7 @@ export function buildBIPropertyFields(field: BIField, definitions: EnterprisePro: 'string',}))}++export function matchesBIFieldSearch(field: BIField, search: string): boolean {+ return field.name.toLowerCase().includes(search.trim().toLowerCase()) || !!getBIPropertyTarget(field)+}diff --git a/products/business_intelligence/frontend/biPropertyFieldsLogic.test.ts b/products/business_intelligence/frontend/biPropertyFieldsLogic.test.tsindex 83598e09b474..ea99003af85d 100644--- a/products/business_intelligence/frontend/biPropertyFieldsLogic.test.ts+++ b/products/business_intelligence/frontend/biPropertyFieldsLogic.test.ts@@ -6,7 +6,7 @@ import { BIField } from '~/queries/schema/schema-business-intelligence'import { initKeaTests } from '~/test/init'import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'-import { getBIPropertyTarget } from './biPropertyFields'+import { getBIPropertyTarget, matchesBIFieldSearch } from './biPropertyFields'import { biPropertyFieldsLogic } from './biPropertyFieldsLogic'const field: BIField = {@@ -21,7 +21,7 @@ const definition = (property_type: EnterprisePropertyDefinitionApi['property_type'] = 'String'): EnterprisePropertyDefinitionApi => ({ name, property_type }) as EnterprisePropertyDefinitionApi-describe('BI related properties', () => {+describe('BI properties', () => {beforeEach(() => initKeaTests())it('loads related properties on expansion, pages, searches, and keeps the root table in generated SQL', async () => {@@ -57,6 +57,22 @@ describe('BI related properties', () => {await expectLogic(logic, () => logic.actions.setSearch('annual')).toFinishAllListeners()expect(list).toHaveBeenLastCalledWith('997', expect.objectContaining({ search: 'annual', offset: 0 }))expect(logic.values.fields).toHaveLength(1)+ const localPage = logic.values.page+ logic.actions.toggleExpanded()+ list.mockResolvedValue({ count: 1, results: [definition('plan')] })+ await expectLogic(logic, () => {+ biPropertyFieldsLogic({ tabId: 'properties', field, dataPaneSearch: 'plan' })+ }).toFinishAllListeners()+ expect(logic.values.fields[0].name).toContain('plan')+ const callsBeforeClear = list.mock.calls.length+ await expectLogic(logic, () => {+ biPropertyFieldsLogic({ tabId: 'properties', field, dataPaneSearch: '' })+ }).toFinishAllListeners()+ expect(logic.values.expanded).toBe(false)+ expect(logic.values.page).toEqual(localPage)+ await expectLogic(logic, () => logic.actions.toggleExpanded()).toFinishAllListeners()+ expect(list).toHaveBeenCalledTimes(callsBeforeClear)+ expect(logic.values.fields[0].name).toContain('annual_spend')} finally {logic.unmount()list.mockRestore()@@ -81,6 +97,73 @@ describe('BI related properties', () => {}})+ it.each([+ ['events', 'properties', 'event', '$browser'],+ ['persons', 'properties', 'person', 'profile.country'],+ ['events', 'person.properties', 'person', 'plan'],+ ])('finds %s %s through the Data pane search', async (table, name, type, property) => {+ const rootField: BIField = { ...field, name, expression: name, type: 'json', source: { table } }+ const list = jest.spyOn(api, 'propertyDefinitionsList').mockResolvedValue({+ count: 1,+ results: [definition(property)],+ })+ const logicProps = { tabId: 'search', field: rootField }+ const logic = biPropertyFieldsLogic({ ...logicProps, dataPaneSearch: property })+ expect(matchesBIFieldSearch(rootField, property)).toBe(true)+ await expectLogic(logic, () => {+ logic.mount()+ }).toFinishAllListeners()+ try {+ expect(logic.values.expanded).toBe(true)+ expect(list).toHaveBeenLastCalledWith(+ '997',+ expect.objectContaining({+ type,+ search: property,+ offset: 0,+ exclude_hidden: true,+ exclude_restricted: true,+ })+ )+ const propertyField = logic.values.fields[0]+ expect(propertyField.source).toEqual({ table })+ expect(buildBIQuery({ ...DEFAULT_BI_CONFIG, source: { table }, rows: [propertyField] })?.query).toContain(+ `FROM ${table}`+ )+ expect(propertyField.expression).toBe(`${name}.${property.includes('.') ? `"${property}"` : property}`)++ list.mockResolvedValue({ count: 1, results: [definition('$pathname')] })+ await expectLogic(logic, () => {+ biPropertyFieldsLogic({ ...logicProps, dataPaneSearch: '$pathname' })+ }).toFinishAllListeners()+ expect(logic.values.fields.map((field) => field.expression)).toEqual([`${name}.$pathname`])+ expect(list).toHaveBeenLastCalledWith('997', expect.objectContaining({ search: '$pathname', offset: 0 }))++ const callsBeforeClear = list.mock.calls.length+ await expectLogic(logic, () => {+ biPropertyFieldsLogic({ ...logicProps, dataPaneSearch: '' })+ }).toFinishAllListeners()+ expect(logic.values.expanded).toBe(false)+ expect(logic.values.page).toBeNull()+ expect(list).toHaveBeenCalledTimes(callsBeforeClear)+ await expectLogic(logic, () => logic.actions.toggleExpanded()).toFinishAllListeners()+ expect(list).toHaveBeenLastCalledWith('997', expect.objectContaining({ search: undefined, offset: 0 }))+ await expectLogic(logic, () => logic.actions.setSearch('local')).toFinishAllListeners()+ await expectLogic(logic, () => {+ biPropertyFieldsLogic({ ...logicProps, dataPaneSearch: 'PROPERTIES' })+ }).toFinishAllListeners()+ expect(list).toHaveBeenLastCalledWith('997', expect.objectContaining({ search: undefined }))+ await expectLogic(logic, () => {+ biPropertyFieldsLogic({ ...logicProps, dataPaneSearch: '' })+ }).toFinishAllListeners()+ expect(logic.values.expanded).toBe(true)+ expect(logic.values.search).toBe('local')+ } finally {+ logic.unmount()+ list.mockRestore()+ }+ })+it.each([[{ ...field, name: 'properties', type: 'json' as const }, { type: 'event' }],[field, { type: 'person' }],diff --git a/products/business_intelligence/frontend/biPropertyFieldsLogic.ts b/products/business_intelligence/frontend/biPropertyFieldsLogic.tsindex 3b82cbdeabee..e0f3c1b4eb1a 100644--- a/products/business_intelligence/frontend/biPropertyFieldsLogic.ts+++ b/products/business_intelligence/frontend/biPropertyFieldsLogic.ts@@ -2,12 +2,14 @@ import {LogicWrapper,MakeLogicType,actions,+ afterMount,connect,kea,key,listeners,path,props,+ propsChanged,reducers,selectors,} from 'kea'@@ -24,6 +26,7 @@ import { buildBIPropertyFields, getBIPropertyTarget } from './biPropertyFields'export interface BIPropertyFieldsLogicProps {tabId: stringfield: BIField+ dataPaneSearch?: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -32,6 +35,8 @@ export interface biPropertyFieldsLogicValues {error: string | nullexpanded: booleanfields: BIField[]+ localSearch: string+ manuallyExpanded: booleanpage: PaginatedEnterprisePropertyDefinitionListApi | nullpageLoading: booleansearch: string@@ -60,6 +65,9 @@ export interface biPropertyFieldsLogicActions {offset: number}}+ restorePage: (page: PaginatedEnterprisePropertyDefinitionListApi | null) => {+ page: PaginatedEnterprisePropertyDefinitionListApi | null+ }setSearch: (search: string) => {search: string}@@ -72,6 +80,8 @@ export interface biPropertyFieldsLogicActions {export interface biPropertyFieldsLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ expanded: (manuallyExpanded: boolean, arg: any) => boolean+ search: (localSearch: string, arg: any) => stringfields: (page: PaginatedEnterprisePropertyDefinitionListApi | null) => BIField[]}}@@ -88,8 +98,12 @@ export const biPropertyFieldsLogic: LogicWrapper<biPropertyFieldsLogicType> = kekey(({ tabId, field }) => JSON.stringify([tabId, field.id])),path((key) => ['products', 'business_intelligence', 'frontend', 'biPropertyFieldsLogic', key]),connect({ values: [projectLogic, ['currentProjectId']] }),- actions({ toggleExpanded: true, setSearch: (search: string) => ({ search }) }),- loaders(({ props, values }) => ({+ actions({+ toggleExpanded: true,+ setSearch: (search: string) => ({ search }),+ restorePage: (page: PaginatedEnterprisePropertyDefinitionListApi | null) => ({ page }),+ }),+ loaders(({ props, values, cache }) => ({page: [null as PaginatedEnterprisePropertyDefinitionListApi | null,{@@ -97,6 +111,7 @@ export const biPropertyFieldsLogic: LogicWrapper<biPropertyFieldsLogicType> = ke{ offset }: { offset: number },breakpoint): Promise<PaginatedEnterprisePropertyDefinitionListApi | null> => {+ const searchVersion = cache.searchVersionconst target = getBIPropertyTarget(props.field)if (!target || !values.currentProjectId) {return null@@ -104,31 +119,68 @@ export const biPropertyFieldsLogic: LogicWrapper<biPropertyFieldsLogicType> = keif (values.search) {await breakpoint(250)}- const response = await api.propertyDefinitionsList(String(values.currentProjectId), {- type: target.type,- group_type_index: target.groupTypeIndex,- exclude_hidden: true,- exclude_restricted: true,- search: values.search.trim() || undefined,- limit: 25,- offset,- })- breakpoint()- return {- ...response,- results: [...(offset ? (values.page?.results ?? []) : []), ...response.results],+ if (searchVersion !== cache.searchVersion) {+ return values.page+ }+ try {+ const response = await api.propertyDefinitionsList(String(values.currentProjectId), {+ type: target.type,+ group_type_index: target.groupTypeIndex,+ exclude_hidden: true,+ exclude_restricted: true,+ search: values.search.trim() || undefined,+ limit: 25,+ offset,+ })+ breakpoint()+ if (searchVersion !== cache.searchVersion) {+ return values.page+ }+ return {+ ...response,+ results: [...(offset ? (values.page?.results ?? []) : []), ...response.results],+ }+ } catch (error) {+ if (searchVersion !== cache.searchVersion) {+ return values.page+ }+ throw error}},},],})),reducers({- expanded: [false, { toggleExpanded: (expanded) => !expanded }],- search: ['', { setSearch: (_, { search }) => search }],- page: [null as PaginatedEnterprisePropertyDefinitionListApi | null, { setSearch: () => null }],- error: [null as string | null, { loadPage: () => null, loadPageFailure: (_, { error }) => error }],+ manuallyExpanded: [false, { toggleExpanded: (expanded) => !expanded }],+ localSearch: ['', { setSearch: (_, { search }) => search }],+ page: [+ null as PaginatedEnterprisePropertyDefinitionListApi | null,+ {+ loadPage: (page, { offset }) => (offset ? page : null),+ restorePage: (_, { page }) => page,+ },+ ],+ pageLoading: [false, { restorePage: () => false }],+ error: [+ null as string | null,+ { loadPage: () => null, restorePage: () => null, loadPageFailure: (_, { error }) => error },+ ],}),selectors(({ props }) => ({+ expanded: [+ (s) => [s.manuallyExpanded, (_, props) => props.dataPaneSearch?.trim()],+ (manuallyExpanded: boolean, dataPaneSearch: string | undefined): boolean =>+ manuallyExpanded || !!dataPaneSearch,+ ],+ search: [+ (s) => [s.localSearch, (_, props) => props.dataPaneSearch?.trim()],+ (localSearch: string, dataPaneSearch: string | undefined): string =>+ dataPaneSearch+ ? props.field.name.toLowerCase().includes(dataPaneSearch.toLowerCase())+ ? ''+ : dataPaneSearch+ : localSearch,+ ],fields: [(s) => [s.page],(page: PaginatedEnterprisePropertyDefinitionListApi | null): BIField[] =>@@ -143,4 +195,24 @@ export const biPropertyFieldsLogic: LogicWrapper<biPropertyFieldsLogicType> = ke},setSearch: () => actions.loadPage({ offset: 0 }),})),+ afterMount(({ actions, props }) => {+ if (props.dataPaneSearch?.trim()) {+ actions.loadPage({ offset: 0 })+ }+ }),+ propsChanged(({ actions, props, values, cache }, oldProps) => {+ const search = props.dataPaneSearch?.trim()+ if (search !== oldProps.dataPaneSearch?.trim()) {+ cache.searchVersion = (cache.searchVersion ?? 0) + 1+ if (!oldProps.dataPaneSearch?.trim()) {+ cache.localPage = values.page+ cache.localPageSearch = values.localSearch+ }+ if (!search && !values.manuallyExpanded) {+ actions.restorePage(cache.localPageSearch === values.localSearch ? (cache.localPage ?? null) : null)+ } else {+ actions.loadPage({ offset: 0 })+ }+ }+ }),])