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(data-catalog): support full-text catalog search (#116138)

Adam Bowkerbd0c50c81155
diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.py
index c439d745eebd..d6e5b421a1b8 100644
--- a/products/data_catalog/backend/presentation/views.py
+++ b/products/data_catalog/backend/presentation/views.py
@@ -4,15 +4,21 @@ Thin: validate via the serializer, call the facade, serialize the result. Domain
(name uniqueness, upsert, rename, validation, drift, approval) live in the logic layer behind the facade.
"""
+from functools import reduce
+from operator import or_
from typing import cast
-from django.db.models import QuerySet
+from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVectorField
+from django.db.models import Func, QuerySet, Value
+from django.db.models.expressions import CombinedExpression
+from django.db.models.functions import Coalesce
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action as drf_action
from rest_framework.exceptions import PermissionDenied
+from rest_framework.filters import SearchFilter
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.throttling import BaseThrottle
@@ -21,6 +27,7 @@ from rest_framework.views import APIView
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.helpers.full_text_search import build_search_vector
from posthog.models import User
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle, HogQLQueryThrottle
@@ -61,11 +68,52 @@ def _resolve_bulk_metrics(
)
+class CatalogSearchFilter(SearchFilter):
+ def get_search_vector(self, request: Request, view: APIView) -> CombinedExpression:
+ return build_search_vector(dict.fromkeys(self.get_search_fields(view, request) or [], "A"), config="english")
+
+ def filter_queryset(self, request: Request, queryset: QuerySet, view: APIView) -> QuerySet:
+ terms = self.get_search_terms(request)
+ if not terms:
+ return queryset
+ vector = self.get_search_vector(request, view)
+ query = reduce(or_, [SearchQuery(term, config="english") for term in terms[:60]])
+ return (
+ queryset.alias(_search_vector=vector, _search_rank=SearchRank(vector, query))
+ .filter(_search_vector=query)
+ .order_by("-_search_rank", "pk")
+ )
+
+
+class MetricSearchFilter(CatalogSearchFilter):
+ def get_search_vector(self, request: Request, view: APIView) -> CombinedExpression:
+ definition = Func(
+ Value("english"),
+ "definition",
+ Value('["string"]'),
+ function="jsonb_to_tsvector",
+ output_field=SearchVectorField(),
+ )
+ return CombinedExpression(
+ super().get_search_vector(request, view),
+ "||",
+ Func(
+ Coalesce(definition, Value("", output_field=SearchVectorField())),
+ Value("A"),
+ function="setweight",
+ output_field=SearchVectorField(),
+ ),
+ output_field=SearchVectorField(),
+ )
+
+
class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/)."""
scope_object = "data_catalog"
lookup_field = "name"
+ filter_backends = [MetricSearchFilter]
+ search_fields = ["name", "display_name", "description"]
serializer_class = MetricSerializer
queryset = Metric.objects.unscoped()
@@ -274,6 +322,8 @@ class CertificationViewSet(
"""Trust marks on warehouse tables and views. Reads exclude soft-deleted targets."""
scope_object = "data_catalog"
+ filter_backends = [CatalogSearchFilter]
+ search_fields = ["table__name", "saved_query__name", "notes"]
serializer_class = CertificationSerializer
queryset = TableCertification.objects.unscoped()
@@ -340,6 +390,8 @@ class RelationshipProposalViewSet(
"""Reviewed join facts. Accepting one promotes it to a real DataWarehouseJoin; rejections persist."""
scope_object = "data_catalog"
+ filter_backends = [CatalogSearchFilter]
+ search_fields = ["source_table_name", "joining_table_name", "reasoning"]
serializer_class = RelationshipProposalSerializer
queryset = RelationshipProposal.objects.unscoped()
diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.py
index 4531a51e29da..e7ee76f88b2f 100644
--- a/products/data_catalog/backend/tests/test_api.py
+++ b/products/data_catalog/backend/tests/test_api.py
@@ -146,15 +146,35 @@ class TestMetricAPI(APIBaseTest):
assert response.status_code == status.HTTP_201_CREATED, response.json()
assert response.json()["definition_kind"] == "MarkdownDefinition"
- def test_list_is_team_scoped(self) -> None:
+ @parameterized.expand(
+ [
+ ("unfiltered", "", ["mine", "unrelated"], "description"),
+ ("search", "activation revenue", ["mine"], "description"),
+ ("natural_language", "what is our activation", ["mine"], "description"),
+ ("stop_words", "what is our", [], "description"),
+ ("display_name", "what is activation", ["mine"], "display_name"),
+ ("definition", "what is activation", ["mine"], "definition"),
+ ("query", "what is count", ["mine"], "query"),
+ ]
+ )
+ def test_list_is_team_scoped(self, name: str, search: str, expected: list[str], match_field: str) -> None:
other_team = Team.objects.create_with_data(
organization=self.organization, initiating_user=self.user, name="Other"
)
- self.client.post(self.url, {"name": "mine", "description": "d"}, format="json")
- Metric.objects.for_team(other_team.id).create(team=other_team, name="theirs", description="d")
-
- names = [row["name"] for row in self.client.get(self.url).json()["results"]]
- assert names == ["mine"]
+ fields: dict[str, object] = {"description": "retention"}
+ if match_field == "definition":
+ fields["definition"] = {"kind": "MarkdownDefinition", "markdown": "Overview\nactivation"}
+ elif match_field == "query":
+ fields["definition"] = {"kind": "HogQLQuery", "query": "SELECT\ncount() FROM events"}
+ else:
+ fields[match_field] = "activation"
+ created = self.client.post(self.url, {"name": "mine", **fields}, format="json")
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ Metric.objects.for_team(other_team.id).create(team=other_team, name="theirs", **fields)
+
+ self.client.post(self.url, {"name": "unrelated", "description": "retention"}, format="json")
+ names = [row["name"] for row in self.client.get(self.url, {"search": search}).json()["results"]]
+ assert sorted(names) == expected
@patch("products.data_catalog.backend.logic.metrics.Database.create_for")
def test_metrics_referencing_denied_tables_are_hidden(self, create_database: MagicMock) -> None:
diff --git a/products/data_catalog/backend/tests/test_certifications.py b/products/data_catalog/backend/tests/test_certifications.py
index c5710d743d7c..960bc32e2570 100644
--- a/products/data_catalog/backend/tests/test_certifications.py
+++ b/products/data_catalog/backend/tests/test_certifications.py
@@ -362,6 +362,29 @@ class TestCertificationAPI(APIBaseTest):
super().setUp()
self.url = f"/api/projects/{self.team.id}/data_catalog/certifications/"
+ @parameterized.expand(
+ [
+ ("table_name", "table", False),
+ ("view_name", "view", False),
+ ("table_notes", "table", True),
+ ("view_notes", "view", True),
+ ]
+ )
+ def test_search_matches_target_names_and_notes(self, name: str, target_type: str, match_notes: bool) -> None:
+ target_factory = _table if target_type == "table" else _view
+ target_field = "table" if target_type == "table" else "saved_query"
+ target = target_factory(self.team, name="retention" if match_notes else "activation")
+ matched = TableCertification.objects.for_team(self.team.id).create(
+ team=self.team, notes="activation" if match_notes else "", **{target_field: target}
+ )
+ unrelated = target_factory(self.team, name="unrelated")
+ TableCertification.objects.for_team(self.team.id).create(team=self.team, **{target_field: unrelated})
+
+ response = self.client.get(self.url, {"search": "what is activation"})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert [row["id"] for row in response.json()["results"]] == [str(matched.id)]
+
def test_create_and_certify(self) -> None:
table = _table(self.team)
created = self.client.post(self.url, {"table_id": str(table.id)}, format="json")
diff --git a/products/data_catalog/backend/tests/test_relationships.py b/products/data_catalog/backend/tests/test_relationships.py
index c89e16718c8c..d519631e6f08 100644
--- a/products/data_catalog/backend/tests/test_relationships.py
+++ b/products/data_catalog/backend/tests/test_relationships.py
@@ -254,6 +254,31 @@ class TestRelationshipAPI(APIBaseTest):
super().setUp()
self.url = f"/api/projects/{self.team.id}/data_catalog/relationship_proposals/"
+ @parameterized.expand(
+ [
+ (field, status_filter)
+ for field in ("source_table_name", "joining_table_name", "reasoning")
+ for status_filter in ("proposed", "rejected")
+ ]
+ )
+ def test_search_combines_with_status(self, field: str, status_filter: str) -> None:
+ matches: dict[str, RelationshipProposal] = {}
+ for proposal_status in (RelationshipStatus.PROPOSED, RelationshipStatus.REJECTED):
+ matches[proposal_status] = RelationshipProposal.objects.for_team(self.team.id).create(
+ team=self.team,
+ undirected_fingerprint=f"matching-{proposal_status}",
+ status=proposal_status,
+ **{**_JOIN, field: "activation"},
+ )
+ RelationshipProposal.objects.for_team(self.team.id).create(
+ team=self.team, undirected_fingerprint="unrelated", **_JOIN
+ )
+
+ response = self.client.get(self.url, {"search": "activation", "status": status_filter})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert [row["id"] for row in response.json()["results"]] == [str(matches[status_filter].id)]
+
def test_create_proposal(self) -> None:
response = self.client.post(self.url, _JOIN, format="json")
assert response.status_code == status.HTTP_201_CREATED, response.json()
diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.ts
index f291d93d8498..6463c9fd14a3 100644
--- a/products/data_catalog/frontend/generated/api.schemas.ts
+++ b/products/data_catalog/frontend/generated/api.schemas.ts
@@ -560,6 +560,10 @@ export type DataCatalogCertificationsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * A search term.
+ */
+ search?: string
}
export type DataCatalogMetricsListParams = {
@@ -571,6 +575,10 @@ export type DataCatalogMetricsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * A search term.
+ */
+ search?: string
}
export type DataCatalogMetricsRunCreateParams = {
@@ -609,6 +617,10 @@ export type DataCatalogRelationshipProposalsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * A search term.
+ */
+ search?: string
/**
* Filter by proposed/accepted/rejected.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 165b06ec388b..5e553352d0b9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -121034,6 +121034,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * A search term.
+ */
+ search?: string;
};
export type DataCatalogMetricsListParams = {
@@ -121045,6 +121049,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * A search term.
+ */
+ search?: string;
};
export type DataCatalogMetricsRunCreateParams = {
@@ -121083,6 +121091,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * A search term.
+ */
+ search?: string;
/**
* Filter by proposed/accepted/rejected.
*/
diff --git a/services/mcp/src/generated/data_catalog/api.ts b/services/mcp/src/generated/data_catalog/api.ts
index fdfd137bc04d..e2afca09a0ef 100644
--- a/services/mcp/src/generated/data_catalog/api.ts
+++ b/services/mcp/src/generated/data_catalog/api.ts
@@ -76,6 +76,7 @@ export const DataCatalogMetricsListParams = () => zod.object({
export const DataCatalogMetricsListQueryParams = () => 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('A search term.'),
})
/**
diff --git a/services/mcp/src/tools/generated/data_catalog.ts b/services/mcp/src/tools/generated/data_catalog.ts
index 1ed829430449..7330cec0725f 100644
--- a/services/mcp/src/tools/generated/data_catalog.ts
+++ b/services/mcp/src/tools/generated/data_catalog.ts
@@ -753,6 +753,7 @@ const metricList = (): ToolBase<
query: {
limit: params.limit,
offset: params.offset,
+ search: params.search,
},
})
const filtered = {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/metric-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/metric-list.json
index 8331b796ac73..bc560e594d69 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/metric-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/metric-list.json
@@ -8,6 +8,10 @@
"offset": {
"description": "The initial index from which to return the results.",
"type": "number"
+ },
+ "search": {
+ "description": "A search term.",
+ "type": "string"
}
},
"type": "object"