Below is one way to approach the problem. The idea is to group events by their name and combine all their JSON “properties” so that we can extract the distinct JSON paths and types for each event. One solution is to aggregate all the JSON objects for a given event name into an array (using the aggregate function groupArray), then pass that aggregated array through the helper function distinctJSONPathsAndTypes. Finally, we use arrayJoin to “explode” the result so that each JSON path/type pair appears on its own row.
For example, you might write the query as follows:
SELECT
event_name,
arrayJoin(distinctJSONPathsAndTypes(groupArray(properties))) AS property_schema
FROM ${tenant}_events
GROUP BY event_name
ORDER BY event_name;
Explanation
-
Grouping by Event Name:
The query groups rows by event_name so that the schema is derived separately for each distinct event.
-
Combining JSON Columns:
The groupArray(properties) collects all the properties values for a given event name into an array.
-
Deriving the JSON Schema:
The function distinctJSONPathsAndTypes (which you mentioned is similar to the standalone query
SELECT arrayJoin(distinctJSONPathsAndTypes(properties)) FROM DB.${tenant}_events) is applied to the aggregated array. This returns an array of unique JSON path/type pairs.
-
Flattening the Array:
Finally, arrayJoin is used to flatten the resulting array so that each row in the result corresponds to one distinct JSON path/type.
TypeScript Example Function
You might wrap this query inside your TypeScript function as follows:
export const deriveSegmentEventSchemafromTenantTable = async (tenant: string) => {
// Construct the query with the tenant-specific table reference.
const query = `
SELECT
event_name,
arrayJoin(distinctJSONPathsAndTypes(groupArray(properties))) AS property_schema
FROM ${tenant}_events
GROUP BY event_name
ORDER BY event_name
`;
// Assume you have a function called `runQuery` that executes your ClickHouse SQL query.
const result = await runQuery(query);
return result;
};
Notes
-
Function Availability:
Make sure that the function distinctJSONPathsAndTypes as well as the usage of groupArray with it is supported in your version of ClickHouse. If needed, adjust the aggregation based on available functions.
-
Performance Considerations:
When running these types of queries on large datasets, the cost of aggregating all JSON objects per event may be significant. Consider any necessary performance optimizations or pre-aggregations if needed.
This query should provide a schema (i.e. the unique property paths and their types) grouped by each event name from your tenant’s events table.