{"data":{"slug":"github-lobehub-lobehub-agents-skills-full-text-search-a1eb4434e26a","title":"Product Full-Text Search for LobeHub Data","summary":"Search through LobeHub's product data including agents, topics, messages, files, knowledge bases, documents, chat groups, and memories using FtsSearchRepo, pg_search\/pg_like, or Elasticsearch. Excludes external web search providers.","url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-full-text-search-a1eb4434e26a","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-lobehub-lobehub-agents-skills-full-text-search-a1eb4434e26a","markdown_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-full-text-search-a1eb4434e26a.md","download_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-full-text-search-a1eb4434e26a\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before using Elasticsearch, ensure it supports every entity in FTS_SEARCH_BACKEND_ENTITIES through coverage tests. For pg_like, ensure it is explicitly selected and not used as a fallback; missing extensions or unreachable services must fail.","instructions":"---\nname: full-text-search\ndescription: 'Use for product search: FtsSearchRepo, pg_search\/pg_like\/Elasticsearch, mapping migrations, projections, Outbox sync, reindexing and performance. Excludes agent web search.'\n---\n\n# Product Full-Text Search\n\nThis skill covers search over LobeHub-owned product data such as agents, topics, messages, files,\nknowledge bases, documents, chat groups, and memories. It does not cover the agent's external web\nsearch providers under `apps\/server\/src\/services\/search\/` or builtin web-browsing tools.\n\n## Architecture\n\nProduct reads follow one stable path:\n\n```text\nrouter\/service -> createFtsSearchRepo -> FtsSearchRepo -> selected backend -> existing result schema\n```\n\n- `apps\/server\/src\/services\/ftsSearch\/` owns request-scoped provider selection, Elasticsearch\n  configuration, its HTTP client, and backend telemetry. Routers and domain services must call\n  `createFtsSearchRepo`; they must not construct providers themselves.\n- `packages\/database\/src\/repositories\/ftsSearch\/` owns the provider-neutral contract and the concrete\n  PostgreSQL and Elasticsearch implementations. Keep public result shapes stable in `FtsSearchRepo`.\n- `packages\/types\/src\/ftsSearch.ts` owns the shared searchable-entity list and search domain types.\n- `packages\/database\/src\/repositories\/ftsSearchDocument\/` owns Elasticsearch document schemas,\n  mappings, queryable fields, and source-to-document projection.\n- `packages\/database\/src\/schemas\/ftsSearchSyncOutbox.ts` and\n  `packages\/database\/src\/repositories\/ftsSearchSyncOutbox\/` own durable change capture, claims,\n  retries, dead letters, leases, revision fences, and capture-definition validation.\n- `scripts\/elasticsearchReindex\/` owns the resumable full-backfill command and its operational\n  runtime. Shared database source queries and document construction remain in\n  `packages\/database\/src\/repositories\/ftsSearchDocument\/`. `apps\/server\/src\/services\/ftsSearchSync\/` and\n  `scripts\/elasticsearchSync\/` own continuous incremental draining.\n- `packages\/env\/src\/ftsSearch.ts` owns generic Elasticsearch environment variables.\n\n## Provider and Permission Invariants\n\n- `FTS_SEARCH_PROVIDER` is a deployment-level provider selector with current values `pg_search`,\n  `elasticsearch`, and `pg_like`. It is not a feature flag or a user rollout. Add another enum value\n  only when its provider covers all entities in `FTS_SEARCH_BACKEND_ENTITIES` end to end, including\n  `mode: 'candidates'` when the provider enables `ftsSearchCandidateEnabled`.\n- Provider errors, missing configuration, and unsupported candidate behavior must remain visible.\n  Never silently retry through another provider. `pg_like` is an explicitly selected lightweight\n  provider, not an implicit fallback: a missing extension or unreachable service must still fail.\n- `packages\/database\/src\/repositories\/ftsSearch\/postgres\/` owns the query, permission, pagination,\n  and hydration layer shared by PostgreSQL providers. `pgSearch\/` and `pgLike\/` own only their\n  provider adapter, dialect, and provider-specific candidate behavior. Neither provider directory\n  may import the other, so either provider can be retired without owning shared functionality.\n- Before selecting Elasticsearch, require coverage tests proving that it supports every entity in\n  the provider-neutral backend contract. Do not add per-entity routing between providers.\n- Preserve `userId`, `workspaceId`, and caller-agent visibility throughout every provider. Candidate\n  retrieval must not broaden the caller's scope.\n- Where Elasticsearch only supplies candidate IDs, PostgreSQL hydration and parent checks remain\n  the authoritative permission boundary. Do not return raw Elasticsearch hits directly when the\n  existing result path requires database authorization or hydration.\n- Provider implementations return the existing hydrated response types and ordering contract. Do\n  not make routers understand provider-specific result shapes.\n\n## Changing a Searchable Entity\n\n### Scope for pg_like\n\n`pg_like` primarily serves individual users with small datasets. Review it for correct matching,\npermissions, and usable result ordering at that scale. For richer search quality or larger datasets,\nrecommend self-hosted Elasticsearch or Elastic Cloud. Do not add indexes or change the database\nschema as part of pg_like optimization. Keep repairs bounded; distinguish new implementation bugs\nfrom shared provider limitations and deliberate lightweight-search trade-offs. Do not infer a\npersonal-user performance problem from large shared development datasets without representative\nmeasurements.\n\n### Entity changes\n\nTreat an entity addition or projection change as one cross-layer change. Inspect and update every\napplicable item:\n\n1. `FTS_SEARCH_DOCUMENT_ENTITIES` and shared request\/result types.\n2. Search document schema, mapping, text fields, filters, fixtures, and mapping parity tests.\n3. `FtsSearchDocumentBuilder`, including soft deletion and fanout from related source rows.\n4. PostgreSQL and Elasticsearch backend behavior, permission hydration, pagination, and ranking.\n5. Capture functions\/triggers or fanout queries in `captureInfrastructure.ts`.\n6. Reindex checkpoints, Outbox draining, metrics, and self-host documentation.\n\nSchema fields, mappings, builders, and fixed fixtures must agree. Current mapping fields plus\nexplicit `FTS_SEARCH_RETAINED_SOURCE_PROPERTIES` must equal the current Zod fields, without overlap.\nRetained source properties keep older open indexes writable during field removals; keep the builder\nproducing them until those indexes are closed. They must not appear in current query metadata.\nA field outside the document schema must not appear in a mapping or query field list.\n\nElasticsearch `multi_match` query length is bounded by a shared leaf-clause budget divided by the\nselected query-field count. Adding a field reduces that entity's safe query length, and changing a\nquery analyzer to emit multiple terms per Unicode code point requires revisiting the budget and its\nfield-count regression tests.\n\n## Capture, Reindex, and Sync\n\n- Regular database migrations own durable schema: the revision sequence, Outbox table and indexes,\n  and schema-managed source indexes such as the Memory fanout GIN index.\n- Capture functions and triggers are installed only when an operator explicitly enables the\n  Elasticsearch path. `installCaptureInfrastructure()` is transactional, definition-checked,\n  idempotent for an exact installation, and fail-closed for partial or altered definitions.\n- Do not install capture for every PostgreSQL-only instance. Do not move a normal schema index into\n  the runtime installer merely because it supports capture.\n- The Outbox coalesces by `(entity, document_id)`. A newer capture resets retry\/dead-letter state and\n  allocates a new revision only after locking the conflicting row, preserving same-document commit\n  order.\n- Sequence allocation is non-transactional. Use the existing write fences and committed revision\n  boundary; never treat `last_value` alone as proof that all earlier Outbox rows are visible.\n- Claims use the precise lease timestamp as a fencing token. A stale worker must not acknowledge,\n  fail, or release work reclaimed by another worker.\n- Permanent failures and exhausted retries become durable dead letters. A drain that creates or\n  observes dead work must fail instead of continuing to publish a successful cutover signal.\n- Full backfill does not replace continuous sync. For the initial PostgreSQL-to-Elasticsearch\n  cutover, keep the application on PostgreSQL until aliases are ready and the Outbox is empty and\n  stable, then switch explicitly. Later mapping upgrades keep searches on the existing Elasticsearch\n  alias until promotion.\n\nThe supported operator entrypoints below run from the OSS repository root. A wrapping repository\nmay expose different package scripts; check its `package.json` before invoking these or the mapping\nmigration commands linked below.\n\n```bash\nbun run db:install-fts-search-capture\nbun run fts-search:reindex -- --status\nbun run fts-search:reindex -- --apply --yes\nbun run fts-search:sync -- --max-steps=8 --yes\nbun run scripts\/pgSearchCleanup\/index.ts --status\nbun run scripts\/pgSearchCleanup\/index.ts --apply --yes\n```\n\n## Mapping Generations\n\nDocker startup runs `fts-search-elasticsearch-reindex.cjs --startup --yes` after PostgreSQL\nmigrations when the selected provider is Elasticsearch. It blocks serving until index migration\nand catch-up succeed. Persist the same checkpoint volume across application and migration\ncontainers; failed namespace locks still require explicit recovery. Continuous sync remains a\nseparate worker. Hosted and manual workflows keep their explicit migration commands.\n\nFor mapping changes, generation operations, repeat\/resume behavior, or deployment integration, read\n[Mapping migration workflow](references\/mapping-migrations.md). It routes to the public command guide\nand adds recovery, automation, and local Docker rehearsal rules.\n\n- Treat managed and Serverless Elasticsearch APIs as capability-constrained. Create operational\n  metadata and control indexes with the smallest portable request, and add topology, storage, or\n  index settings only after verifying that the target service supports them; settings accepted by a\n  self-managed cluster may be rejected by a managed service.\n- Make idempotent Elasticsearch resource creation depend on the structured error type, such as\n  `resource_already_exists_exception`, not a broad HTTP status range. Preserve any other creation\n  failure and stop before follow-up reads or mutations instead of turning a rejected request into a\n  misleading verification error.\n\nElasticsearch cannot change an existing field's type or index-time analyzer in place. The code\ndeclares the target and Elasticsearch records the live state, per entity:\n\n- `FTS_SEARCH_INDEX_DEFINITIONS[entity].schemaVersion` is the declared generation; the fingerprint is\n  `sha256` of the mapping plus the shared analysis. Add complete changed-entity definitions in a new\n  `ftsSearchDocument\/migration\/NNNN-meaningful-name\/` batch, register it and update current pointers\n  in `migration\/index.ts`. Append expected fingerprints in `__tests__\/schemaSnapshots.json`; preserve\n  published batches and baselines. `mappings.test.ts` and `migration\/index.test.ts` check current\n  parity, history, version bumps and fingerprint changes. See `migration\/README.md` for ownership.\n  Shared analysis changes alter\n  every entity fingerprint and classify as breaking for every entity; bump all affected versions\n  and rebuild rather than using in-place upgrades.\n- Every physical index `<alias>-v<n>` or same-schema rebuild `<alias>-v<n>-r<runId>` carries\n  `_meta.{reindex_run_id, schema_version, schema_fingerprint}`; the alias marks the live generation.\n  A rebuild suffix is physical identity, not a schema-version bump. Indexes created before fingerprints\n  existed may omit the fingerprint, but still need a valid run ID and schema version for sync\n  readiness. `_meta.schema_version` wins over the `-v<n>` suffix because an in-place upgrade advances\n  `_meta` without renaming the index.\n- The sync runtime accepts an alias that still serves an older generation (upgrade in progress) and\n  refuses one that serves a newer generation or a different fingerprint of the declared version. It\n  writes every change to all open `<alias>-v*` indexes plus the alias write index, pruning each\n  document to the fields that index maps (every generation is `dynamic: strict`), so a new\n  generation can be backfilled beside the live one; a bulk work item is acknowledged only when\n  every existing generation accepted it (2xx or 409 conflict).\n- Canonical migration checkpoints remain keyed by `(namespace, schemaVersion)`. Explicit current-version\n  rebuild checkpoints add `reindexRunId`, so repeated v1 rebuilds never reuse a completed v1 cursor.\n  `--apply` groups the requested entities by declared version, treats existing aliases as an\n  upgrade (no `--fresh-run`), leaves existing aliases in place, and emits `promotion_pending`. A\n  completed first install creates aliases. Promoting a newer generation requires a completed\n  checkpoint, a fingerprint match when targeting the declared version, and an idle target-entity Outbox. Rollback\n  to an older stamped generation can use its metadata without a retained checkpoint;\n  `--retire` requires `in_sync` and only closes old generations; explicit `--purge` installs\n  exact-index templates forbidding auto-creation before deleting eligible closed generations.\n  `--in-place` requires\n  `mappingChange: additive`, widens the live index with `PUT _mapping`, pins the checkpoint to that\n  index, and backfills with `external_gte` so concurrent sync writes win.\n- Use `--apply --rebuild-current --entity=<entity> --yes` when projection or capture semantics changed\n  without a physical mapping change and historical documents must be regenerated from PostgreSQL.\n  Deploy runtime support first: sync must recognize `-r<runId>` generations before one is created.\n  Resume with the reported `--run-id=<uuid>`. Promote with the exact\n  `--generation=<alias>-v<n>-r<uuid>` because version-only selection is ambiguous. The old generation\n  remains dual-written for rollback and becomes same-version retirement-eligible only after the\n  promotion records which live run superseded it.\n- Checkpoints are local files, not Drizzle migration history. Preserve `ES_REINDEX_STATE_DIR` across\n  invocations. Completed runs skip backfill; incomplete runs resume from saved cursors. Mutating CLI\n  commands share a non-expiring Elasticsearch namespace lock, independent of checkpoint location.\n  A failed command retains its lock when its outcome may be uncertain. Before `--release-lock=<owner> --yes`, stop the previous process and resolve pending requests; never assume age proves it stopped.\n  The lock does not serialize old binaries or external operator actions.\n- Reconciliation is exact only on a first install; once an alias serves an entity, concurrent sync\n  writes make a higher Elasticsearch count legitimate and only a shortfall fails.\n- `scripts\/elasticsearchReindex\/runtime\/generationService.ts` owns classification (`missing`,\n  `unmanaged`, `in_sync`, `drift`, `upgrade_available`, `rollback_required`), promotion, and\n  retirement; keep them free of Cloud-specific policy.\n\nRead `docs\/self-hosting\/advanced\/neon-pg-search-migration.mdx` or its Chinese counterpart before\nchanging the operational sequence. When database rollout or index cost affects the design, also\nuse the `db-migrations` skill and measure the relevant operation on the actual Dev database before\nadding manual or deferred release steps.\n\n## Observability and Product Analytics\n\n- Server provider metrics and traces live in `apps\/server\/src\/services\/ftsSearch\/observability.ts`.\n  Keep labels bounded: entity, provider, operation, outcome, and coarse error type are acceptable;\n  raw queries, user IDs, document IDs, and index contents are not.\n- User-perceived search behavior lives with the open-source Command Menu in\n  `src\/features\/CommandMenu\/analytics.ts`. Product analytics may cover end-to-end duration, rendered\n  result counts, empty results, result clicks, and abandonment without a Cloud business slot.\n- Measurement or analytics failures must never alter the selected provider's result or error.\n- Backend metrics explain provider cost and latency; frontend events explain what the user actually\n  experienced. Do not substitute one for the other.\n\n## Validation\n\n- Add or update focused tests beside every changed provider, mapping, builder, capture, sync, or\n  analytics module.\n- Preserve boundary tests proving callers use `FtsSearchRepo`, providers cannot leak raw result shapes,\n  and telemetry failures do not affect search behavior.\n- Test pagination after authorization drops candidates, delete\/scope-change priority, concurrent\n  Outbox claims and stale settlements, retry\/dead-letter behavior, reindex resume identity, and\n  capture-definition mismatch whenever those paths change.\n- Run `bun run check <changed-files...>` from the repository root. For migration or database-runtime\n  changes, follow the `db-migrations` and `testing` skills and verify against the actual Dev database.\n","use_cases":["Search for specific agents or topics within the product database","Reindex product data to ensure up-to-date search results","Perform advanced filtering and sorting on search results"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/lobehub\/lobehub\/blob\/54382b5c8e81544da454fa6d7b50f461a562c1ee\/.agents\/skills\/full-text-search\/SKILL.md","source_commit":"54382b5c8e81544da454fa6d7b50f461a562c1ee","license":null,"version":null,"listing_approved_at":"2026-11-22","created_at":"2026-11-21T11:14:22.000000Z","updated_at":"2026-11-22T11:17:05.000000Z","seo_title":"Product Full-Text Search for LobeHub Data","seo_description":"Efficiently search through LobeHub's product data including agents, topics, messages, and more. Supports Elasticsearch, pg_search, and pg_like.","seo_keywords":["product search","full-text search","LobeHub search","Elasticsearch search","pg_search integration"]}}