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: full-text search retrieval for knowledge chunks (#61887)

Alex V6022e29cc532
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 6d819b47f8c7..b8eaa4f2e10d 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -4,7 +4,6 @@ Business logic for business_knowledge.
All ORM access, chunking, quota enforcement, and search queries.
"""
-import re
import uuid
import datetime
from dataclasses import dataclass
@@ -13,6 +12,7 @@ from operator import or_
from urllib.parse import urlsplit
from uuid import UUID
+from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.db import (
connection as db_connection,
transaction,
@@ -23,6 +23,7 @@ from django.utils import timezone
import structlog
+from posthog.helpers.full_text_search import process_query
from posthog.models.scoping import with_team_scope
from posthog.security.url_validation import is_url_allowed
@@ -159,7 +160,7 @@ def _bulk_create_chunks(
team_id: int,
chunks: list[_Chunk],
) -> None:
- KnowledgeChunk.objects.bulk_create(
+ created = KnowledgeChunk.objects.bulk_create(
[
KnowledgeChunk(
id=_chunk_id(source.id, document.stable_id, c.heading_path, c.ordinal),
@@ -174,6 +175,14 @@ def _bulk_create_chunks(
for c in chunks
]
)
+ # Populate the FTS vector here (the single chunk-creation choke point) so it
+ # stays correct everywhere — including the test schema, which is built from
+ # model state with migrations disabled and so would never run a DB trigger.
+ # Computed in Postgres via `to_tsvector('english', content)`.
+ if created:
+ KnowledgeChunk.objects.filter(team_id=team_id, id__in=[c.id for c in created]).update(
+ content_search_vector=SearchVector("content", config="english")
+ )
# --- Quota enforcement -------------------------------------------------------
@@ -1464,8 +1473,6 @@ def has_ready_sources(team_id: int) -> bool:
_SEARCH_LIMIT_CAP = 20
-_WORD_RE = re.compile(r"\w{2,}", re.UNICODE)
-
@dataclass(frozen=True)
class KnowledgeSearchResult:
@@ -1490,34 +1497,49 @@ def search_knowledge(
limit: int = 10,
) -> list[KnowledgeSearchResult]:
"""
- Word-level ILIKE search over chunks belonging to READY sources.
-
- Splits the query into words (>=2 chars) and matches chunks containing
- ANY of them (OR). Uses the GIN trigram index for performance. The top
- `limit` matches (shortest, most focused chunks first) anchor the result;
- each anchor is expanded to its ordinal-adjacent neighbours (ordinal n-1,
- n, n+1 within the same document) so the agent gets continuous context
- instead of isolated fragments. `ordinal` is document-global and
- contiguous, so neighbours never cross into a different document.
+ Full-text relevance search over chunks belonging to READY sources.
+
+ Builds an `english`-config `tsquery` from the user query (stemming +
+ stopword removal + prefix match on the last term, via `process_query`) with
+ OR semantics, and matches it against the chunk `content_search_vector` using
+ the GIN index. The top `limit` matches by `ts_rank` (so chunks hitting more
+ query terms rank first) anchor the result; each anchor is expanded to its
+ ordinal-adjacent neighbours (ordinal n-1, n, n+1 within the same document)
+ so the agent gets continuous context instead of isolated fragments.
+ `ordinal` is document-global and contiguous, so neighbours never cross into
+ a different document.
"""
limit = max(1, min(limit, _SEARCH_LIMIT_CAP))
- words = _WORD_RE.findall(query)
- if not words:
+ # `process_query` strips tsquery metacharacters and joins terms with a
+ # trailing prefix match; returns None only when the result is an empty
+ # string (i.e. the query contained nothing but unsafe characters).
+ # Stopword-only inputs are not caught here — they pass through as a
+ # non-empty string and PostgreSQL discards the stopwords inside
+ # to_tsquery, yielding no matches.
+ processed = process_query(query)
+ if processed is None:
return []
-
- word_filters = reduce(or_, (Q(content__icontains=w) for w in words))
+ # OR rather than AND the terms: the agent sends natural-language questions,
+ # and AND drops any chunk missing a single term (e.g. "can a customer get a
+ # refund within 30 days" wouldn't match a focused refund chunk). `ts_rank`
+ # still surfaces chunks matching more terms first. `process_query` only ever
+ # inserts " & " as a separator, so the replace is unambiguous.
+ processed = processed.replace(" & ", " | ")
+ search_query = SearchQuery(processed, config="english", search_type="raw")
anchors = list(
KnowledgeChunk.objects.filter(
- word_filters,
team_id=team_id,
source__status=SourceStatus.READY,
document__tombstoned_at__isnull=True,
document__safety_verdict=SafetyVerdict.SAFE,
+ content_search_vector=search_query,
)
+ .annotate(rank=SearchRank(F("content_search_vector"), search_query))
.only("id", "document_id", "ordinal", "char_count")
- .order_by("char_count")[:limit]
+ # `id` is the final tiebreaker so rank+length ties order deterministically.
+ .order_by("-rank", "char_count", "id")[:limit]
)
if not anchors:
return []
diff --git a/products/business_knowledge/backend/migrations/0008_knowledgechunk_content_search_vector.py b/products/business_knowledge/backend/migrations/0008_knowledgechunk_content_search_vector.py
new file mode 100644
index 000000000000..8a363c3ebc8c
--- /dev/null
+++ b/products/business_knowledge/backend/migrations/0008_knowledgechunk_content_search_vector.py
@@ -0,0 +1,24 @@
+# Adds a nullable tsvector column backing full-text relevance search over
+# chunks (replacing the word-level ILIKE scan). The column is additive and
+# nullable — a brief lock, safe online. The vector itself is populated in
+# application code (`logic._bulk_create_chunks`), not a trigger — the test
+# schema is built from model state with migrations disabled, so a
+# migration-only trigger would be absent there. The backing GIN index is built
+# CONCURRENTLY in a separate non-atomic migration (0009).
+
+from django.contrib.postgres.search import SearchVectorField
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("business_knowledge", "0007_knowledgedocument_classification_attempts"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="knowledgechunk",
+ name="content_search_vector",
+ field=SearchVectorField(null=True),
+ ),
+ ]
diff --git a/products/business_knowledge/backend/migrations/0009_bk_chunk_content_tsv_index.py b/products/business_knowledge/backend/migrations/0009_bk_chunk_content_tsv_index.py
new file mode 100644
index 000000000000..7c3f4b5e81e3
--- /dev/null
+++ b/products/business_knowledge/backend/migrations/0009_bk_chunk_content_tsv_index.py
@@ -0,0 +1,38 @@
+# Builds the GIN index over `content_search_vector` CONCURRENTLY so it never
+# holds a write lock. Isolated in its own non-atomic migration (split from the
+# AddField in 0008) per the CONCURRENTLY-must-run-outside-a-transaction rule.
+
+from django.contrib.postgres.indexes import GinIndex
+from django.db import migrations
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("business_knowledge", "0008_knowledgechunk_content_search_vector"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddIndex(
+ model_name="knowledgechunk",
+ index=GinIndex(
+ fields=["content_search_vector"],
+ name="bk_chunk_content_tsv",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="bk_chunk_content_tsv",
+ table_name="posthog_business_knowledge_knowledgechunk",
+ columns="(content_search_vector)",
+ using="gin",
+ ),
+ ],
+ ),
+ ]
diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txt
index 778ceb72f8b8..b544d222fa88 100644
--- a/products/business_knowledge/backend/migrations/max_migration.txt
+++ b/products/business_knowledge/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0007_knowledgedocument_classification_attempts
+0009_bk_chunk_content_tsv_index
diff --git a/products/business_knowledge/backend/models/knowledge_chunk.py b/products/business_knowledge/backend/models/knowledge_chunk.py
index 39d71b732cec..d97fa73468b8 100644
--- a/products/business_knowledge/backend/models/knowledge_chunk.py
+++ b/products/business_knowledge/backend/models/knowledge_chunk.py
@@ -1,6 +1,7 @@
from typing import Any
from django.contrib.postgres.indexes import GinIndex
+from django.contrib.postgres.search import SearchVectorField
from django.db import models
from posthog.models.scoping.manager import TeamScopedManager
@@ -34,6 +35,14 @@ class KnowledgeChunk(models.Model):
# Rough character length; kept separately so the agent can ORDER BY / LIMIT
# without loading content into HogQL context.
char_count = models.PositiveIntegerField()
+ # `english`-config tsvector of `content`, backing full-text relevance search.
+ # Maintained in `logic._bulk_create_chunks` right after the rows are inserted
+ # (the single chunk-creation choke point) rather than by a DB trigger or a
+ # GeneratedField: the test schema is built from model state with migrations
+ # disabled, so a migration-only trigger would not exist there, and a
+ # GeneratedField can't use the STABLE two-arg `to_tsvector(text, text)`.
+ # Nullable so the INSERT can land before the vector is computed.
+ content_search_vector = SearchVectorField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
objects = TeamScopedManager()
@@ -44,6 +53,7 @@ class KnowledgeChunk(models.Model):
models.Index(fields=["team", "source"], name="bk_chunk_team_source"),
models.Index(fields=["document", "ordinal"], name="bk_chunk_doc_ordinal"),
GinIndex(fields=["content"], opclasses=["gin_trgm_ops"], name="bk_chunk_content_trgm"),
+ GinIndex(fields=["content_search_vector"], name="bk_chunk_content_tsv"),
]
# One physical chunk per (document, heading_path, ordinal). Matches
# the uuid5 seed so the deterministic id can never collide silently.
diff --git a/products/business_knowledge/backend/tests/fixtures/retrieval_eval.yaml b/products/business_knowledge/backend/tests/fixtures/retrieval_eval.yaml
index ff6baab4bdf3..a9f8706f6998 100644
--- a/products/business_knowledge/backend/tests/fixtures/retrieval_eval.yaml
+++ b/products/business_knowledge/backend/tests/fixtures/retrieval_eval.yaml
@@ -16,6 +16,16 @@
expect_found: true
- query: "30 days"
expect_found: true
+ # Stemming: "refunding" -> "refund", which the old ILIKE substring scan missed.
+ - query: "refunding"
+ expect_found: true
+ # Stemming: "cancelled" -> "cancel" matches "cancellation" in the text.
+ - query: "cancelled subscription"
+ expect_found: true
+ # Natural-language question: OR semantics + ts_rank still surface the chunk
+ # even though not every term appears (AND semantics would return nothing).
+ - query: "can a customer get a refund within 30 days of purchase"
+ expect_found: true
- query: "quantum physics research"
expect_found: false
diff --git a/products/business_knowledge/backend/tests/test_retrieval_eval.py b/products/business_knowledge/backend/tests/test_retrieval_eval.py
index a65d43dd3887..679a42428776 100644
--- a/products/business_knowledge/backend/tests/test_retrieval_eval.py
+++ b/products/business_knowledge/backend/tests/test_retrieval_eval.py
@@ -109,3 +109,15 @@ class TestRetrievalEval(BaseTest):
assert r.source_name == "Refund Policy"
assert r.chunk_id is not None
assert r.source_id is not None
+
+ def test_ranking_returns_most_relevant_source_first(self) -> None:
+ # A term that only appears in the onboarding doc must rank that doc's
+ # chunk first — FTS relevance ordering, not insertion order.
+ results = logic.search_knowledge(self.team.id, "tracking snippet")
+ assert len(results) > 0
+ assert results[0].source_name == "Onboarding Guide"
+
+ def test_stopword_only_query_returns_nothing(self) -> None:
+ # `english` config drops stopwords, so a query of only stopwords yields an
+ # empty tsquery and therefore no matches (rather than erroring).
+ assert logic.search_knowledge(self.team.id, "the and of") == []