Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(self-host): add optional Elasticsearch to Docker Compose (#19028)

YuTengjing330c12a76010
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
index 6f925279f0e..79762cc30f6 100644
--- a/.agents/skills/full-text-search/SKILL.md
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -100,6 +100,8 @@ bun run db:install-fts-search-capture
bun run fts-search:reindex -- --status
bun run fts-search:reindex -- --apply --yes
bun run fts-search:sync -- --max-steps=8 --yes
+bun run scripts/pgSearchCleanup/index.ts --status
+bun run scripts/pgSearchCleanup/index.ts --apply --yes
```
Read `docs/self-hosting/advanced/elasticsearch-migration.mdx` or its Chinese counterpart before
diff --git a/Dockerfile b/Dockerfile
index fccffdb7c3e..33afb539d76 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -70,6 +70,9 @@ COPY apps/desktop/src/main/package.json ./apps/desktop/src/main/package.json
COPY apps/share/package.json ./apps/share/package.json
COPY apps/workbench/package.json ./apps/workbench/package.json
+# @neondatabase/serverless is required at load time by drizzle-orm/neon-serverless, which the
+# bundled Elasticsearch sync CLI imports through the shared server DB factory even when
+# DATABASE_DRIVER=node selects the pg driver; without it the sync container crash-loops.
RUN set -e && \
if [ "${USE_CN_MIRROR:-false}" = "true" ]; then \
export SENTRYCLI_CDNURL="https://npmmirror.com/mirrors/sentry-cli"; \
@@ -84,7 +87,7 @@ RUN set -e && \
mkdir -p /deps && \
cd /deps && \
echo '{"name":"deps","private":true}' > package.json && \
- pnpm add pg drizzle-orm
+ pnpm add pg drizzle-orm @neondatabase/serverless
COPY . .
@@ -96,6 +99,7 @@ RUN rm -rf src/app/desktop "src/app/(backend)/trpc/desktop"
RUN npm run build:docker
RUN pnpm exec esbuild scripts/elasticsearchReindex/index.ts --bundle --platform=node --format=cjs --outfile=/app/fts-search-elasticsearch-reindex.cjs --external:pg --external:drizzle-orm '--external:drizzle-orm/*'
RUN pnpm exec esbuild scripts/elasticsearchSync/cli.ts --bundle --platform=node --format=cjs --outfile=/app/fts-search-elasticsearch-sync.cjs --external:pg --external:drizzle-orm '--external:drizzle-orm/*'
+RUN pnpm exec esbuild scripts/pgSearchCleanup/index.ts --bundle --platform=node --format=cjs --outfile=/app/fts-search-pg-search-cleanup.cjs --external:pg
# Preserve SWC helpers referenced through pnpm virtual-store symlinks by Next.js.
RUN mkdir -p /runtime-deps && cp -a node_modules/.pnpm/@swc+helpers@* /runtime-deps/
@@ -119,20 +123,26 @@ COPY --from=builder /app/scripts/migrateServerDB/docker.cjs /app/docker.cjs
COPY --from=builder /app/scripts/migrateServerDB/errorHint.js /app/errorHint.js
COPY --from=builder /app/fts-search-elasticsearch-reindex.cjs /app/fts-search-elasticsearch-reindex.cjs
COPY --from=builder /app/fts-search-elasticsearch-sync.cjs /app/fts-search-elasticsearch-sync.cjs
+COPY --from=builder /app/fts-search-pg-search-cleanup.cjs /app/fts-search-pg-search-cleanup.cjs
# copy dependencies
COPY --from=builder /deps/node_modules/.pnpm /app/node_modules/.pnpm
COPY --from=builder /deps/node_modules/pg /app/node_modules/pg
COPY --from=builder /runtime-deps/ /app/node_modules/.pnpm/
COPY --from=builder /deps/node_modules/drizzle-orm /app/node_modules/drizzle-orm
+COPY --from=builder /deps/node_modules/@neondatabase /app/node_modules/@neondatabase
# Copy server launcher and shared scripts
COPY --from=builder /app/scripts/serverLauncher/startServer.js /app/startServer.js
COPY --from=builder /app/scripts/_shared /app/scripts/_shared
+# /app/.elasticsearch-reindex is the default checkpoint directory of the Elasticsearch reindex
+# command. Creating it here lets a Docker named volume mounted on it inherit nextjs ownership so
+# the one-off Compose service can write checkpoints without running as root.
RUN set -e && \
addgroup -S -g 1001 nodejs && \
adduser -D -G nodejs -H -S -h /app -u 1001 nextjs && \
+ mkdir -p /app/.elasticsearch-reindex && \
chown -R nextjs:nodejs /app /etc/proxychains4.conf
## Production image, copy all the files and run next
diff --git a/apps/server/src/services/ftsSearch/config.test.ts b/apps/server/src/services/ftsSearch/config.test.ts
new file mode 100644
index 00000000000..8838992662b
--- /dev/null
+++ b/apps/server/src/services/ftsSearch/config.test.ts
@@ -0,0 +1,62 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ ftsSearchEnv: {} as Record<string, string | undefined>,
+}));
+
+vi.mock('@/envs/ftsSearch', () => ({ ftsSearchEnv: mocks.ftsSearchEnv }));
+
+const loadConfig = async () => {
+ vi.resetModules();
+ const { loadElasticsearchFtsSearchConfig } = await import('./index');
+ return loadElasticsearchFtsSearchConfig();
+};
+
+describe('loadElasticsearchFtsSearchConfig', () => {
+ beforeEach(() => {
+ for (const key of Object.keys(mocks.ftsSearchEnv)) delete mocks.ftsSearchEnv[key];
+ mocks.ftsSearchEnv.ES_INDEX_NAMESPACE = 'lobehub';
+ mocks.ftsSearchEnv.ES_URL = 'https://search.example.com';
+ });
+
+ it('loads the Elastic Cloud configuration with an API key', async () => {
+ mocks.ftsSearchEnv.ES_API_KEY = 'test-api-key';
+
+ await expect(loadConfig()).resolves.toEqual({
+ allowInsecureHttp: false,
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
+ url: 'https://search.example.com',
+ });
+ });
+
+ it('remains unconfigured without an API key unless insecure HTTP is explicitly allowed', async () => {
+ await expect(loadConfig()).resolves.toBeUndefined();
+
+ mocks.ftsSearchEnv.ES_ALLOW_INSECURE_HTTP = 'false';
+ await expect(loadConfig()).resolves.toBeUndefined();
+ });
+
+ it('loads a private-network configuration without an API key when explicitly allowed', async () => {
+ mocks.ftsSearchEnv.ES_ALLOW_INSECURE_HTTP = 'true';
+ mocks.ftsSearchEnv.ES_URL = 'http://elasticsearch:9200';
+
+ await expect(loadConfig()).resolves.toEqual({
+ allowInsecureHttp: true,
+ apiKey: undefined,
+ indexNamespace: 'lobehub',
+ url: 'http://elasticsearch:9200',
+ });
+ });
+
+ it('remains unconfigured without a URL or namespace', async () => {
+ mocks.ftsSearchEnv.ES_API_KEY = 'test-api-key';
+ delete mocks.ftsSearchEnv.ES_URL;
+ await expect(loadConfig()).resolves.toBeUndefined();
+
+ mocks.ftsSearchEnv.ES_URL = 'https://search.example.com';
+ delete mocks.ftsSearchEnv.ES_INDEX_NAMESPACE;
+ await expect(loadConfig()).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.test.ts b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
index 6f959d3a4bd..96a764aca3a 100644
--- a/apps/server/src/services/ftsSearch/elasticsearch.test.ts
+++ b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
@@ -38,6 +38,53 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
).not.toThrow();
});
+ it('rejects an API key over plaintext HTTP even when insecure HTTP is allowed', () => {
+ expect(
+ () =>
+ new ElasticsearchFtsSearchHttpClient({
+ allowInsecureHttp: true,
+ apiKey: 'test-api-key',
+ url: 'http://elasticsearch:9200',
+ }),
+ ).toThrow('must not be sent over plaintext HTTP');
+ });
+
+ it('requires an API key unless insecure private-network access is explicitly allowed', () => {
+ expect(
+ () => new ElasticsearchFtsSearchHttpClient({ url: 'https://search.example.com' }),
+ ).toThrow('API key is required unless ES_ALLOW_INSECURE_HTTP=true');
+ });
+
+ it('sends unauthenticated requests to an explicitly insecure private-network endpoint', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ hits: { hits: [] }, took: 1 }), {
+ headers: { 'Content-Type': 'application/json' },
+ status: 200,
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ allowInsecureHttp: true,
+ url: 'http://elasticsearch:9200',
+ });
+
+ await client.search({
+ body: { query: { match_all: {} } },
+ entity: 'agents',
+ executedQueryChars: 1,
+ index: 'lobehub-agents',
+ originalQueryChars: 1,
+ pagination: 'bounded',
+ queryFieldCount: 1,
+ truncated: false,
+ });
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [endpoint, init] = fetchMock.mock.calls[0];
+ expect(String(endpoint)).toBe('http://elasticsearch:9200/lobehub-agents/_search');
+ expect(Object.keys(init.headers)).not.toContain('Authorization');
+ });
+
it('returns no write targets without making requests when no aliases are provided', async () => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.ts b/apps/server/src/services/ftsSearch/elasticsearch.ts
index ae785e1898d..8476cd1a7e0 100644
--- a/apps/server/src/services/ftsSearch/elasticsearch.ts
+++ b/apps/server/src/services/ftsSearch/elasticsearch.ts
@@ -9,7 +9,7 @@ import type {
ElasticsearchFtsSearchInput,
ElasticsearchFtsSearchResponse,
} from '@/database/repositories/ftsSearch';
-import { parseElasticsearchUrl } from '@/database/repositories/ftsSearch/elasticsearch/url';
+import { resolveElasticsearchTransport } from '@/database/repositories/ftsSearch/elasticsearch/url';
import type {
ElasticsearchFtsSearchErrorCode,
@@ -111,7 +111,10 @@ export interface ElasticsearchFtsSearchBulkResponse {
}
export interface ElasticsearchFtsSearchHttpClientOptions {
- apiKey: string;
+ /** Explicit opt-in for plaintext HTTP / no API key on a private container network. */
+ allowInsecureHttp?: boolean;
+ /** Required unless `allowInsecureHttp` is enabled; never sent over plaintext HTTP. */
+ apiKey?: string;
requestTimeoutMs?: number;
url: string;
usage?: FtsSearchUsage;
@@ -236,23 +239,32 @@ const getTraceDetails = (): {
/** HTTP transport that never logs credentials, request text, or Elasticsearch payloads. */
export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchClient {
- private readonly apiKey: string;
+ private readonly authorizationHeader: string | undefined;
private readonly requestTimeoutMs: number;
private readonly url: URL;
private readonly usage: FtsSearchUsage;
constructor({
+ allowInsecureHttp,
apiKey,
requestTimeoutMs = 10_000,
url,
usage = 'unattributed',
}: ElasticsearchFtsSearchHttpClientOptions) {
- this.apiKey = apiKey;
+ const transport = resolveElasticsearchTransport({ allowInsecureHttp, apiKey, url });
+ this.authorizationHeader = transport.authorizationHeader;
this.requestTimeoutMs = requestTimeoutMs;
- this.url = parseElasticsearchUrl(url);
+ this.url = transport.url;
this.usage = usage;
}
+ /** Adds the Authorization header only for authenticated endpoints. */
+ private headers(extra: Record<string, string> = {}): Record<string, string> {
+ return this.authorizationHeader
+ ? { Authorization: this.authorizationHeader, ...extra }
+ : { ...extra };
+ }
+
/** Fails closed unless every incremental destination is a writable alias with tombstone support. */
async assertFtsSearchSyncAliases(aliases: string[]): Promise<void> {
await this.getFtsSearchSyncWriteTargets(aliases);
@@ -261,7 +273,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
private async getFtsSearchSyncWriteTargetMap(aliases: string[]) {
const aliasPath = aliases.map(encodeURIComponent).join(',');
const aliasResponse = await fetch(new URL(`/_alias/${aliasPath}`, this.url), {
- headers: { Authorization: `ApiKey ${this.apiKey}` },
+ headers: this.headers(),
method: 'GET',
signal: AbortSignal.timeout(this.requestTimeoutMs),
});
@@ -327,7 +339,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
this.url,
),
{
- headers: { Authorization: `ApiKey ${this.apiKey}` },
+ headers: this.headers(),
method: 'GET',
signal: AbortSignal.timeout(this.requestTimeoutMs),
},
@@ -382,7 +394,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
this.url,
),
{
- headers: { Authorization: `ApiKey ${this.apiKey}` },
+ headers: this.headers(),
method: 'GET',
signal: AbortSignal.timeout(this.requestTimeoutMs),
},
@@ -452,10 +464,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
const endpoint = new URL('/_bulk?require_alias=true', this.url);
const response = await fetch(endpoint, {
body,
- headers: {
- 'Authorization': `ApiKey ${this.apiKey}`,
- 'Content-Type': 'application/x-ndjson',
- },
+ headers: this.headers({ 'Content-Type': 'application/x-ndjson' }),
method: 'POST',
signal: AbortSignal.timeout(this.requestTimeoutMs),
});
@@ -556,10 +565,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
try {
const response = await fetch(endpoint, {
body,
- headers: {
- 'Authorization': `ApiKey ${this.apiKey}`,
- 'Content-Type': 'application/json',
- },
+ headers: this.headers({ 'Content-Type': 'application/json' }),
method: 'POST',
signal: AbortSignal.timeout(this.requestTimeoutMs),
});
diff --git a/apps/server/src/services/ftsSearch/index.ts b/apps/server/src/services/ftsSearch/index.ts
index 01b320298e0..de05d3a52f4 100644
--- a/apps/server/src/services/ftsSearch/index.ts
+++ b/apps/server/src/services/ftsSearch/index.ts
@@ -54,7 +54,13 @@ interface FtsSearchBackendFactoryDependencies {
}
export interface ElasticsearchFtsSearchConfig {
- apiKey: string;
+ /**
+ * Explicit opt-in for plaintext HTTP / no API key on a private container network.
+ * Optional so downstream callers that build a config literal keep the secure default (`false`).
+ */
+ allowInsecureHttp?: boolean;
+ /** Required unless `allowInsecureHttp` is enabled; never sent over plaintext HTTP. */
+ apiKey?: string;
indexNamespace: string;
url: string;
}
@@ -73,9 +79,13 @@ export const loadElasticsearchFtsSearchConfig = (): ElasticsearchFtsSearchConfig
const indexNamespace =
ftsSearchEnv.ES_INDEX_NAMESPACE ??
(process.env.NODE_ENV === 'development' ? 'lobehub-dev' : undefined);
- if (!ftsSearchEnv.ES_API_KEY || !ftsSearchEnv.ES_URL || !indexNamespace) return;
+ const allowInsecureHttp = ftsSearchEnv.ES_ALLOW_INSECURE_HTTP === 'true';
+ /** The Elastic Cloud path keeps requiring an API key; only the explicit insecure mode may omit it. */
+ if (!ftsSearchEnv.ES_URL || !indexNamespace) return;
+ if (!ftsSearchEnv.ES_API_KEY && !allowInsecureHttp) return;
return {
+ allowInsecureHttp,
apiKey: ftsSearchEnv.ES_API_KEY,
indexNamespace,
url: ftsSearchEnv.ES_URL,
diff --git a/docker-compose/deploy/.env.example b/docker-compose/deploy/.env.example
index 64f4e14f949..08a889d74c5 100644
--- a/docker-compose/deploy/.env.example
+++ b/docker-compose/deploy/.env.example
@@ -40,4 +40,30 @@ RUSTFS_SECRET_KEY=YOUR_RUSTFS_PASSWORD
# Configure the bucket information of RUSTFS
RUSTFS_LOBE_BUCKET=lobe
+# ===========================
+# == Optional Elasticsearch ==
+# ===========================
+# LobeHub searches with PostgreSQL pg_search by default. To run the optional
+# single-node Elasticsearch shipped with this Compose file instead, read
+# https://lobehub.com/docs/self-hosting/advanced/full-text-search first.
+# The service is off unless you opt in with COMPOSE_PROFILES:
+# 1. Uncomment the ES_* lines below and enable the Elasticsearch service, then run `docker compose up -d`
+# and the one-off backfill: `docker compose run --rm fts-search-reindex --apply --fresh-run --yes`
+# COMPOSE_PROFILES=elasticsearch
+# 2. Once the backfill status is ready_for_incremental_sync, also start the sync worker:
+# COMPOSE_PROFILES=elasticsearch,elasticsearch-sync
+# 3. Once the Outbox has caught up, switch search traffic explicitly (never automatic):
+# FTS_SEARCH_PROVIDER=elasticsearch
+#
+# The bundled Elasticsearch runs with security disabled and is reachable only inside
+# the Compose network, so plaintext HTTP without an API key must be enabled explicitly.
+# Do not set ES_API_KEY together with an http:// URL and never publish port 9200.
+# ES_URL=http://elasticsearch:9200
+# ES_ALLOW_INSECURE_HTTP=true
+# ES_INDEX_NAMESPACE=lobehub
+# JVM heap of the Elasticsearch container: at most half of the memory you give it (min. 1g).
+# ES_JAVA_OPTS=-Xms1g -Xmx1g
+# Seconds the sync worker sleeps after a drain that found no more work.
+# FTS_SEARCH_SYNC_INTERVAL_SECONDS=15
+
JWKS_KEY={"keys":[{"d":"PVoFyqyrGstB8wU52S7gqqQQdZLtin_thcEM0nrNtqp9U-NlKLlhgEcWp5t89ycgvhsAzmrRbezGj4JBTr3jn7eWdwQpPJNYiipnsgeJn0pwsB0H2dMqtavxinoPVXkMTOuGHMTFhhyguFBw2JbIL0PTQUcUlXjv40OoJpYHZeggSxgfV-TuxjwW8Ll4-n84M5IOi6A53RvioE-Hm1iyIc2XLBCfyOu-SbAQYi8HzrA64kCxobAB0peLQMiAzfZmwPKiGOhnhKrAlYmG02qFnbUYiJu_-AXwsAyGv9S9i6dwK7QXaGGWYyis8LlPpd_JmPrBnrWomwDlI045NUMWZQ","dp":"OSXI2NBBZl2r0Dpf4-1z44A_jC5lOyXtJhXQYnSXy5eIuxTJcEtkUYagGEwnREO4Q3t-4J-lT_6Y71M1ZlgKG1upwfw1O4aE3vGpHOik9iZYYCjA8fe5uBfOpX1ELmOtHNoHRhMtyjuPxSFXLlSp3bgcF1f3F40ClukdvXCx0Mc","dq":"m6hNdfj-F8E_7nUlX2nG95OffkFrhHTo67ML9aPgpvFwBlzg-hk5LwtxMfUzngqWF78TMl0JDm7vS1bz0xlWqXqu8pFPoTUnUoWgYfvuyHLBwR5TgccQkfoKbkSMzYNy8VJPXZeyIjVXsW98tZvj-NZF-M9Pke_EWJm-jjXCu_8","e":"AQAB","kty":"RSA","n":"piffosMS0HOSgsSr_zQkXYaQt1kOCD73VR0b2XJD6UdQCKPbnBOzTIuA_xowX61QVsl5pCZLTw8ERC3r2Nlxj5Rp_H6RuOT7ioUqlbnxSGnfuAn8dFupY3A-sf9HVDOvtJdlS-nO9yA4wWU-A50zZ1Mf0pPZlUZE6dUQfsJFi5yXaNAybyk3U4VpMO_SXAilWEHVhiO0F0ccpJMCkT47AeXmYH9MlWwIGcay0UiAsdrs8J-q1arZ7Mbq0oxHmUXJG0vwRvAL8KnCEi8cJ3e2kKCRcr-BQCujsHUyUl6f_ATwSVuTHdAR1IzIcW37v27h3WQK_v0ffQM1NstamDX5vQ","p":"4myVm2M5cZGvVXsOmWUTUG87VC1GlQcL5tmMNSGSpQCL8yWZ1vANkmCxSMptrKB4dU9DAB3On6_oMhW1pJ3uYNGSW49BcmJoLkiWKeg5zWFnKPQNuThQmY1sCCubtKhBQgaYUr7TVzN9smrDV3zCu9MlRl-XPwnEmWaDII3g-f8","q":"u9v4IOEsb4l2Y3eWKE2bwJh5fJRR4vivaYA7U-1-OpvDwB3A48Rey9IL1ucXqE5G1Du8BtijPm5oSAar5uzrjtg1bZ9gevif6DnBGaIRE7LnSrUsTPfZwzntJ1rTaGiVe_pAdnTKXXaH6DxygXxH4wvGgA44V3TTfBXQUcjzdEM","qi":"lDBnSPKkRnYqQvbqVD1LxzqBPEeqEA3GyCqMj6fIZNgoEaBSLi0TSsUyGZ5mahX3KO35vKAZa5jvGjhvUGUiXycq8KvRZdeGK45vJdwZT2TiXiDwo9IQgJcbFMpxaB9DhjX2x0yqxgUY5ca75jLqbMuKBKBN0PVqIr9jlHkR8_s","use":"sig","kid":"6823046760c5d460","alg":"RS256"}]}
diff --git a/docker-compose/deploy/.env.zh-CN.example b/docker-compose/deploy/.env.zh-CN.example
index 90751935262..6d78580823c 100644
--- a/docker-compose/deploy/.env.zh-CN.example
+++ b/docker-compose/deploy/.env.zh-CN.example
@@ -37,4 +37,28 @@ RUSTFS_ACCESS_KEY=admin
RUSTFS_SECRET_KEY=YOUR_RUSTFS_PASSWORD
RUSTFS_LOBE_BUCKET=lobe
+# ===========================
+# ===== 可选 Elasticsearch =====
+# ===========================
+# LobeHub 默认使用 PostgreSQL pg_search 提供全文搜索。如需改用本 Compose 文件附带的
+# 可选单节点 Elasticsearch,请先阅读 https://lobehub.com/zh/docs/self-hosting/advanced/full-text-search
+# 该服务默认不会启动,需要通过 COMPOSE_PROFILES 显式启用:
+# 1. 取消下方 ES_* 变量的注释并启用 Elasticsearch 服务,然后执行 `docker compose up -d`
+# 以及一次性全量回填:`docker compose run --rm fts-search-reindex --apply --fresh-run --yes`
+# COMPOSE_PROFILES=elasticsearch
+# 2. 回填状态变为 ready_for_incremental_sync 后,再启动增量同步任务:
+# COMPOSE_PROFILES=elasticsearch,elasticsearch-sync
+# 3. 增量队列追平后,由你显式切换搜索流量(不会自动切换):
+# FTS_SEARCH_PROVIDER=elasticsearch
+#
+# 附带的 Elasticsearch 关闭了安全认证,并且只能在 Compose 内部网络访问,
+# 因此必须显式允许无 API 密钥的明文 HTTP。不要在 http:// 地址上同时设置 ES_API_KEY,也不要对外暴露 9200 端口。
+# ES_URL=http://elasticsearch:9200
+# ES_ALLOW_INSECURE_HTTP=true
+# ES_INDEX_NAMESPACE=lobehub
+# Elasticsearch 容器的 JVM 堆内存:不要超过分配给该容器内存的一半(最少 1g)。
+# ES_JAVA_OPTS=-Xms1g -Xmx1g
+# 增量同步任务在一次没有新任务的消费后等待的秒数。
+# FTS_SEARCH_SYNC_INTERVAL_SECONDS=15
+
JWKS_KEY={"keys":[{"d":"PVoFyqyrGstB8wU52S7gqqQQdZLtin_thcEM0nrNtqp9U-NlKLlhgEcWp5t89ycgvhsAzmrRbezGj4JBTr3jn7eWdwQpPJNYiipnsgeJn0pwsB0H2dMqtavxinoPVXkMTOuGHMTFhhyguFBw2JbIL0PTQUcUlXjv40OoJpYHZeggSxgfV-TuxjwW8Ll4-n84M5IOi6A53RvioE-Hm1iyIc2XLBCfyOu-SbAQYi8HzrA64kCxobAB0peLQMiAzfZmwPKiGOhnhKrAlYmG02qFnbUYiJu_-AXwsAyGv9S9i6dwK7QXaGGWYyis8LlPpd_JmPrBnrWomwDlI045NUMWZQ","dp":"OSXI2NBBZl2r0Dpf4-1z44A_jC5lOyXtJhXQYnSXy5eIuxTJcEtkUYagGEwnREO4Q3t-4J-lT_6Y71M1ZlgKG1upwfw1O4aE3vGpHOik9iZYYCjA8fe5uBfOpX1ELmOtHNoHRhMtyjuPxSFXLlSp3bgcF1f3F40ClukdvXCx0Mc","dq":"m6hNdfj-F8E_7nUlX2nG95OffkFrhHTo67ML9aPgpvFwBlzg-hk5LwtxMfUzngqWF78TMl0JDm7vS1bz0xlWqXqu8pFPoTUnUoWgYfvuyHLBwR5TgccQkfoKbkSMzYNy8VJPXZeyIjVXsW98tZvj-NZF-M9Pke_EWJm-jjXCu_8","e":"AQAB","kty":"RSA","n":"piffosMS0HOSgsSr_zQkXYaQt1kOCD73VR0b2XJD6UdQCKPbnBOzTIuA_xowX61QVsl5pCZLTw8ERC3r2Nlxj5Rp_H6RuOT7ioUqlbnxSGnfuAn8dFupY3A-sf9HVDOvtJdlS-nO9yA4wWU-A50zZ1Mf0pPZlUZE6dUQfsJFi5yXaNAybyk3U4VpMO_SXAilWEHVhiO0F0ccpJMCkT47AeXmYH9MlWwIGcay0UiAsdrs8J-q1arZ7Mbq0oxHmUXJG0vwRvAL8KnCEi8cJ3e2kKCRcr-BQCujsHUyUl6f_ATwSVuTHdAR1IzIcW37v27h3WQK_v0ffQM1NstamDX5vQ","p":"4myVm2M5cZGvVXsOmWUTUG87VC1GlQcL5tmMNSGSpQCL8yWZ1vANkmCxSMptrKB4dU9DAB3On6_oMhW1pJ3uYNGSW49BcmJoLkiWKeg5zWFnKPQNuThQmY1sCCubtKhBQgaYUr7TVzN9smrDV3zCu9MlRl-XPwnEmWaDII3g-f8","q":"u9v4IOEsb4l2Y3eWKE2bwJh5fJRR4vivaYA7U-1-OpvDwB3A48Rey9IL1ucXqE5G1Du8BtijPm5oSAar5uzrjtg1bZ9gevif6DnBGaIRE7LnSrUsTPfZwzntJ1rTaGiVe_pAdnTKXXaH6DxygXxH4wvGgA44V3TTfBXQUcjzdEM","qi":"lDBnSPKkRnYqQvbqVD1LxzqBPEeqEA3GyCqMj6fIZNgoEaBSLi0TSsUyGZ5mahX3KO35vKAZa5jvGjhvUGUiXycq8KvRZdeGK45vJdwZT2TiXiDwo9IQgJcbFMpxaB9DhjX2x0yqxgUY5ca75jLqbMuKBKBN0PVqIr9jlHkR8_s","use":"sig","kid":"6823046760c5d460","alg":"RS256"}]}
diff --git a/docker-compose/deploy/docker-compose.yml b/docker-compose/deploy/docker-compose.yml
index b844e4f4c20..8559c33df00 100644
--- a/docker-compose/deploy/docker-compose.yml
+++ b/docker-compose/deploy/docker-compose.yml
@@ -134,6 +134,123 @@ services:
env_file:
- .env
+ # ---------------------------------------------------------------------------
+ # Optional: self-hosted single-node Elasticsearch for LobeHub full-text search.
+ # Disabled by default; LobeHub keeps using PostgreSQL pg_search unless you opt in.
+ # Enable with COMPOSE_PROFILES in .env and follow the docs:
+ # https://lobehub.com/docs/self-hosting/advanced/full-text-search
+ #
+ # Resources: the JVM heap below (ES_JAVA_OPTS, default 1 GB) should stay at or
+ # below half of the memory available to this container; plan for at least 2 GB
+ # RAM for Elasticsearch alone. Linux hosts must set vm.max_map_count=262144.
+ #
+ # The image is built locally from ./elasticsearch/Dockerfile: the pinned
+ # official image plus the required analysis-icu plugin. The build runs once,
+ # the first time the profile is enabled, and needs outbound access to
+ # docker.elastic.co / artifacts.elastic.co; afterwards container recreation
+ # works offline. To upgrade, change the version in both `image` and
+ # `build.args` below, then run `docker compose up -d --build`.
+ # ---------------------------------------------------------------------------
+ elasticsearch:
+ image: lobehub-elasticsearch-icu:9.5.2
+ build:
+ context: ./elasticsearch
+ args:
+ ELASTICSEARCH_VERSION: 9.5.2
+ container_name: lobe-elasticsearch
+ # Only this profile starts the bundled node. The reindex and sync services
+ # below deliberately do not depend on it, so the same services also work
+ # against an external Elasticsearch (ES_URL + ES_API_KEY in .env) without
+ # building or starting a local node.
+ profiles: [elasticsearch]
+ # Intentionally no `ports`: security is disabled, so this node must stay
+ # reachable only from services on lobe-network. Never publish 9200.
+ environment:
+ - 'discovery.type=single-node'
+ - 'cluster.name=lobehub'
+ - 'xpack.security.enabled=false'
+ - 'xpack.ml.enabled=false'
+ - 'ingest.geoip.downloader.enabled=false'
+ - 'ES_JAVA_OPTS=${ES_JAVA_OPTS:--Xms1g -Xmx1g}'
+ volumes:
+ - 'elasticsearch-data:/usr/share/elasticsearch/data'
+ ulimits:
+ nofile:
+ soft: 65536
+ hard: 65536
+ healthcheck:
+ test:
+ [
+ 'CMD-SHELL',
+ "curl -fsS 'http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=5s' >/dev/null || exit 1",
+ ]
+ interval: 10s
+ timeout: 10s
+ retries: 30
+ start_period: 90s
+ restart: always
+ networks:
+ - lobe-network
+
+ # One-off full backfill / status command for the optional Elasticsearch path.
+ # It never starts with `docker compose up`; run it explicitly, for example:
+ # docker compose run --rm fts-search-reindex --status
+ # docker compose run --rm fts-search-reindex --apply --fresh-run --yes
+ # The checkpoint lives in the fts-search-reindex-state volume so a later run
+ # with the same arguments (without --fresh-run) resumes instead of restarting.
+ # With the bundled node, start the stack with `docker compose up -d --wait`
+ # first so Elasticsearch is healthy before the backfill connects to it.
+ fts-search-reindex:
+ image: lobehub/lobehub
+ profiles: [elasticsearch-reindex]
+ depends_on:
+ postgresql:
+ condition: service_healthy
+ environment:
+ - 'DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@postgresql:5432/${LOBE_DB_NAME}'
+ - 'ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex'
+ env_file:
+ - .env
+ volumes:
+ - 'fts-search-reindex-state:/app/.elasticsearch-reindex'
+ # The script lives in the entrypoint so that arguments given to
+ # `docker compose run fts-search-reindex ...` replace only `--status`.
+ entrypoint: ['/bin/node', '/app/fts-search-elasticsearch-reindex.cjs']
+ command: ['--status']
+ restart: 'no'
+ networks:
+ - lobe-network
+
+ # Long-running incremental sync worker for the optional Elasticsearch path.
+ # Start it only after the backfill status is ready_for_incremental_sync by
+ # adding the elasticsearch-sync profile to COMPOSE_PROFILES in .env. It keeps
+ # draining the PostgreSQL Outbox into Elasticsearch and exits non-zero (and is
+ # restarted) when it hits failed or dead-letter work, so check its logs. It
+ # also exits and is restarted until the Elasticsearch target is reachable.
+ fts-search-sync:
+ image: lobehub/lobehub
+ container_name: lobe-fts-search-sync
+ profiles: [elasticsearch-sync]
+ depends_on:
+ postgresql:
+ condition: service_healthy
+ environment:
+ - 'DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@postgresql:5432/${LOBE_DB_NAME}'
+ - 'FTS_SEARCH_SYNC_ENABLED=true'
+ - 'MIGRATION_DB=1'
+ env_file:
+ - .env
+ entrypoint: ['/bin/node', '/app/fts-search-elasticsearch-sync.cjs']
+ command: ['--max-steps=8', '--interval-seconds=${FTS_SEARCH_SYNC_INTERVAL_SECONDS:-15}', '--yes']
+ # On SIGTERM the worker finishes only the current drain step (not all 8) and
+ # then exits, so the grace period has to cover one step: its bulk request may
+ # wait up to 20s plus database settlement. Compose's default of 10s would
+ # SIGKILL mid-step and leave claims to expire into retries.
+ stop_grace_period: 2m
+ restart: always
+ networks:
+ - lobe-network
+
networks:
lobe-network:
driver: bridge
@@ -143,3 +260,8 @@ volumes:
driver: local
rustfs-data:
driver: local
+ # Only created when an Elasticsearch profile is enabled.
+ elasticsearch-data:
+ driver: local
+ fts-search-reindex-state:
+ driver: local
diff --git a/docker-compose/deploy/elasticsearch/Dockerfile b/docker-compose/deploy/elasticsearch/Dockerfile
new file mode 100644
index 00000000000..d8aeedcd987
--- /dev/null
+++ b/docker-compose/deploy/elasticsearch/Dockerfile
@@ -0,0 +1,8 @@
+# Optional single-node Elasticsearch for LobeHub full-text search.
+# Built by the `elasticsearch` service in ../docker-compose.yml; the version is
+# passed from there so that `image` and the base image always match.
+ARG ELASTICSEARCH_VERSION
+FROM docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION}
+
+# The LobeHub index mappings require the ICU analysis plugin.
+RUN bin/elasticsearch-plugin install --batch analysis-icu
diff --git a/docker-compose/setup.sh b/docker-compose/setup.sh
index 5a2ab9f717a..966972bf0fb 100644
--- a/docker-compose/setup.sh
+++ b/docker-compose/setup.sh
@@ -488,6 +488,7 @@ FILES=(
"$SUB_DIR/docker-compose.yml"
"$SUB_DIR/searxng-settings.yml"
"$SUB_DIR/bucket.config.json"
+ "$SUB_DIR/elasticsearch/Dockerfile"
)
ENV_EXAMPLES=(
"$SUB_DIR/.env.zh-CN.example"
@@ -526,6 +527,9 @@ section_download_files(){
download_file "$SOURCE_URL/${FILES[0]}" "docker-compose.yml"
download_file "$SOURCE_URL/${FILES[1]}" "searxng-settings.yml"
download_file "$SOURCE_URL/${FILES[2]}" "bucket.config.json"
+ # Build context of the optional Elasticsearch service (only built when its profile is enabled)
+ mkdir -p elasticsearch
+ download_file "$SOURCE_URL/${FILES[3]}" "elasticsearch/Dockerfile"
# Download .env.example with the specified language
if [ "$LANGUAGE" = "zh_CN" ]; then
download_file "$SOURCE_URL/${ENV_EXAMPLES[0]}" ".env"
@@ -558,8 +562,10 @@ section_configurate_host() {
ask "(y/n)" "y"
if [[ "$ask_result" == "y" ]]; then
PROTOCOL="https"
- # Replace all http with https
- sed "${SED_INPLACE_ARGS[@]}" "s#http://#https://#" .env
+ # Replace http with https on variable assignments only (commented ones
+ # included), so explanatory comments keep their wording, and skip the
+ # in-network Elasticsearch endpoint, which is plain HTTP by design.
+ sed "${SED_INPLACE_ARGS[@]}" '/^#\{0,1\} \{0,1\}[A-Za-z0-9_]*=/{/ES_URL=/!s|http://|https://|;}' .env
fi
fi
diff --git a/docs/self-hosting/advanced/elasticsearch-migration.mdx b/docs/self-hosting/advanced/elasticsearch-migration.mdx
index 2b876044d82..acd793f5337 100644
--- a/docs/self-hosting/advanced/elasticsearch-migration.mdx
+++ b/docs/self-hosting/advanced/elasticsearch-migration.mdx
@@ -1,6 +1,6 @@
---
-title: Migrate Search Data to Elasticsearch (3.x)
-description: Safely backfill LobeHub search data into an empty Elasticsearch project with durable resume support.
+title: Migrate from pg_search to Elasticsearch (3.x)
+description: Safely move an existing LobeHub deployment from PostgreSQL pg_search to Elasticsearch.
tags:
- Elasticsearch
- Search
@@ -8,9 +8,29 @@ tags:
- Self-hosting
---
-# Migrate Search Data to Elasticsearch
+# Migrate from pg\_search to Elasticsearch
-The 3.x migration tool copies LobeHub's 14 searchable entity types from PostgreSQL into a new Elasticsearch project. It atomically records the cursor, counters, and item-level failures in a local checkpoint file, so running the same command with the same state directory resumes the existing attempt.
+This guide moves an existing LobeHub deployment from PostgreSQL `pg_search` to Elasticsearch while
+the application remains available. The 3.x migration tool copies LobeHub's 14 searchable entity
+types into a new Elasticsearch project. It atomically records cursors, counters, and item-level
+failures in a local checkpoint file, so running the same command with the same state directory
+resumes the existing attempt.
+
+This workflow is for a database that has already applied the historical `pg_search` migrations and
+currently serves search with `FTS_SEARCH_PROVIDER=pg_search`. For backend selection and the ongoing
+Elasticsearch data flow, read [Full-Text Search](/docs/self-hosting/advanced/full-text-search).
+
+<Callout type="warning">
+ Neon stopped offering `pg_search` to new projects on March 19, 2026. Neon has notified affected
+ existing customers that the extension will be removed on September 21, 2026; queries, indexes,
+ and applications that still depend on it will stop working after removal. Complete this
+ migration before that deadline. Setting `FTS_SEARCH_PROVIDER=elasticsearch` on a fresh database
+ does not skip LobeHub's historical `pg_search` migrations: `bun run db:migrate` still attempts to
+ create the extension and BM25 indexes, and fails when the database service does not provide them.
+ See Neon's
+ [pg\_search notice](https://neon.com/docs/extensions/pg_search) and
+ [extension catalog](https://neon.com/docs/extensions/pg-extensions) for the current service state.
+</Callout>
<Callout type="warning">
The reindex command does not switch product search requests to Elasticsearch. Keep the application on PostgreSQL search while you backfill and validate the new indexes. The regular database migration creates the PostgreSQL Outbox schema and the schema-managed Memory fanout GIN index; it does not install search-capture functions or triggers. Capture starts only after you explicitly run `bun run db:install-fts-search-capture` or start `bun run fts-search:reindex -- --apply`, even if the incremental consumer is still paused.
@@ -18,15 +38,15 @@ The 3.x migration tool copies LobeHub's 14 searchable entity types from PostgreS
## Environment variables
-| Variable | Required | Purpose |
-| ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
-| `DATABASE_URL` | Yes | PostgreSQL source database and incremental-change Outbox. Reindex checkpoints are not stored in the database. |
-| `ES_URL` | Apply | HTTPS endpoint of the new, empty Elasticsearch project that receives the 3.x search indexes. |
-| `ES_API_KEY` | Apply | Elasticsearch API key used to create indexes, write bulk documents, refresh/count indexes, and create aliases. Do not use a read-only key. |
-| `ES_INDEX_NAMESPACE` | Yes | Stable deployment-owned prefix, for example `lobehub`. It produces aliases such as `lobehub-messages`. Keep it unchanged across reruns. |
-| `FTS_SEARCH_SYNC_ENABLED` | Sync | Set to `true` only after the full backfill is ready and before running the incremental consumer. |
-| `ES_REINDEX_STATE_DIR` | Mutate | Local checkpoint directory. It must be explicit for mutations and must persist across every resume attempt. |
-| `FTS_SEARCH_PROVIDER` | Runtime | Full-text search provider: `pg_search` (default) or `elasticsearch`. Keep `pg_search` until backfill, catch-up, and validation finish. |
+| Variable | Required | Purpose |
+| ------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `DATABASE_URL` | Yes | PostgreSQL source database and incremental-change Outbox. Reindex checkpoints are not stored in the database. |
+| `ES_URL` | Apply | Endpoint of the new, empty Elasticsearch target that receives the 3.x search indexes. HTTPS, or plaintext HTTP only for loopback or with `ES_ALLOW_INSECURE_HTTP=true`. |
+| `ES_API_KEY` | Apply | Elasticsearch API key used to create indexes, write bulk documents, refresh/count indexes, and create aliases. Do not use a read-only key. Required unless `ES_ALLOW_INSECURE_HTTP=true`. |
+| `ES_ALLOW_INSECURE_HTTP` | Compose | `true` only for an Elasticsearch node with security disabled that is reachable exclusively inside a private container network, such as the optional Docker Compose service. |
+| `ES_INDEX_NAMESPACE` | Yes | Stable deployment-owned prefix, for example `lobehub`. It produces aliases such as `lobehub-messages`. Keep it unchanged across reruns. |
+| `FTS_SEARCH_SYNC_ENABLED` | Sync | Set to `true` only after the full backfill is ready and before running the incremental consumer. |
+| `FTS_SEARCH_PROVIDER` | Cutover | Set to `elasticsearch` after backfill, catch-up, and validation finish to switch user search traffic. |
`ES_URL` and `ES_API_KEY` are not needed for the read-only `--status` command.
Operators that keep multiple Elasticsearch targets in one environment can select an explicit pair
@@ -37,7 +57,9 @@ hostname and variable names, never credential values.
Remote Elasticsearch targets must use HTTPS. Plain HTTP is accepted only for loopback addresses
such as `localhost` during local development, so an API key cannot be sent unencrypted to a remote
-host.
+host. The single explicit exception is `ES_ALLOW_INSECURE_HTTP=true`, which permits plaintext HTTP
+to a private container hostname without an API key; even then the runtime, reindex, and sync
+clients all refuse to send an API key over plaintext HTTP.
## Before you start
@@ -46,26 +68,24 @@ host.
[`analysis-icu`](https://www.elastic.co/docs/reference/elasticsearch/plugins/analysis-icu)
plugin. Elastic Cloud Serverless includes core analysis plugins; on Elastic Cloud Hosted, enable
the provided plugin for the deployment; on self-managed Elasticsearch, install it on every node
- and restart every node before the first `--apply`.
+ and restart every node before the first `--apply`. Docker Compose deployments can instead enable
+ the optional `elasticsearch` service of the official Compose file, whose image is built with the
+ plugin included; see
+ [Run Elasticsearch with Docker Compose](/docs/self-hosting/advanced/full-text-search#run-elasticsearch-with-docker-compose).
-2. Back up PostgreSQL before enabling Elasticsearch capture.
+2. Create and verify a PostgreSQL recovery point before enabling Elasticsearch capture, then
+ rehearse the migration against an isolated database copy and an isolated empty Elasticsearch
+ target. The rehearsal should exercise at least one batch for every non-empty entity, a resume
+ using the same checkpoint, incremental catch-up, and the application smoke tests you will use at
+ cutover.
-3. If an existing, write-heavy database is about to apply the migration, run the following
- statement in the database SQL editor, outside a transaction. It builds the Memory fanout index
- without blocking writes, so the regular migration can reuse it. A new or low-traffic
- installation can skip this pre-step and let the migration create the index normally:
+ On Neon, create a child branch for the rehearsal and use a manual snapshot or the root branch's
+ point-in-time restore window for production recovery. A child branch is an isolated test copy;
+ it is not itself a point-in-time restore point. See Neon's
+ [branching](https://neon.com/docs/introduction/branching) and
+ [backup and restore](https://neon.com/docs/guides/backup-restore) documentation.
- ```sql
- CREATE INDEX CONCURRENTLY IF NOT EXISTS "user_memories_contexts_user_memory_ids_gin_idx"
- ON "user_memories_contexts" USING gin ("user_memory_ids");
- ```
-
- `IF NOT EXISTS` does not verify an existing index definition. If an interrupted build left this
- index invalid, or the installer reports that its table, column, GIN operator class, or predicate
- is wrong, run `DROP INDEX CONCURRENTLY "user_memories_contexts_user_memory_ids_gin_idx"` outside
- a transaction, recreate it with the statement above, and then continue.
-
-4. Apply the database migrations for the same LobeHub release:
+3. Apply the database migrations for the same LobeHub release:
```bash
bun run db:migrate
@@ -76,7 +96,7 @@ host.
PostgreSQL-only deployment can stop here: it still maintains the schema-managed GIN index, but
does not pay the trigger or Outbox capture-write overhead.
-5. Install the optional PostgreSQL change capture before the first backfill:
+4. Install the optional PostgreSQL change capture before the first backfill:
```bash
bun run db:install-fts-search-capture
@@ -91,7 +111,7 @@ host.
capture active while preparing the Elasticsearch target. If you do not intend to enable
Elasticsearch, do not run it.
-6. Keep the application's search backend on PostgreSQL and keep incremental Elasticsearch draining disabled.
+5. Keep the application's search backend on PostgreSQL and keep incremental Elasticsearch draining disabled.
The first production mapping is version `v1`. The tool creates physical indexes such as `lobehub-messages-v1`. After all 14 indexes finish and their counts match the durable checkpoints, it creates stable aliases such as `lobehub-messages`. An alias is only a stable Elasticsearch name; creating it does not change which search backend serves users.
@@ -198,6 +218,13 @@ counts, retries, cursors, failures, and final state. It never records database o
URLs, credentials, or document source text. Keep these private files with the checkpoint when
moving or archiving a run.
+The backfill command exports OpenTelemetry only when `ENABLE_TELEMETRY` is set. In that case, pass
+`--telemetry-environment=<development|preview|production>` and configure either
+`OTEL_EXPORTER_OTLP_ENDPOINT` or both signal-specific metrics and traces endpoints. Otherwise leave
+telemetry disabled and use the local event and summary files. Always set the same explicit
+`ES_INDEX_NAMESPACE` for the migration command, incremental consumer, and application runtime;
+the command has no development fallback for a missing namespace.
+
## Run from the Docker image
The official image includes `/app/fts-search-elasticsearch-reindex.cjs`:
@@ -215,10 +242,27 @@ docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
```
The bind mount is required for resume after a `--rm` container exits. Running with the host user's
-ID lets the process write the bind-mounted directory without changing its ownership. If Docker
-Compose already supplies the same environment variables and database network, mount the same
-persistent state directory and run the image as a one-time service instead of starting a second
-application server.
+ID lets the process write the bind-mounted directory without changing its ownership.
+
+## Run from Docker Compose
+
+The official `docker-compose/deploy/docker-compose.yml` already defines the same command as the
+`fts-search-reindex` service, wired to the Compose PostgreSQL, the optional in-network
+`elasticsearch` service, and a named `fts-search-reindex-state` volume for the checkpoint:
+
+```bash
+docker compose run --rm fts-search-reindex --status
+docker compose run --rm fts-search-reindex --apply --fresh-run --yes
+```
+
+Extra arguments are passed through, so the rehearsal, `--entity`, `--skip-failure`, and resume
+commands above work unchanged. The service uses the `ES_URL`, `ES_ALLOW_INSECURE_HTTP`, and
+`ES_INDEX_NAMESPACE` values from `.env`; with an external Elastic Cloud target, set `ES_URL` and
+`ES_API_KEY` there instead, leave `ES_ALLOW_INSECURE_HTTP` unset, and keep the `elasticsearch`
+profile out of `COMPOSE_PROFILES`; the service depends only on PostgreSQL, so the bundled node is
+neither built nor started. The complete Compose sequence,
+including enabling the node and the sync worker, is in
+[Run Elasticsearch with Docker Compose](/docs/self-hosting/advanced/full-text-search#run-elasticsearch-with-docker-compose).
## Start incremental synchronization
@@ -232,6 +276,14 @@ bun run fts-search:sync -- --max-steps=8 --yes
One invocation processes at most eight drain steps and then exits. `hasMore: true` in the final JSON
means the bound was reached safely; run it again. Schedule the same command with cron, a container
job, or another process supervisor so it continues to run while Elasticsearch search is enabled.
+Omitting `--max-steps` processes one step; accepted values are from 1 through 100.
+
+For a long-running worker instead of an external scheduler, add `--interval-seconds=<1-3600>`: the
+command repeats the same bounded drain, continues immediately while `hasMore` is true, sleeps for
+the interval otherwise, and stops cleanly on `SIGINT` / `SIGTERM` after finishing the drain step in
+progress (not the whole bound), so a supervisor's stop timeout only needs to cover one step. A run that leaves failed or
+dead-letter work still exits non-zero, so the supervisor's restart policy and logs surface it. The
+Compose `fts-search-sync` service (profile `elasticsearch-sync`) uses this mode.
The consumer validates the PostgreSQL capture definitions and every Elasticsearch write alias before
claiming work. Missing or stale capture infrastructure, an invalid alias, retryable write failure, or
dead-letter work produces a non-zero exit code. It never installs triggers and never deletes failed
@@ -252,6 +304,14 @@ switching queries. Then set `FTS_SEARCH_PROVIDER=elasticsearch` and redeploy the
`FTS_SEARCH_PROVIDER=pg_search` until catch-up is complete. Elasticsearch failures remain visible to
callers; the search path does not silently fall back to PostgreSQL or `ilike`.
+After deployment, keep the old BM25 indexes and `pg_search` extension during an agreed observation
+window. Confirm that successful backend operations are attributed to `elasticsearch`, no new
+`pg_search` operations appear, the Outbox repeatedly returns to zero lag with no dead work, and the
+product search surfaces your deployment uses pass smoke tests. While the old database objects still
+exist, rollback is limited to restoring `FTS_SEARCH_PROVIDER=pg_search` and redeploying; the Outbox
+consumer may continue running while you diagnose Elasticsearch. If you stop that consumer after
+capture has been installed, source changes continue accumulating in the Outbox until it resumes.
+
## Resume and verify
- After a process crash or temporary Elasticsearch failure, re-run the `--apply --yes` command with the same state directory but without `--fresh-run`. Completed entities are skipped and the next batch starts after the local cursor. This is safe while the optional capture infrastructure remains installed, because changes made during the pause are retained in the Outbox.
@@ -295,3 +355,37 @@ progress.
the application is ready to switch search backends by itself. Keep `fts-search:sync` scheduled for as
long as Elasticsearch serves search traffic.
</Callout>
+
+## Remove pg\_search before the Neon deadline
+
+After Elasticsearch has served search reliably through your observation window and a current
+PostgreSQL recovery point is available, inspect the remaining LobeHub-managed objects:
+
+```bash
+bun run scripts/pgSearchCleanup/index.ts --status
+```
+
+Then remove them without copying SQL from this guide:
+
+```bash
+bun run scripts/pgSearchCleanup/index.ts --apply --yes
+```
+
+Use a direct `DATABASE_URL`, not a transaction-pool endpoint. The command refuses to apply before
+`FTS_SEARCH_PROVIDER=elasticsearch`, refuses unrecognized BM25 indexes, removes the known indexes
+concurrently, and then removes the extension without `CASCADE`. It is safe to rerun after an
+interrupted cleanup. It does not remove the Elasticsearch Outbox, capture triggers, or incremental
+consumer.
+
+The official image includes `/app/fts-search-pg-search-cleanup.cjs`:
+
+```bash
+docker run --rm --env-file .env \
+ lobehub/lobehub:latest /app/fts-search-pg-search-cleanup.cjs --status
+docker run --rm --env-file .env \
+ lobehub/lobehub:latest /app/fts-search-pg-search-cleanup.cjs --apply --yes
+```
+
+Affected Neon deployments must complete this cleanup before September 21, 2026. Other PostgreSQL
+providers can keep `pg_search` installed, but removing the retired objects avoids continuing to
+maintain unused BM25 indexes.
diff --git a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
index 4b9710a5c08..dfa1bc1e0f4 100644
--- a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
+++ b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
@@ -1,6 +1,6 @@
---
-title: 将搜索数据迁移到 Elasticsearch(3.x)
-description: 使用可断点续跑的工具,将 LobeHub 搜索数据安全回填到空的 Elasticsearch 项目。
+title: 从 pg_search 迁移到 Elasticsearch(3.x)
+description: 将现有 LobeHub 部署从 PostgreSQL pg_search 安全迁移到 Elasticsearch。
tags:
- Elasticsearch
- 搜索
@@ -8,9 +8,23 @@ tags:
- 私有部署
---
-# 将搜索数据迁移到 Elasticsearch
+# 从 pg\_search 迁移到 Elasticsearch
-3.x 迁移工具会把 PostgreSQL 中 14 类可搜索数据复制到新的 Elasticsearch 项目。工具会把游标、计数和逐条失败记录原子写入本地 checkpoint 文件,因此中断后使用同一个状态目录重复执行命令即可续跑。
+本文用于在应用持续可用的情况下,把现有 LobeHub 部署从 PostgreSQL `pg_search` 迁移到
+Elasticsearch。3.x 迁移工具会把 PostgreSQL 中 14 类可搜索数据复制到新的 Elasticsearch 项目。工具会把游标、计数和逐条失败记录原子写入本地 checkpoint 文件,因此中断后使用同一个状态目录重复执行命令即可续跑。
+
+此流程要求数据库已经执行过历史 `pg_search` 迁移,并且当前使用
+`FTS_SEARCH_PROVIDER=pg_search` 提供搜索。搜索后端选择和 Elasticsearch 长期同步链路请先阅读
+[全文搜索](/zh/docs/self-hosting/advanced/full-text-search)。
+
+<Callout type="warning">
+ Neon 已于 2026 年 3 月 19 日停止为新项目提供 `pg_search`,并已通知受影响的现有客户:该扩展将在
+ 2026 年 9 月 21 日从 Neon 移除,此后依赖它的查询、索引和应用都会停止工作。请在截止日期前完成本文迁移。
+ 对全新数据库设置 `FTS_SEARCH_PROVIDER=elasticsearch` 并不会跳过 LobeHub 的历史 `pg_search` 迁移:
+ `bun run db:migrate` 仍会尝试创建扩展和 BM25 索引,并在数据库服务不提供它们时失败。请结合 Neon 的
+ [pg\_search 公告](https://neon.com/docs/extensions/pg_search)和
+ [扩展列表](https://neon.com/docs/extensions/pg-extensions)核对当前服务状态。
+</Callout>
<Callout type="warning">
全量回填命令不会把产品搜索请求切到 Elasticsearch。回填和验收期间,应用必须继续使用 PostgreSQL 搜索。常规数据库迁移会创建 PostgreSQL 增量队列的基础结构和由数据库结构管理的 Memory 扇出 GIN 索引,但不会安装搜索变更采集函数和触发器。只有显式执行 `bun run db:install-fts-search-capture` 或启动 `bun run fts-search:reindex -- --apply` 后才会开始采集,即使增量消费器仍处于暂停状态也是如此。
@@ -18,39 +32,40 @@ tags:
## 环境变量
-| 变量 | 是否必需 | 用途 |
-| ------------------------- | ---- | --------------------------------------------------------------------- |
-| `DATABASE_URL` | 是 | PostgreSQL 源数据库和增量变更队列;回填 checkpoint 不写入数据库。 |
-| `ES_URL` | 执行时 | 新建空 Elasticsearch 项目的 HTTPS 地址,用于接收 3.x 搜索索引。 |
-| `ES_API_KEY` | 执行时 | 用于创建索引、批量写入、刷新 / 统计索引和创建别名的 Elasticsearch 密钥,不能使用只读密钥。 |
-| `ES_INDEX_NAMESPACE` | 是 | 当前部署长期不变的索引前缀,例如 `lobehub`;会生成 `lobehub-messages` 等别名,续跑时不能修改。 |
-| `FTS_SEARCH_SYNC_ENABLED` | 增量同步 | 只有全量回填就绪后才能设为 `true`,用于启用增量消费器。 |
-| `ES_REINDEX_STATE_DIR` | 执行时 | 本地 checkpoint 目录;修改状态时必须显式配置,且每次续跑都必须保留并使用同一个目录。 |
-| `FTS_SEARCH_PROVIDER` | 运行时 | 全文搜索提供方:`pg_search`(默认)或 `elasticsearch`;完成回填、追平和验收前必须保持 `pg_search`。 |
+| 变量 | 是否必需 | 用途 |
+| ------------------------- | ------- | --------------------------------------------------------------------------------------------------- |
+| `DATABASE_URL` | 是 | PostgreSQL 源数据库和增量变更队列;回填 checkpoint 不写入数据库。 |
+| `ES_URL` | 执行时 | 接收 3.x 搜索索引的新建空 Elasticsearch 目标地址。使用 HTTPS;明文 HTTP 只允许用于回环地址,或在 `ES_ALLOW_INSECURE_HTTP=true` 时使用。 |
+| `ES_API_KEY` | 执行时 | 用于创建索引、批量写入、刷新 / 统计索引和创建别名的 Elasticsearch 密钥,不能使用只读密钥。除 `ES_ALLOW_INSECURE_HTTP=true` 外均为必需。 |
+| `ES_ALLOW_INSECURE_HTTP` | Compose | 仅对关闭安全认证且只能在私有容器网络内访问的 Elasticsearch 节点(例如官方 Compose 的可选服务)设为 `true`。 |
+| `ES_INDEX_NAMESPACE` | 是 | 当前部署长期不变的索引前缀,例如 `lobehub`;会生成 `lobehub-messages` 等别名,续跑时不能修改。 |
+| `FTS_SEARCH_SYNC_ENABLED` | 增量同步 | 只有全量回填就绪后才能设为 `true`,用于启用增量消费器。 |
+| `FTS_SEARCH_PROVIDER` | 切换时 | 回填、追平和验收完成后设为 `elasticsearch`,将用户搜索请求切换到 Elasticsearch。 |
只读的 `--status` 命令不需要 `ES_URL` 和 `ES_API_KEY`。
如果同一个环境中保存了多套 Elasticsearch 目标,可以同时传入 `--elasticsearch-url-env=<变量名>` 和 `--elasticsearch-api-key-env=<变量名>` 显式选择其中一组。两个参数必须成对使用;还可以通过 `--expected-elasticsearch-host-prefix=<主机名前缀>` 在任何回填写入前拒绝错误目标。命令会打印并记录选中的主机名和变量名,但不会记录密钥值。
-远程 Elasticsearch 目标必须使用 HTTPS。只有本地开发时的 `localhost` 等回环地址可以使用明文 HTTP,避免把 API 密钥通过未加密连接发送到远程主机。
+远程 Elasticsearch 目标必须使用 HTTPS。只有本地开发时的 `localhost` 等回环地址可以使用明文 HTTP,避免把 API 密钥通过未加密连接发送到远程主机。唯一的显式例外是
+`ES_ALLOW_INSECURE_HTTP=true`:它允许对私有容器网络内的主机名使用无 API 密钥的明文 HTTP;即便如此,运行时、回填和同步三个客户端都会拒绝通过明文 HTTP 发送 API 密钥。
## 开始前
1. 在正式使用的区域创建一个新的空 Elasticsearch 项目。LobeHub 搜索分析器依赖官方
[`analysis-icu`](https://www.elastic.co/docs/reference/elasticsearch/plugins/analysis-icu)
- 插件。Elastic Cloud Serverless 已包含核心分析插件;Elastic Cloud Hosted 需要为部署启用官方插件;自行管理的 Elasticsearch 必须在所有节点安装插件并重启所有节点。请在首次执行 `--apply` 前完成。
+ 插件。Elastic Cloud Serverless 已包含核心分析插件;Elastic Cloud Hosted 需要为部署启用官方插件;自行管理的 Elasticsearch 必须在所有节点安装插件并重启所有节点。请在首次执行 `--apply` 前完成。Docker Compose
+ 部署也可以改为启用官方 Compose 文件中的可选 `elasticsearch` 服务,其镜像构建时已内置该插件,详见
+ [使用 Docker Compose 运行 Elasticsearch](/zh/docs/self-hosting/advanced/full-text-search#使用-docker-compose-运行-elasticsearch)。
-2. 在启用 Elasticsearch 采集前备份 PostgreSQL。
+2. 在启用 Elasticsearch 采集前创建并验证 PostgreSQL 恢复点,再使用隔离的数据库副本和空
+ Elasticsearch 目标演练。演练至少要覆盖每个非空数据类型的一个批次、使用同一 checkpoint
+ 续跑、增量追平,以及正式切换时要执行的应用搜索检查。
-3. 如果是已有且写入量较大的数据库,请在执行数据库迁移前,在数据库 SQL 编辑器中、事务之外执行以下语句。它会在不阻塞写入的情况下创建 Memory 扇出索引,后续常规迁移可以直接复用。全新或低流量安装可以跳过这一步,交给迁移正常创建索引:
+ Neon 用户可以创建子分支进行隔离演练,并为正式根分支创建手动快照或确认时间点恢复窗口。
+ 子分支只是隔离的测试副本,本身不能代替正式分支的时间点恢复。请参阅 Neon 的
+ [分支文档](https://neon.com/docs/introduction/branching)和
+ [备份与恢复文档](https://neon.com/docs/guides/backup-restore)。
- ```sql
- CREATE INDEX CONCURRENTLY IF NOT EXISTS "user_memories_contexts_user_memory_ids_gin_idx"
- ON "user_memories_contexts" USING gin ("user_memory_ids");
- ```
-
- `IF NOT EXISTS` 不会校验同名索引的定义。如果并发创建留下无效索引,或安装器提示索引的表、列、GIN 操作符类或条件不正确,请在事务之外执行 `DROP INDEX CONCURRENTLY "user_memories_contexts_user_memory_ids_gin_idx"`,用上面的语句重新创建,然后继续后续步骤。
-
-4. 执行同一 LobeHub 版本自带的数据库迁移:
+3. 执行同一 LobeHub 版本自带的数据库迁移:
```bash
bun run db:migrate
@@ -58,7 +73,7 @@ tags:
这一步会创建增量队列的序列、表、普通索引,以及由数据库结构管理的 Memory 扇出 GIN 索引,但不会创建 PostgreSQL 变更采集函数和触发器。只使用 PostgreSQL 搜索的部署可以停在这里:它仍会维护这个 GIN 索引,但不会承担触发器和增量队列的采集写入开销。
-5. 在首次回填前安装可选的 PostgreSQL 变更采集:
+4. 在首次回填前安装可选的 PostgreSQL 变更采集:
```bash
bun run db:install-fts-search-capture
@@ -66,7 +81,7 @@ tags:
安装器会先严格校验由数据库结构管理的 GIN 索引(不会创建这个索引),再在一个事务中原子安装并验证采集函数和 16 个触发器。完整的预期设施已经存在时可以安全重复执行;如果发现部分对象、被禁用的对象或定义异常,安装器会直接失败,不会静默修复。安装成功后,源数据变更会立即写入增量队列。`bun run fts-search:reindex -- --apply` 也会自动执行这一步;如果希望在准备 Elasticsearch 目标期间就开始采集,可以先显式执行安装命令。若不打算启用 Elasticsearch,不要执行这一步。
-6. 保持应用搜索后端为 PostgreSQL,并关闭 Elasticsearch 增量消费。
+5. 保持应用搜索后端为 PostgreSQL,并关闭 Elasticsearch 增量消费。
首次正式映射版本是 `v1`。工具会创建 `lobehub-messages-v1` 这类实体索引;14 类索引全部完成且数量与断点记录一致后,再创建 `lobehub-messages` 这类稳定别名。别名只是 Elasticsearch 内部长期不变的名字,创建别名不会改变用户请求当前使用的搜索后端。
@@ -125,6 +140,11 @@ ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
每次执行或续跑都会把脱敏后的详细运行事件追加到 `<状态目录>/runs/<run-id>/events.jsonl`,并原子更新 `<状态目录>/runs/<run-id>/summary.json`。日志包含各数据类型和批量请求的耗时、字节数、文档数、重试、游标、失败与最终状态,但不会记录数据库或 Elasticsearch 地址、密钥以及文档正文。迁移或归档任务时,应把这些私有日志和 checkpoint 一起保留。
+只有设置 `ENABLE_TELEMETRY` 后,全量回填命令才会输出 OpenTelemetry 数据。此时必须传入
+`--telemetry-environment=<development|preview|production>`,并配置统一的
+`OTEL_EXPORTER_OTLP_ENDPOINT`,或分别配置指标和链路地址;否则应保持遥测关闭,使用本地事件和汇总文件。
+迁移命令、增量消费器和应用运行时必须显式使用同一个 `ES_INDEX_NAMESPACE`;迁移命令在开发环境也不会为缺失的前缀提供默认值。
+
## 使用 Docker 镜像运行
官方镜像内置 `/app/fts-search-elasticsearch-reindex.cjs`:
@@ -141,7 +161,24 @@ docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --apply --fresh-run --yes
```
-使用 `--rm` 时必须挂载状态目录,否则容器退出后无法续跑。命令使用宿主机当前用户的 ID 运行,使进程可以写入挂载目录,同时不会修改目录所有者。如果 Docker Compose 已提供相同的环境变量和数据库网络,请挂载同一个持久化状态目录,并把镜像作为一次性服务运行,不要再启动一个应用服务实例。
+使用 `--rm` 时必须挂载状态目录,否则容器退出后无法续跑。命令使用宿主机当前用户的 ID 运行,使进程可以写入挂载目录,同时不会修改目录所有者。
+
+## 使用 Docker Compose 运行
+
+官方 `docker-compose/deploy/docker-compose.yml` 已将同一条命令定义为 `fts-search-reindex`
+服务,并接入 Compose 内的 PostgreSQL、可选的内部网络 `elasticsearch` 服务,以及保存 checkpoint 的命名卷
+`fts-search-reindex-state`:
+
+```bash
+docker compose run --rm fts-search-reindex --status
+docker compose run --rm fts-search-reindex --apply --fresh-run --yes
+```
+
+额外参数会原样传入,因此上文的演练、`--entity`、`--skip-failure` 和续跑命令都可以直接使用。该服务读取 `.env` 中的
+`ES_URL`、`ES_ALLOW_INSECURE_HTTP` 和 `ES_INDEX_NAMESPACE`;如果目标是外部 Elastic Cloud,请改为在其中设置
+`ES_URL` 和 `ES_API_KEY`,不要设置 `ES_ALLOW_INSECURE_HTTP`,也不要在 `COMPOSE_PROFILES` 中启用 `elasticsearch`
+profile;该服务只依赖 PostgreSQL,因此不会构建或启动内置节点。包含启用节点和同步任务的完整 Compose 流程见
+[使用 Docker Compose 运行 Elasticsearch](/zh/docs/self-hosting/advanced/full-text-search#使用-docker-compose-运行-elasticsearch)。
## 启动增量同步
@@ -153,6 +190,11 @@ bun run fts-search:sync -- --max-steps=8 --yes
```
每次最多执行 8 轮消费后退出。最终 JSON 中出现 `hasMore: true` 只表示本次达到上限,可以安全再次执行。应使用 cron、容器任务或其他进程管理器持续调度同一条命令,Elasticsearch 承担搜索期间不能停止。消费器会在领取任务前校验 PostgreSQL 采集定义和全部 Elasticsearch 写入别名;采集设施缺失或过期、别名异常、可重试写入失败或死信都会返回非零退出码。消费器不会自动安装触发器,也不会自动删除失败任务。
+省略 `--max-steps` 时只执行一轮;可用范围为 1 到 100。
+
+如果不想依赖外部调度器,可以加上 `--interval-seconds=<1-3600>` 让命令作为长期任务运行:它会重复执行同样的有界消费,`hasMore`
+为 true 时立即继续,否则等待指定秒数,并在收到 `SIGINT` / `SIGTERM` 时完成当前正在进行的那一步消费(而不是整个上限)后正常停止,因此进程管理器的停止超时只需覆盖一步。留下失败或死信任务的那一轮仍会以非零状态退出,因此进程管理器的重启策略和日志能够暴露问题。Compose
+中的 `fts-search-sync` 服务(profile `elasticsearch-sync`)使用的就是这种模式。
官方镜像内置 `/app/fts-search-elasticsearch-sync.cjs`,执行的是同一套有界消费逻辑:
@@ -165,6 +207,10 @@ docker run --rm --env-file .env \
保持持续调度,并反复运行 `bun run fts-search:reindex -- --status`,直到 `pending`、`ready`、`retrying`、`inFlight`、`dead` 和 `revisionLag` 全部为 0。切换查询前必须再检查一次。确认追平后,把 `FTS_SEARCH_PROVIDER` 设为 `elasticsearch` 并重新部署。追平前必须保持 `FTS_SEARCH_PROVIDER=pg_search`。Elasticsearch 出错时会直接暴露给调用方,搜索路径不会静默回退到 PostgreSQL 或 `ilike`。
+部署后,在约定好的观察窗口内保留旧 BM25 索引和 `pg_search` 扩展。需要确认成功的后端请求都归属于
+`elasticsearch`、没有新增 `pg_search` 请求、增量队列可以反复回到零延迟且没有死信,并完成当前部署实际使用的产品搜索检查。在旧数据库对象仍保留时,回滚只需恢复
+`FTS_SEARCH_PROVIDER=pg_search` 并重新部署;排查 Elasticsearch 期间可以继续运行增量消费任务。如果安装采集后停止消费器,源数据变更会继续在增量队列中累积,直到消费器恢复。
+
## 续跑与验收
- 进程崩溃或 Elasticsearch 临时失败后,使用同一个状态目录重新执行 `--apply --yes`,但不要再传 `--fresh-run`。已完成的数据类型会被跳过,未完成的数据类型从本地游标后继续。只要可选的采集设施仍在,暂停期间的变更就会保留在增量队列中,因此可以安全续跑。
@@ -191,3 +237,34 @@ ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --appl
<Callout type="info">
全量回填命令不会代替持续运行的增量消费器,也不会自行宣称应用已经可以切换搜索后端。只要 Elasticsearch 仍在承担搜索,就必须持续调度 `fts-search:sync`。
</Callout>
+
+## 在 Neon 截止日期前卸载 pg\_search
+
+Elasticsearch 稳定运行并经过观察窗口,且 PostgreSQL 已有当前恢复点后,先查看剩余的 LobeHub 管理对象:
+
+```bash
+bun run scripts/pgSearchCleanup/index.ts --status
+```
+
+确认后通过脚本完成清理,不需要从文档复制 SQL:
+
+```bash
+bun run scripts/pgSearchCleanup/index.ts --apply --yes
+```
+
+请使用直连 `DATABASE_URL`,不要使用事务池地址。只有
+`FTS_SEARCH_PROVIDER=elasticsearch` 时脚本才允许执行;遇到无法识别的 BM25 索引会拒绝继续。脚本会并发删除
+LobeHub 管理的旧索引,再以不带 `CASCADE` 的方式卸载扩展;中断后可以安全重跑。它不会删除 Elasticsearch
+依赖的增量队列、采集触发器或消费任务。
+
+官方镜像内置 `/app/fts-search-pg-search-cleanup.cjs`:
+
+```bash
+docker run --rm --env-file .env \
+ lobehub/lobehub:latest /app/fts-search-pg-search-cleanup.cjs --status
+docker run --rm --env-file .env \
+ lobehub/lobehub:latest /app/fts-search-pg-search-cleanup.cjs --apply --yes
+```
+
+受影响的 Neon 部署必须在 2026 年 9 月 21 日前完成此步骤。其他 PostgreSQL 服务可以保留
+`pg_search`,但删除已停用的对象可以避免继续维护不再使用的 BM25 索引。
diff --git a/docs/self-hosting/advanced/full-text-search.mdx b/docs/self-hosting/advanced/full-text-search.mdx
new file mode 100644
index 00000000000..cafb36113d0
--- /dev/null
+++ b/docs/self-hosting/advanced/full-text-search.mdx
@@ -0,0 +1,269 @@
+---
+title: Full-Text Search
+description: Choose and operate the pg_search or Elasticsearch backend for LobeHub product search.
+tags:
+ - Full-Text Search
+ - Elasticsearch
+ - pg_search
+ - Self-hosting
+---
+
+# Full-Text Search
+
+LobeHub uses full-text search for product data such as agents, topics, messages, files, knowledge
+bases, chat groups, and memories. This is separate from the web-search tools that an agent can call.
+
+LobeHub supports two product-search backends:
+
+| Backend | Best fit | Additional operations |
+| --------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `pg_search` | A deployment that already runs PostgreSQL with the ParadeDB `pg_search` extension and wants the simplest topology | PostgreSQL maintains the BM25 indexes; no separate search-sync worker is required |
+| `elasticsearch` | A deployment that wants a dedicated, independently scalable search service or must leave `pg_search` | Requires an Elasticsearch service (external, or the optional single-node service in the official Docker Compose file), an initial backfill, PostgreSQL change capture, and a continuously scheduled incremental consumer |
+
+`FTS_SEARCH_PROVIDER` selects one backend for the whole deployment. The accepted values are
+`pg_search` and `elasticsearch`; the default is `pg_search`. LobeHub does not silently fall back to
+the other backend when the selected provider is unavailable.
+
+<Callout type="warning">
+ `FTS_SEARCH_PROVIDER=elasticsearch` does not make historical database migrations skip
+ `pg_search`. The current Elasticsearch migration workflow is intended for an existing LobeHub
+ database that has already applied the `pg_search` migrations. A fresh database on a service that
+ cannot install `pg_search` is not currently supported merely by selecting Elasticsearch:
+ `bun run db:migrate` still reaches migrations that create the extension and BM25 indexes, and
+ fails when the database service does not provide them.
+</Callout>
+
+## Choose a backend
+
+### Keep `pg_search`
+
+Keep the default provider when your PostgreSQL service supports `pg_search`, its BM25 indexes fit
+comfortably with the rest of the database workload, and you prefer not to operate a separate search
+service.
+
+For a self-managed database, the LobeHub Docker examples use the
+`paradedb/paradedb:latest-pg17` image and preload `pg_search`. Apply the normal LobeHub database
+migrations to install the extension and the LobeHub-managed BM25 indexes, then keep:
+
+```bash
+FTS_SEARCH_PROVIDER=pg_search
+```
+
+### Use Elasticsearch
+
+Choose Elasticsearch when search needs independent capacity, when you want to separate search
+storage from transactional PostgreSQL, or when your PostgreSQL provider is ending `pg_search`
+support.
+
+Neon stopped offering `pg_search` to new projects on March 19, 2026. Neon has notified affected
+existing customers that the extension will be removed on September 21, 2026; queries, indexes, and
+applications that still depend on it will stop working after removal. Existing LobeHub deployments
+on Neon should complete the
+[pg\_search to Elasticsearch migration guide](/docs/self-hosting/advanced/elasticsearch-migration)
+before that deadline. Check Neon's
+[current pg\_search notice](https://neon.com/docs/extensions/pg_search) and
+[extension catalog](https://neon.com/docs/extensions/pg-extensions) before acting.
+
+There are two supported ways to run Elasticsearch. Both use the same backfill and incremental
+sync commands and the same `ES_INDEX_NAMESPACE`; they differ only in how LobeHub reaches the
+cluster.
+
+#### External Elasticsearch (Elastic Cloud or a managed cluster)
+
+- an Elasticsearch project reachable from the LobeHub server over HTTPS;
+- the official ICU analysis plugin, which is bundled in Elastic Cloud Serverless and must be
+ installed on every node of a self-managed cluster;
+- `ES_URL`, `ES_API_KEY`, and a stable `ES_INDEX_NAMESPACE`;
+- a full backfill followed by continuous Outbox synchronization;
+- `FTS_SEARCH_PROVIDER=elasticsearch` only after the backfill and incremental queue are complete.
+
+Plain HTTP is accepted only for loopback addresses during local development. LobeHub refuses to
+send an API key to any other host over plaintext HTTP.
+
+#### Docker Compose single-node Elasticsearch
+
+The official `docker-compose/deploy/docker-compose.yml` ships an optional, disabled-by-default
+`elasticsearch` service plus the backfill and sync commands built from the official LobeHub image.
+It is intended for a single-host deployment that wants Elasticsearch without an external account.
+Elasticsearch runs with security disabled and is reachable only inside the Compose network, so the
+plaintext, no-API-key connection must be enabled explicitly with `ES_ALLOW_INSECURE_HTTP=true`. See
+[Run Elasticsearch with Docker Compose](#run-elasticsearch-with-docker-compose) below.
+
+#### Database requirement for both options
+
+Selecting Elasticsearch does not remove the historical `pg_search` migrations. Until that
+follow-up ships, every LobeHub database, including a fresh Docker Compose install, must still run on
+a PostgreSQL image that can install `pg_search`, such as the bundled `paradedb/paradedb:latest-pg17`.
+Elasticsearch then takes over search traffic after the backfill; the `pg_search` objects can be
+removed later with the supported cleanup command.
+
+See [Migrate from pg\_search to Elasticsearch](/docs/self-hosting/advanced/elasticsearch-migration)
+for the complete rehearsal, backfill, cutover, and rollback procedure.
+
+## How Elasticsearch synchronization works
+
+PostgreSQL remains the source of truth. Enabling the Elasticsearch path installs change-capture
+triggers that coalesce source changes into a durable Outbox. The recurring consumer writes those
+changes to Elasticsearch. Search requests retrieve candidate identifiers from Elasticsearch, then
+LobeHub hydrates and authorizes the results against PostgreSQL before returning them.
+
+The operating sequence is therefore:
+
+```text
+PostgreSQL write
+ -> capture trigger
+ -> FTS Outbox
+ -> recurring fts-search:sync consumer
+ -> Elasticsearch index
+ -> candidate search
+ -> PostgreSQL permission check and hydration
+```
+
+The full reindex is only the initial snapshot. It does not replace the recurring consumer. Keep
+`fts-search:sync` scheduled for as long as Elasticsearch serves search traffic.
+
+## Run Elasticsearch with Docker Compose
+
+The optional services in `docker-compose/deploy/docker-compose.yml` are gated by Compose profiles,
+so a default `docker compose up` neither downloads nor starts them:
+
+| Service | Profile | Role |
+| -------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
+| `elasticsearch` | `elasticsearch` | Single node built locally from the pinned official image plus `analysis-icu`, with a named data volume, a health check, and no published port |
+| `fts-search-reindex` | `elasticsearch-reindex` | One-off backfill / status command from the `lobehub/lobehub` image; its checkpoint lives in the `fts-search-reindex-state` volume |
+| `fts-search-sync` | `elasticsearch-sync` | Long-running incremental consumer from the `lobehub/lobehub` image; restarts and logs when it hits failed or dead-letter work |
+
+Resource notes: the node uses a 1 GB JVM heap by default (`ES_JAVA_OPTS`); keep the heap at or
+below half of the memory available to the container and plan for at least 2 GB of RAM for
+Elasticsearch alone. Linux hosts must set `vm.max_map_count=262144`. The first `docker compose up`
+with the profile enabled builds the image once from the pinned official image and installs
+`analysis-icu`, so that build needs outbound access to `docker.elastic.co` and
+`artifacts.elastic.co`; later container recreations work offline. The build context is the
+`elasticsearch/Dockerfile` next to the Compose file, which `setup.sh` downloads as well. To upgrade
+Elasticsearch, change the version in both `image` and `build.args` of the `elasticsearch` service
+and run `docker compose up -d --build`.
+
+1. **Enable the node.** In `.env`, uncomment the Elasticsearch block and keep `pg_search` serving
+ requests:
+
+ ```bash
+ COMPOSE_PROFILES=elasticsearch
+ ES_URL=http://elasticsearch:9200
+ ES_ALLOW_INSECURE_HTTP=true
+ ES_INDEX_NAMESPACE=lobehub
+ # FTS_SEARCH_PROVIDER stays pg_search (the default) until the last step
+ ```
+
+ Then start the stack and wait for every service, including the new node, to become healthy;
+ the database migrations of the same release create the Outbox schema:
+
+ ```bash
+ docker compose up -d --wait
+ ```
+
+2. **Backfill.** Inspect the state, then run the one-off backfill. `--apply` installs the PostgreSQL
+ change capture, creates the 14 indexes with the ICU mapping, copies the data, and creates the
+ aliases:
+
+ ```bash
+ docker compose run --rm fts-search-reindex --status
+ docker compose run --rm fts-search-reindex --apply --fresh-run --yes
+ ```
+
+ Only the first run uses `--fresh-run`. If it is interrupted, run the same command without
+ `--fresh-run` to resume from the checkpoint volume. Repeat `--status` until the run is
+ `ready_for_incremental_sync`, every entity is `completed`, and every `failedCount` is `0`.
+
+3. **Start continuous sync.** Add the sync profile and recreate the stack:
+
+ ```bash
+ COMPOSE_PROFILES=elasticsearch,elasticsearch-sync
+ ```
+
+ ```bash
+ docker compose up -d
+ docker compose logs -f fts-search-sync
+ ```
+
+ The worker runs `fts-search-elasticsearch-sync.cjs --max-steps=8 --interval-seconds=15 --yes`
+ in a loop (`FTS_SEARCH_SYNC_INTERVAL_SECONDS` changes the pause between empty drains). It exits
+ non-zero on failed or dead-letter work; Compose restarts it, so a container that keeps restarting
+ means the queue needs attention. Keep it running for as long as Elasticsearch serves search.
+
+4. **Switch explicitly.** When `docker compose run --rm fts-search-reindex --status` shows `pending`,
+ `ready`, `retrying`, `inFlight`, `dead`, and `revisionLag` all at `0`, set
+ `FTS_SEARCH_PROVIDER=elasticsearch` in `.env` and recreate the application container:
+
+ ```bash
+ docker compose up -d lobe
+ ```
+
+ Nothing switches the provider automatically. Rolling back means restoring
+ `FTS_SEARCH_PROVIDER=pg_search` and recreating `lobe`; the sync worker may keep running.
+
+External target: the `fts-search-reindex` and `fts-search-sync` services depend only on
+PostgreSQL, not on the bundled node. To run them against Elastic Cloud instead, leave the
+`elasticsearch` profile out of `COMPOSE_PROFILES`, set `ES_URL` and `ES_API_KEY` in `.env`, and do
+not set `ES_ALLOW_INSECURE_HTTP`; steps 2 to 4 are otherwise identical.
+
+Security boundary of this mode: `ES_ALLOW_INSECURE_HTTP=true` permits plaintext HTTP to a
+non-loopback host and lets `ES_API_KEY` be omitted. It never permits sending an API key over
+plaintext HTTP, so do not combine it with `ES_API_KEY` and an `http://` URL. The Elasticsearch
+service publishes no port; never add one, because the node accepts unauthenticated requests. The
+Elastic Cloud path is unchanged: without this variable LobeHub still requires HTTPS and an API key.
+
+## Configuration reference
+
+| Variable | Purpose |
+| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `FTS_SEARCH_PROVIDER` | Deployment-wide provider: `pg_search` or `elasticsearch` |
+| `ES_URL` | Elasticsearch endpoint. HTTPS, or plaintext HTTP only for loopback or, with `ES_ALLOW_INSECURE_HTTP=true`, a private Compose hostname such as `elasticsearch` |
+| `ES_API_KEY` | Elasticsearch API key with index creation, bulk write, refresh, count, alias, and search permissions. Required unless `ES_ALLOW_INSECURE_HTTP=true` |
+| `ES_ALLOW_INSECURE_HTTP` | `true` opts in to plaintext HTTP without an API key for an Elasticsearch node reachable only inside a private container network. Never sends a key over HTTP |
+| `ES_INDEX_NAMESPACE` | Stable deployment-owned prefix for physical indexes and aliases |
+| `FTS_SEARCH_SYNC_ENABLED` | Enables the incremental consumer; set to `true` only after the initial backfill is ready. The Compose sync service sets it itself |
+
+Compose-only variables read by `docker-compose/deploy/docker-compose.yml`:
+
+| Variable | Purpose |
+| ---------------------------------- | ----------------------------------------------------------------------------------------------- |
+| `COMPOSE_PROFILES` | `elasticsearch` starts the node; `elasticsearch,elasticsearch-sync` also starts the sync worker |
+| `ES_JAVA_OPTS` | JVM heap of the Elasticsearch container, default `-Xms1g -Xmx1g` |
+| `FTS_SEARCH_SYNC_INTERVAL_SECONDS` | Seconds the sync worker sleeps after a drain that found no more work, default `15` |
+
+Do not reuse one namespace for unrelated LobeHub deployments. Do not change the namespace while a
+migration or incremental consumer is active.
+
+## Monitor Elasticsearch search
+
+LobeHub exports bounded OpenTelemetry metrics and traces without recording raw queries, user IDs,
+document IDs, or indexed text. The main metric families are:
+
+| Metric | What it answers |
+| ------------------------------------------------ | ---------------------------------------------------------------------- |
+| `fts_search_backend_operations_total` | Request volume and failures by provider, entity, operation, and result |
+| `fts_search_backend_operation_duration` | End-to-end backend latency |
+| `fts_search_backend_result_count` | Requested, candidate, and PostgreSQL-hydrated result counts |
+| `fts_search_elasticsearch_requests_total` | Actual Elasticsearch request volume and result |
+| `fts_search_elasticsearch_request_duration` | Elasticsearch request duration including response parsing |
+| `fts_search_elasticsearch_request_size` | Serialized request-body size |
+| `fts_search_elasticsearch_response_decoded_size` | Decoded response-body size |
+| `fts_search_elasticsearch_response_hits` | Hits returned per Elasticsearch request |
+| `fts_search_elasticsearch_server_took` | Processing time reported by Elasticsearch |
+
+Traces use spans named `fts.search.backend.<operation>`. Use request counts, bytes, hits, server
+time, and indexed storage together when investigating Elasticsearch cost; any single signal alone
+is insufficient. See [Grafana Observability](/docs/self-hosting/advanced/observability/grafana) for
+the self-hosted OpenTelemetry stack.
+
+## Operating rules
+
+- Back up PostgreSQL and rehearse on an isolated database copy and Elasticsearch target before a
+ production migration.
+- Keep the same durable checkpoint directory for every resume of one backfill. Never run two
+ workers against the same checkpoint and physical indexes.
+- Keep `pg_search` serving requests until every entity is complete, failures are zero, and the
+ incremental queue has caught up.
+- Use the supported cleanup command after cutover; users do not need to copy database-object SQL.
+- Keep the Elasticsearch Outbox, capture triggers, and recurring consumer. They are required by the
+ active Elasticsearch backend and are unrelated to Neon's removal of `pg_search`.
diff --git a/docs/self-hosting/advanced/full-text-search.zh-CN.mdx b/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
new file mode 100644
index 00000000000..a58102e426b
--- /dev/null
+++ b/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
@@ -0,0 +1,234 @@
+---
+title: 全文搜索
+description: 为 LobeHub 产品搜索选择并运行 pg_search 或 Elasticsearch 后端。
+tags:
+ - 全文搜索
+ - Elasticsearch
+ - pg_search
+ - 私有部署
+---
+
+# 全文搜索
+
+LobeHub 使用全文搜索检索助手、话题、消息、文件、知识库、群聊和记忆等产品数据。这里的全文搜索与助手可调用的联网搜索工具无关。
+
+LobeHub 支持两种产品搜索后端:
+
+| 后端 | 适用场景 | 额外运维工作 |
+| --------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------ |
+| `pg_search` | PostgreSQL 已支持 ParadeDB `pg_search` 扩展,希望部署结构尽量简单 | BM25 索引由 PostgreSQL 维护,不需要单独运行搜索同步任务 |
+| `elasticsearch` | 希望搜索服务独立扩容,或者数据库服务即将停止支持 `pg_search` | 需要 Elasticsearch 服务(外部服务,或官方 Docker Compose 附带的可选单节点服务)、首次全量回填、PostgreSQL 变更采集和持续运行的增量消费任务 |
+
+`FTS_SEARCH_PROVIDER` 为整个部署选择唯一的后端,可用值为 `pg_search` 和
+`elasticsearch`,默认值是 `pg_search`。选中的后端不可用时,LobeHub 不会静默切换到另一个后端。
+
+<Callout type="warning">
+ 设置 `FTS_SEARCH_PROVIDER=elasticsearch` 不会让历史数据库迁移跳过 `pg_search`。当前
+ Elasticsearch 迁移流程面向已经执行过 `pg_search` 迁移的现有 LobeHub 数据库。对于无法安装
+ `pg_search` 的数据库服务,仅选择 Elasticsearch 目前还不能完成全新建库:`bun run db:migrate`
+ 仍会执行创建扩展和 BM25 索引的历史迁移,并在数据库服务不提供它们时失败。
+</Callout>
+
+## 如何选择
+
+### 继续使用 `pg_search`
+
+如果 PostgreSQL 服务支持 `pg_search`,BM25 索引没有挤占其他数据库工作负载,并且你不希望额外维护一套搜索服务,可以继续使用默认后端。
+
+自建数据库时,LobeHub 的 Docker 示例使用 `paradedb/paradedb:latest-pg17` 镜像并预加载
+`pg_search`。执行正常的 LobeHub 数据库迁移以安装扩展和项目维护的 BM25 索引,并保持:
+
+```bash
+FTS_SEARCH_PROVIDER=pg_search
+```
+
+### 使用 Elasticsearch
+
+如果搜索需要独立容量、希望把搜索存储从事务 PostgreSQL 中拆开,或者数据库服务即将停止支持
+`pg_search`,可以选择 Elasticsearch。
+
+Neon 已于 2026 年 3 月 19 日停止为新项目提供 `pg_search`,并已通知受影响的现有客户:该扩展将在
+2026 年 9 月 21 日从 Neon 移除,此后依赖它的查询、索引和应用都会停止工作。已经在 Neon 上运行 LobeHub 的用户应在截止日期前完成
+[从 pg\_search 迁移到 Elasticsearch](/zh/docs/self-hosting/advanced/elasticsearch-migration)。执行前请同时核对 Neon 的
+[最新 pg\_search 公告](https://neon.com/docs/extensions/pg_search)和
+[扩展列表](https://neon.com/docs/extensions/pg-extensions)。
+
+Elasticsearch 有两种受支持的运行方式。两者使用同一套回填和增量同步命令、同一个
+`ES_INDEX_NAMESPACE`,区别只在于 LobeHub 如何连接集群。
+
+#### 外部 Elasticsearch(Elastic Cloud 或托管集群)
+
+- LobeHub 服务端可以通过 HTTPS 访问的 Elasticsearch 项目;
+- 官方 ICU 分析插件;Elastic Cloud Serverless 已内置,自建集群则必须在每个节点安装;
+- `ES_URL`、`ES_API_KEY` 和保持不变的 `ES_INDEX_NAMESPACE`;
+- 先完成全量回填,再持续消费 PostgreSQL 增量队列;
+- 只有全量回填完成且增量队列追平后,才能设置 `FTS_SEARCH_PROVIDER=elasticsearch`。
+
+明文 HTTP 只允许用于本地开发时的回环地址。LobeHub 拒绝把 API 密钥通过明文 HTTP 发送到任何其他主机。
+
+#### Docker Compose 单节点 Elasticsearch
+
+官方 `docker-compose/deploy/docker-compose.yml` 附带一个默认关闭的可选 `elasticsearch`
+服务,以及基于官方 LobeHub 镜像的回填和同步命令,适合希望在单机上使用 Elasticsearch、又不想申请外部账号的部署。该
+Elasticsearch 关闭了安全认证,只能在 Compose 内部网络访问,因此必须通过
+`ES_ALLOW_INSECURE_HTTP=true` 显式允许无 API 密钥的明文连接。详见下文
+[使用 Docker Compose 运行 Elasticsearch](#使用-docker-compose-运行-elasticsearch)。
+
+#### 两种方式共同的数据库限制
+
+选择 Elasticsearch 不会移除历史 `pg_search` 迁移。在这项后续工作完成前,所有 LobeHub 数据库(包括全新的 Docker
+Compose 安装)仍必须运行在能够安装 `pg_search` 的 PostgreSQL 镜像上,例如自带的
+`paradedb/paradedb:latest-pg17`。回填完成后由 Elasticsearch 接管搜索流量;`pg_search`
+相关对象可以之后通过项目提供的清理命令移除。
+
+完整的演练、回填、切换和回滚流程,请参阅
+[从 pg\_search 迁移到 Elasticsearch](/zh/docs/self-hosting/advanced/elasticsearch-migration)。
+
+## Elasticsearch 如何同步数据
+
+PostgreSQL 始终是数据事实来源。启用 Elasticsearch 路径后,采集触发器会把源数据变更合并写入持久化增量队列,持续运行的消费任务再把这些变更写入 Elasticsearch。搜索时,Elasticsearch 只返回候选标识,LobeHub 仍会回到 PostgreSQL 校验权限并读取最终结果。
+
+运行链路如下:
+
+```text
+PostgreSQL 写入
+ -> 采集触发器
+ -> 全文搜索增量队列
+ -> 持续运行的 fts-search:sync 消费任务
+ -> Elasticsearch 索引
+ -> 候选结果检索
+ -> PostgreSQL 权限校验和结果读取
+```
+
+全量回填只负责首次快照,不能代替持续消费任务。只要 Elasticsearch 仍在提供搜索,就必须持续调度
+`fts-search:sync`。
+
+## 使用 Docker Compose 运行 Elasticsearch
+
+`docker-compose/deploy/docker-compose.yml` 中的可选服务都由 Compose profile 控制,默认的
+`docker compose up` 既不会下载也不会启动它们:
+
+| 服务 | Profile | 作用 |
+| -------------------- | ----------------------- | --------------------------------------------------------------------------------- |
+| `elasticsearch` | `elasticsearch` | 基于固定版本官方镜像在本机构建并内置 `analysis-icu` 的单节点,使用命名数据卷和健康检查,不向宿主机公开端口 |
+| `fts-search-reindex` | `elasticsearch-reindex` | 基于 `lobehub/lobehub` 镜像的一次性回填 / 状态命令;checkpoint 保存在 `fts-search-reindex-state` 卷中 |
+| `fts-search-sync` | `elasticsearch-sync` | 基于 `lobehub/lobehub` 镜像的长期增量消费任务;遇到失败或死信任务时退出并由 Compose 重启,同时输出日志 |
+
+资源说明:节点默认使用 1 GB JVM 堆内存(`ES_JAVA_OPTS`);堆内存不要超过分配给容器内存的一半,并为
+Elasticsearch 单独预留至少 2 GB 内存。Linux 宿主机必须设置 `vm.max_map_count=262144`。启用该 profile 后首次执行
+`docker compose up` 会基于固定版本的官方镜像构建一次镜像并安装 `analysis-icu`,构建时需要能访问
+`docker.elastic.co` 和 `artifacts.elastic.co`;之后重建容器不再需要外网。构建上下文是 Compose 文件旁边的
+`elasticsearch/Dockerfile`,`setup.sh` 会一并下载。升级 Elasticsearch 时,同时修改 `elasticsearch` 服务中
+`image` 和 `build.args` 的版本号,再执行 `docker compose up -d --build`。
+
+1. **启用节点。** 在 `.env` 中取消 Elasticsearch 配置块的注释,并继续让 `pg_search` 提供搜索:
+
+ ```bash
+ COMPOSE_PROFILES=elasticsearch
+ ES_URL=http://elasticsearch:9200
+ ES_ALLOW_INSECURE_HTTP=true
+ ES_INDEX_NAMESPACE=lobehub
+ # FTS_SEARCH_PROVIDER 在最后一步之前保持默认值 pg_search
+ ```
+
+ 然后启动整套服务并等待包括新节点在内的所有服务通过健康检查;同一版本的数据库迁移会创建增量队列的基础结构:
+
+ ```bash
+ docker compose up -d --wait
+ ```
+
+2. **全量回填。** 先查看状态,再执行一次性回填。`--apply` 会安装 PostgreSQL 变更采集、按 ICU
+ 映射创建 14 类索引、复制数据并创建别名:
+
+ ```bash
+ docker compose run --rm fts-search-reindex --status
+ docker compose run --rm fts-search-reindex --apply --fresh-run --yes
+ ```
+
+ 只有第一次执行需要 `--fresh-run`。如果中断,去掉 `--fresh-run` 重新执行同一命令即可从 checkpoint
+ 卷续跑。反复执行 `--status`,直到状态为 `ready_for_incremental_sync`、所有数据类型为 `completed`
+ 且所有 `failedCount` 为 `0`。
+
+3. **启动持续同步。** 加上同步 profile 并重新创建服务:
+
+ ```bash
+ COMPOSE_PROFILES=elasticsearch,elasticsearch-sync
+ ```
+
+ ```bash
+ docker compose up -d
+ docker compose logs -f fts-search-sync
+ ```
+
+ 该任务循环执行 `fts-search-elasticsearch-sync.cjs --max-steps=8 --interval-seconds=15 --yes`
+ (`FTS_SEARCH_SYNC_INTERVAL_SECONDS` 可调整没有新任务时的等待时间)。遇到失败或死信任务时它会以非零状态退出,Compose
+ 会重启它,因此容器反复重启说明队列需要人工处理。只要 Elasticsearch 仍在提供搜索,就必须保持它运行。
+
+4. **显式切换。** 当 `docker compose run --rm fts-search-reindex --status` 显示 `pending`、`ready`、
+ `retrying`、`inFlight`、`dead` 和 `revisionLag` 全部为 `0` 时,在 `.env` 中设置
+ `FTS_SEARCH_PROVIDER=elasticsearch`,并重新创建应用容器:
+
+ ```bash
+ docker compose up -d lobe
+ ```
+
+ 任何步骤都不会自动切换搜索后端。回滚只需恢复 `FTS_SEARCH_PROVIDER=pg_search` 并重新创建
+ `lobe`;同步任务可以继续运行。
+
+外部目标:`fts-search-reindex` 和 `fts-search-sync` 只依赖 PostgreSQL,不依赖内置节点。如果要改为对接 Elastic
+Cloud,请不要在 `COMPOSE_PROFILES` 中启用 `elasticsearch` profile,在 `.env` 中设置 `ES_URL` 和 `ES_API_KEY`,
+且不要设置 `ES_ALLOW_INSECURE_HTTP`;第 2 到第 4 步完全相同。
+
+这一模式的安全边界:`ES_ALLOW_INSECURE_HTTP=true` 允许向非回环主机使用明文 HTTP,并允许省略
+`ES_API_KEY`;但它永远不允许通过明文 HTTP 发送 API 密钥,因此不要把它与 `ES_API_KEY` 和 `http://`
+地址同时使用。Elasticsearch 服务没有公开端口,也不要为它添加端口,因为该节点接受未认证的请求。Elastic Cloud
+路径保持不变:不设置这个变量时,LobeHub 仍然要求 HTTPS 和 API 密钥。
+
+## 配置项
+
+| 变量 | 用途 |
+| ------------------------- | ----------------------------------------------------------------------------------------------------------------- |
+| `FTS_SEARCH_PROVIDER` | 整个部署使用的搜索后端:`pg_search` 或 `elasticsearch` |
+| `ES_URL` | Elasticsearch 地址。使用 HTTPS;明文 HTTP 只允许用于回环地址,或在 `ES_ALLOW_INSECURE_HTTP=true` 时用于 `elasticsearch` 这类 Compose 内部主机名 |
+| `ES_API_KEY` | 具备建索引、批量写入、刷新、统计、别名和搜索权限的 Elasticsearch 密钥;除 `ES_ALLOW_INSECURE_HTTP=true` 外均为必需 |
+| `ES_ALLOW_INSECURE_HTTP` | 设为 `true` 时显式允许对只能在私有容器网络访问的 Elasticsearch 节点使用无 API 密钥的明文 HTTP;永远不会通过 HTTP 发送密钥 |
+| `ES_INDEX_NAMESPACE` | 当前部署独占且保持不变的物理索引和别名前缀 |
+| `FTS_SEARCH_SYNC_ENABLED` | 启用增量消费任务;首次全量回填就绪后才能设为 `true`。Compose 的同步服务会自行设置 |
+
+仅由 `docker-compose/deploy/docker-compose.yml` 读取的 Compose 变量:
+
+| 变量 | 用途 |
+| ---------------------------------- | ---------------------------------------------------------------- |
+| `COMPOSE_PROFILES` | `elasticsearch` 启动节点;`elasticsearch,elasticsearch-sync` 同时启动同步任务 |
+| `ES_JAVA_OPTS` | Elasticsearch 容器的 JVM 堆内存,默认 `-Xms1g -Xmx1g` |
+| `FTS_SEARCH_SYNC_INTERVAL_SECONDS` | 同步任务在一次没有新任务的消费后等待的秒数,默认 `15` |
+
+不同 LobeHub 部署不能共用同一个索引前缀。迁移或增量消费期间不能更改此前缀。
+
+## 监控 Elasticsearch 搜索
+
+LobeHub 会输出有限维度的 OpenTelemetry 指标和链路,不会记录原始查询、用户标识、文档标识或索引正文。主要指标包括:
+
+| 指标 | 可以回答的问题 |
+| ------------------------------------------------ | ---------------------------- |
+| `fts_search_backend_operations_total` | 按后端、数据类型、操作和结果统计的请求量及失败量 |
+| `fts_search_backend_operation_duration` | 搜索后端的端到端耗时 |
+| `fts_search_backend_result_count` | 请求数量、候选数量和 PostgreSQL 最终返回数量 |
+| `fts_search_elasticsearch_requests_total` | 实际 Elasticsearch 请求量和结果 |
+| `fts_search_elasticsearch_request_duration` | 包含响应解析的 Elasticsearch 请求耗时 |
+| `fts_search_elasticsearch_request_size` | 序列化后的请求体大小 |
+| `fts_search_elasticsearch_response_decoded_size` | 解码后的响应体大小 |
+| `fts_search_elasticsearch_response_hits` | 每次 Elasticsearch 请求返回的候选数量 |
+| `fts_search_elasticsearch_server_took` | Elasticsearch 上报的服务端处理时间 |
+
+链路名称为 `fts.search.backend.<operation>`。分析 Elasticsearch 成本时,需要同时查看请求量、请求与响应大小、
+候选数量、服务端耗时和索引存储,不能只看其中一项。自部署 OpenTelemetry 环境请参阅
+[Grafana 可观测性](/zh/docs/self-hosting/advanced/observability/grafana)。
+
+## 运维原则
+
+- 生产迁移前先备份 PostgreSQL,并使用隔离的数据库副本和 Elasticsearch 项目完成演练。
+- 同一次全量回填的每次续跑都必须使用同一个持久化状态目录,不能让两个任务同时操作同一份状态和物理索引。
+- 所有数据类型完成、失败数为 0、增量队列追平前,必须继续让 `pg_search` 对外提供搜索。
+- 切换后使用项目提供的清理命令,不需要手工复制数据库对象 SQL。
+- 必须保留 Elasticsearch 依赖的增量队列、采集触发器和持续消费任务;它们与 Neon 删除 `pg_search` 无关。
diff --git a/docs/self-hosting/environment-variables.mdx b/docs/self-hosting/environment-variables.mdx
index e35f6aa264c..369e82a72e6 100644
--- a/docs/self-hosting/environment-variables.mdx
+++ b/docs/self-hosting/environment-variables.mdx
@@ -26,6 +26,8 @@ LobeHub provides some additional configuration options when deployed, which can
<Card href={'environment-variables/cloud-sandbox'} title={'Cloud Sandbox'} />
<Card href={'environment-variables/analytics'} title={'Data Analytics'} />
+
+ <Card href={'advanced/full-text-search'} title={'Full-Text Search'} />
</Cards>
## Building a Custom Image with Overridden `NEXT_PUBLIC` Variables
diff --git a/docs/self-hosting/environment-variables.zh-CN.mdx b/docs/self-hosting/environment-variables.zh-CN.mdx
index ba9194f915d..1084fa0dff1 100644
--- a/docs/self-hosting/environment-variables.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables.zh-CN.mdx
@@ -24,4 +24,6 @@ LobeHub 在部署时提供了一些额外的配置项,你可以使用环境变
<Card href={'environment-variables/cloud-sandbox'} title={'云端沙箱'} />
<Card href={'environment-variables/analytics'} title={'数据统计'} />
+
+ <Card href={'advanced/full-text-search'} title={'全文搜索'} />
</Cards>
diff --git a/docs/self-hosting/migration/v2/breaking-changes.mdx b/docs/self-hosting/migration/v2/breaking-changes.mdx
index dfc752cd2b9..e37d9937d17 100644
--- a/docs/self-hosting/migration/v2/breaking-changes.mdx
+++ b/docs/self-hosting/migration/v2/breaking-changes.mdx
@@ -76,6 +76,13 @@ For deployment guides, see [Getting Started](/docs/self-hosting/start).
LobeHub 2.0 recommends using **PostgreSQL 17** or higher.
-This is because LobeHub 2.0 uses the [pg\_search](https://github.com/paradedb/paradedb/tree/main/pg_search) extension for full-text search capabilities. If you use Serverless Postgres services like Neon, the pg\_search extension is only available on PostgreSQL 17.
+LobeHub 2.0 introduced the [pg\_search](https://github.com/paradedb/paradedb/tree/main/pg_search)
+extension for full-text search. When 2.0 shipped, Neon provided it to new PostgreSQL 17 projects.
+Neon has since stopped offering `pg_search` to new projects and has notified affected existing
+customers that the extension will be removed on September 21, 2026. Existing Neon deployments
+should complete
+[Migrate from pg\_search to Elasticsearch](/docs/self-hosting/advanced/elasticsearch-migration).
+See [Full-Text Search](/docs/self-hosting/advanced/full-text-search) before choosing the search
+backend for a current deployment.
If you self-host your database with Docker, we recommend using the `paradedb/paradedb:latest-pg17` image.
diff --git a/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdx b/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdx
index ee6cbd56a5a..b86ef6572d2 100644
--- a/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdx
+++ b/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdx
@@ -74,6 +74,10 @@ LobeHub 2.0 仅支持 Server DB 模式,不再支持 Client DB (PGlite)。如
LobeHub 2.0 推荐使用 **PostgreSQL 17** 及以上版本。
-这是因为 LobeHub 2.0 使用了 [pg\_search](https://github.com/paradedb/paradedb/tree/main/pg_search) 插件来提供全文搜索能力。如果您使用 Neon 等 Serverless Postgres 服务,pg\_search 插件仅在 PostgreSQL 17 上可用。
+LobeHub 2.0 引入了 [pg\_search](https://github.com/paradedb/paradedb/tree/main/pg_search)
+扩展来提供全文搜索。当 2.0 发布时,Neon 会为新的 PostgreSQL 17 项目提供该扩展。此后 Neon 已停止为新项目提供
+`pg_search`,并已通知受影响的现有客户:该扩展将在 2026 年 9 月 21 日移除。现有 Neon 部署应在截止日期前完成
+[从 pg\_search 迁移到 Elasticsearch](/zh/docs/self-hosting/advanced/elasticsearch-migration)。当前部署在选择搜索后端前,请先阅读
+[全文搜索](/zh/docs/self-hosting/advanced/full-text-search)。
如果您使用 Docker 自建数据库,推荐使用 `paradedb/paradedb:latest-pg17` 镜像。
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/url.test.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/url.test.ts
new file mode 100644
index 00000000000..0babf7355e8
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/url.test.ts
@@ -0,0 +1,100 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { parseElasticsearchUrl, resolveElasticsearchTransport } from './url';
+
+describe('parseElasticsearchUrl', () => {
+ it('accepts HTTPS and loopback HTTP endpoints by default', () => {
+ expect(parseElasticsearchUrl('https://search.example.com').hostname).toBe('search.example.com');
+ expect(parseElasticsearchUrl('http://localhost:9200').port).toBe('9200');
+ expect(parseElasticsearchUrl('http://127.0.0.1:9200').hostname).toBe('127.0.0.1');
+ });
+
+ it('rejects plaintext HTTP to a non-loopback host by default', () => {
+ expect(() => parseElasticsearchUrl('http://elasticsearch:9200')).toThrow(
+ 'Elasticsearch URL must use HTTPS unless it targets loopback',
+ );
+ });
+
+ it('allows plaintext HTTP to a private-network host only when explicitly enabled', () => {
+ expect(
+ parseElasticsearchUrl('http://elasticsearch:9200', { allowInsecureHttp: true }).hostname,
+ ).toBe('elasticsearch');
+ expect(() =>
+ parseElasticsearchUrl('http://elasticsearch:9200', { allowInsecureHttp: false }),
+ ).toThrow('must use HTTPS unless it targets loopback');
+ });
+
+ it('never accepts embedded credentials or non-HTTP schemes', () => {
+ expect(() =>
+ parseElasticsearchUrl('http://elastic:secret@elasticsearch:9200', {
+ allowInsecureHttp: true,
+ }),
+ ).toThrow('must not contain embedded credentials');
+ expect(() =>
+ parseElasticsearchUrl('ftp://elasticsearch:9200', { allowInsecureHttp: true }),
+ ).toThrow('must use HTTPS unless it targets loopback');
+ expect(() => parseElasticsearchUrl('not a url')).toThrow('must be a valid absolute URL');
+ });
+});
+
+describe('resolveElasticsearchTransport', () => {
+ it('sends an API key over HTTPS', () => {
+ expect(
+ resolveElasticsearchTransport({ apiKey: 'secret', url: 'https://search.example.com' }),
+ ).toEqual({
+ authorizationHeader: 'ApiKey secret',
+ url: new URL('https://search.example.com'),
+ });
+ });
+
+ it('requires an API key unless insecure private-network access is explicitly enabled', () => {
+ expect(() => resolveElasticsearchTransport({ url: 'https://search.example.com' })).toThrow(
+ 'Elasticsearch API key is required unless ES_ALLOW_INSECURE_HTTP=true',
+ );
+ expect(() =>
+ resolveElasticsearchTransport({ apiKey: '', url: 'https://search.example.com' }),
+ ).toThrow('Elasticsearch API key is required unless ES_ALLOW_INSECURE_HTTP=true');
+ expect(() => resolveElasticsearchTransport({ url: 'http://elasticsearch:9200' })).toThrow(
+ 'must use HTTPS unless it targets loopback',
+ );
+ });
+
+ it('omits the Authorization header for an explicitly insecure private-network endpoint', () => {
+ expect(
+ resolveElasticsearchTransport({
+ allowInsecureHttp: true,
+ url: 'http://elasticsearch:9200',
+ }),
+ ).toEqual({ authorizationHeader: undefined, url: new URL('http://elasticsearch:9200') });
+ });
+
+ it('never sends an API key over plaintext HTTP to a non-loopback host', () => {
+ expect(() =>
+ resolveElasticsearchTransport({
+ allowInsecureHttp: true,
+ apiKey: 'secret',
+ url: 'http://elasticsearch:9200',
+ }),
+ ).toThrow('Elasticsearch API key must not be sent over plaintext HTTP');
+ });
+
+ it('keeps the loopback development path with an API key working', () => {
+ expect(
+ resolveElasticsearchTransport({ apiKey: 'secret', url: 'http://localhost:9200' }),
+ ).toEqual({ authorizationHeader: 'ApiKey secret', url: new URL('http://localhost:9200') });
+ });
+
+ it('still uses an API key over HTTPS when insecure HTTP is allowed but unused', () => {
+ expect(
+ resolveElasticsearchTransport({
+ allowInsecureHttp: true,
+ apiKey: 'secret',
+ url: 'https://search.example.com',
+ }),
+ ).toEqual({
+ authorizationHeader: 'ApiKey secret',
+ url: new URL('https://search.example.com'),
+ });
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/url.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/url.ts
index f39223a96b6..fe49cee9eae 100644
--- a/packages/database/src/repositories/ftsSearch/elasticsearch/url.ts
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/url.ts
@@ -1,5 +1,34 @@
+export interface ParseElasticsearchUrlOptions {
+ /**
+ * Permits plaintext HTTP to a non-loopback host. Intended only for an Elasticsearch node that is
+ * reachable exclusively over a private container network (for example the optional Docker Compose
+ * `elasticsearch` service). Enabling it never permits sending an API key over plaintext.
+ */
+ allowInsecureHttp?: boolean;
+}
+
+export interface ElasticsearchTransportInput extends ParseElasticsearchUrlOptions {
+ apiKey?: string;
+ url: string;
+}
+
+export interface ElasticsearchTransport {
+ /** `ApiKey <key>` when the endpoint is authenticated; undefined for explicit no-auth deployments. */
+ authorizationHeader: string | undefined;
+ url: URL;
+}
+
+const isLoopbackHostname = (hostname: string) =>
+ hostname === '127.0.0.1' ||
+ hostname === '[::1]' ||
+ hostname === 'localhost' ||
+ hostname.endsWith('.localhost');
+
/** Parses an Elasticsearch endpoint without allowing credentials to cross a plaintext network. */
-export const parseElasticsearchUrl = (value: string): URL => {
+export const parseElasticsearchUrl = (
+ value: string,
+ { allowInsecureHttp = false }: ParseElasticsearchUrlOptions = {},
+): URL => {
let url: URL;
try {
url = new URL(value);
@@ -11,15 +40,47 @@ export const parseElasticsearchUrl = (value: string): URL => {
throw new Error('Elasticsearch URL must not contain embedded credentials');
}
- const isLoopback =
- url.hostname === '127.0.0.1' ||
- url.hostname === '[::1]' ||
- url.hostname === 'localhost' ||
- url.hostname.endsWith('.localhost');
- /** Local development may use HTTP, but remote API keys must only cross an encrypted transport. */
- if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback)) {
+ const isPlaintextHttp = url.protocol === 'http:';
+ /**
+ * Local development may use HTTP, but remote API keys must only cross an encrypted transport.
+ * A non-loopback HTTP endpoint is accepted only by explicit operator opt-in.
+ */
+ const allowedPlaintext =
+ isPlaintextHttp && (isLoopbackHostname(url.hostname) || allowInsecureHttp);
+ if (url.protocol !== 'https:' && !allowedPlaintext) {
throw new Error('Elasticsearch URL must use HTTPS unless it targets loopback');
}
return url;
};
+
+/**
+ * Resolves the endpoint and Authorization header shared by every Elasticsearch HTTP client so the
+ * runtime, reindex, and sync paths enforce one security boundary:
+ *
+ * - an API key is required unless `allowInsecureHttp` was explicitly enabled;
+ * - an API key is never sent to a non-loopback host over plaintext HTTP, even when insecure HTTP
+ * is allowed.
+ */
+export const resolveElasticsearchTransport = ({
+ allowInsecureHttp = false,
+ apiKey,
+ url: value,
+}: ElasticsearchTransportInput): ElasticsearchTransport => {
+ const url = parseElasticsearchUrl(value, { allowInsecureHttp });
+
+ if (!apiKey) {
+ if (!allowInsecureHttp) {
+ throw new Error('Elasticsearch API key is required unless ES_ALLOW_INSECURE_HTTP=true');
+ }
+ return { authorizationHeader: undefined, url };
+ }
+
+ if (url.protocol === 'http:' && !isLoopbackHostname(url.hostname)) {
+ throw new Error(
+ 'Elasticsearch API key must not be sent over plaintext HTTP; use HTTPS or remove ES_API_KEY',
+ );
+ }
+
+ return { authorizationHeader: `ApiKey ${apiKey}`, url };
+};
diff --git a/packages/env/src/ftsSearch.ts b/packages/env/src/ftsSearch.ts
index 39f7e7f8195..6c2a2a164d9 100644
--- a/packages/env/src/ftsSearch.ts
+++ b/packages/env/src/ftsSearch.ts
@@ -4,12 +4,19 @@ import { z } from 'zod';
export const getElasticsearchFtsSearchConfig = () => {
return createEnv({
runtimeEnv: {
+ ES_ALLOW_INSECURE_HTTP: process.env.ES_ALLOW_INSECURE_HTTP,
ES_API_KEY: process.env.ES_API_KEY,
FTS_SEARCH_SYNC_ENABLED: process.env.FTS_SEARCH_SYNC_ENABLED,
ES_INDEX_NAMESPACE: process.env.ES_INDEX_NAMESPACE,
ES_URL: process.env.ES_URL,
},
server: {
+ /**
+ * Explicit opt-in for an Elasticsearch node on a private container network that runs with
+ * security disabled: allows plaintext `http://` to a non-loopback host and lets `ES_API_KEY`
+ * be omitted. An API key is still never sent over plaintext HTTP.
+ */
+ ES_ALLOW_INSECURE_HTTP: z.enum(['true', 'false']).optional(),
ES_API_KEY: z.string().min(1).optional(),
FTS_SEARCH_SYNC_ENABLED: z.enum(['true', 'false']).optional(),
ES_INDEX_NAMESPACE: z.string().min(1).optional(),
diff --git a/scripts/dockerComposeDeploy.test.ts b/scripts/dockerComposeDeploy.test.ts
new file mode 100644
index 00000000000..c426a649fd5
--- /dev/null
+++ b/scripts/dockerComposeDeploy.test.ts
@@ -0,0 +1,189 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+import { parse } from 'yaml';
+
+const deployDirectory = path.resolve(import.meta.dirname, '../docker-compose/deploy');
+const compose = parse(readFileSync(path.join(deployDirectory, 'docker-compose.yml'), 'utf8')) as {
+ services: Record<
+ string,
+ {
+ build?: { args?: Record<string, string>; context?: string };
+ command?: string[];
+ depends_on?: Record<string, { condition: string }>;
+ entrypoint?: string[];
+ environment?: string[];
+ healthcheck?: { test: string[] };
+ image: string;
+ ports?: string[];
+ profiles?: string[];
+ restart?: string;
+ stop_grace_period?: string;
+ volumes?: string[];
+ }
+ >;
+ volumes: Record<string, unknown>;
+};
+const dockerfile = readFileSync(path.resolve(import.meta.dirname, '../Dockerfile'), 'utf8');
+const elasticsearchDockerfile = readFileSync(
+ path.join(deployDirectory, 'elasticsearch/Dockerfile'),
+ 'utf8',
+);
+const setupScript = readFileSync(path.join(deployDirectory, '../setup.sh'), 'utf8');
+const envExamples = ['.env.example', '.env.zh-CN.example'].map((file) =>
+ readFileSync(path.join(deployDirectory, file), 'utf8'),
+);
+
+const ELASTICSEARCH_PROFILES = ['elasticsearch', 'elasticsearch-reindex', 'elasticsearch-sync'];
+
+describe('deploy docker-compose optional Elasticsearch', () => {
+ const {
+ elasticsearch,
+ 'fts-search-reindex': reindex,
+ 'fts-search-sync': sync,
+ } = compose.services;
+
+ it('keeps every Elasticsearch service behind an opt-in profile so the default deployment is unchanged', () => {
+ const profiled = Object.entries(compose.services).filter(([, service]) => service.profiles);
+ expect(profiled.map(([name]) => name).sort()).toEqual([
+ 'elasticsearch',
+ 'fts-search-reindex',
+ 'fts-search-sync',
+ ]);
+ for (const [, service] of profiled) {
+ expect(service.profiles!.every((profile) => ELASTICSEARCH_PROFILES.includes(profile))).toBe(
+ true,
+ );
+ }
+ expect(compose.services.lobe.depends_on).not.toHaveProperty('elasticsearch');
+ });
+
+ it('keeps the backfill and sync services usable against an external Elasticsearch', () => {
+ // Only the `elasticsearch` profile starts the bundled node. `docker compose run` starts
+ // dependencies, so a `depends_on: elasticsearch` here would build and start the local node
+ // even when .env points at an external Elastic Cloud target.
+ expect(elasticsearch.profiles).toEqual(['elasticsearch']);
+ for (const service of [reindex, sync]) {
+ expect(service.depends_on).not.toHaveProperty('elasticsearch');
+ expect(service.depends_on?.postgresql.condition).toBe('service_healthy');
+ }
+ });
+
+ it('builds a pinned official single-node image with ICU, persistence, and a health check', () => {
+ // A checked-in Dockerfile keeps the Compose file parseable by older Compose releases;
+ // `dockerfile_inline` would be rejected at parse time even with the profile disabled.
+ expect(elasticsearch.build).toEqual({
+ args: { ELASTICSEARCH_VERSION: expect.stringMatching(/^\d+\.\d+\.\d+$/) },
+ context: './elasticsearch',
+ });
+ const version = elasticsearch.build!.args!.ELASTICSEARCH_VERSION;
+ // The local tag carries the same version so bumping it triggers a rebuild on `up`.
+ expect(elasticsearch.image).toBe(`lobehub-elasticsearch-icu:${version}`);
+ expect(elasticsearchDockerfile).toContain(
+ 'FROM docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION}',
+ );
+ expect(elasticsearchDockerfile).toContain(
+ 'RUN bin/elasticsearch-plugin install --batch analysis-icu',
+ );
+ // The one-click installer must download the build context next to the Compose file.
+ expect(setupScript).toContain('"$SUB_DIR/elasticsearch/Dockerfile"');
+ expect(setupScript).toContain('"elasticsearch/Dockerfile"');
+ // No runtime plugin install: the entrypoint of the official image stays untouched.
+ expect(elasticsearch.command).toBeUndefined();
+ expect(elasticsearch.entrypoint).toBeUndefined();
+ expect(elasticsearch.environment).toContain('discovery.type=single-node');
+ expect(elasticsearch.environment).toContain('xpack.security.enabled=false');
+ expect(elasticsearch.environment?.some((entry) => entry.startsWith('ES_JAVA_OPTS='))).toBe(
+ true,
+ );
+ expect(elasticsearch.volumes).toContain('elasticsearch-data:/usr/share/elasticsearch/data');
+ expect(compose.volumes).toHaveProperty('elasticsearch-data');
+ expect(elasticsearch.healthcheck?.test.join(' ')).toContain('/_cluster/health');
+ });
+
+ it('never publishes the unauthenticated Elasticsearch port to the host', () => {
+ expect(elasticsearch.ports).toBeUndefined();
+ expect(reindex.ports).toBeUndefined();
+ expect(sync.ports).toBeUndefined();
+ });
+
+ it('runs backfill and continuous sync from the official LobeHub image', () => {
+ expect(reindex.image).toBe('lobehub/lobehub');
+ expect(reindex.restart).toBe('no');
+ // The image ENTRYPOINT is `/bin/node`, and `docker compose run <service> <args>` replaces the
+ // whole command, so the script must live in the entrypoint for `run ... --apply` to work.
+ expect(reindex.entrypoint).toEqual(['/bin/node', '/app/fts-search-elasticsearch-reindex.cjs']);
+ expect(reindex.command).toEqual(['--status']);
+ expect(reindex.environment).toContain('ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex');
+ expect(reindex.volumes).toContain('fts-search-reindex-state:/app/.elasticsearch-reindex');
+ expect(compose.volumes).toHaveProperty('fts-search-reindex-state');
+ // The image pre-creates the checkpoint mountpoint so the named volume inherits nextjs ownership.
+ expect(dockerfile).toContain('mkdir -p /app/.elasticsearch-reindex');
+
+ expect(sync.image).toBe('lobehub/lobehub');
+ expect(sync.restart).toBe('always');
+ expect(sync.entrypoint).toEqual(['/bin/node', '/app/fts-search-elasticsearch-sync.cjs']);
+ expect(sync.command).toEqual([
+ '--max-steps=8',
+ '--interval-seconds=${FTS_SEARCH_SYNC_INTERVAL_SECONDS:-15}',
+ '--yes',
+ ]);
+ expect(sync.environment).toContain('FTS_SEARCH_SYNC_ENABLED=true');
+ expect(sync.environment).toContain('MIGRATION_DB=1');
+ // Compose's default 10s grace period would SIGKILL a drain step in flight.
+ expect(sync.stop_grace_period).toBe('2m');
+ // The sync bundle keeps drizzle-orm external, and drizzle-orm/neon-serverless requires
+ // @neondatabase/serverless at load time even though DATABASE_DRIVER=node never uses it, so the
+ // image must ship that package next to pg and drizzle-orm or the container crash-loops.
+ expect(dockerfile).toContain('pnpm add pg drizzle-orm @neondatabase/serverless');
+ expect(dockerfile).toContain(
+ 'COPY --from=builder /deps/node_modules/@neondatabase /app/node_modules/@neondatabase',
+ );
+ });
+
+ it('never switches the search provider on behalf of the operator', () => {
+ for (const service of [elasticsearch, reindex, sync, compose.services.lobe]) {
+ expect(
+ service.environment?.some((entry) => entry.startsWith('FTS_SEARCH_PROVIDER=')),
+ ).toBeFalsy();
+ }
+ for (const envExample of envExamples) {
+ expect(envExample).not.toMatch(/^FTS_SEARCH_PROVIDER=/m);
+ }
+ });
+
+ it('documents the explicit insecure in-network mode in both env examples without exposing a key', () => {
+ for (const envExample of envExamples) {
+ expect(envExample).toContain('# COMPOSE_PROFILES=elasticsearch\n');
+ expect(envExample).toContain('# COMPOSE_PROFILES=elasticsearch,elasticsearch-sync\n');
+ expect(envExample).toContain('# ES_URL=http://elasticsearch:9200\n');
+ expect(envExample).toContain('# ES_ALLOW_INSECURE_HTTP=true\n');
+ expect(envExample).toContain('# ES_INDEX_NAMESPACE=lobehub\n');
+ expect(envExample).not.toMatch(/^#?\s*ES_API_KEY=/m);
+ // Every optional line stays commented so the default deployment ignores the whole block.
+ expect(envExample).not.toMatch(/^(COMPOSE_PROFILES|ES_[A-Z_]+)=/m);
+ }
+ });
+
+ it('keeps the in-network Elasticsearch URL on plain HTTP when setup.sh switches to HTTPS', () => {
+ const sedExpression =
+ "'/^#\\{0,1\\} \\{0,1\\}[A-Za-z0-9_]*=/{/ES_URL=/!s|http://|https://|;}' .env";
+ expect(setupScript).toContain(sedExpression);
+ // The rewrite must only touch assignments: the warning comment that tells operators not to
+ // pair ES_API_KEY with an http:// URL has to keep saying http://.
+ for (const envExample of envExamples) {
+ const rewritten = envExample
+ .split('\n')
+ .map((line) =>
+ /^#? ?\w*=/.test(line) && !line.includes('ES_URL=')
+ ? line.replace('http://', 'https://')
+ : line,
+ )
+ .join('\n');
+ expect(rewritten).toContain('# ES_URL=http://elasticsearch:9200\n');
+ expect(rewritten).toContain('http:// ');
+ expect(rewritten).not.toContain('https:// ');
+ }
+ });
+});
diff --git a/scripts/elasticsearchReindex/index.ts b/scripts/elasticsearchReindex/index.ts
index 720bae18f65..9ef3915104f 100644
--- a/scripts/elasticsearchReindex/index.ts
+++ b/scripts/elasticsearchReindex/index.ts
@@ -147,13 +147,15 @@ const { apiKeyEnvironmentName, expectedHostPrefix, urlEnvironmentName } =
const databaseUrl = process.env.DATABASE_URL;
const elasticsearchApiKey = process.env[apiKeyEnvironmentName];
const elasticsearchUrl = process.env[urlEnvironmentName];
+/** Same explicit opt-in as the application runtime; see `packages/env/src/ftsSearch.ts`. */
+const allowInsecureHttp = process.env.ES_ALLOW_INSECURE_HTTP === 'true';
const namespace = process.env.ES_INDEX_NAMESPACE;
const configuredStateDirectory = process.env.ES_REINDEX_STATE_DIR;
const stateDirectory = path.resolve(configuredStateDirectory ?? '.elasticsearch-reindex');
if (!databaseUrl) throw new Error('DATABASE_URL is required');
if (!namespace) throw new Error('ES_INDEX_NAMESPACE is required');
-if (apply && !elasticsearchApiKey) {
+if (apply && !elasticsearchApiKey && !allowInsecureHttp) {
throw new Error(`${apiKeyEnvironmentName} is required with --apply`);
}
if (apply && !elasticsearchUrl) {
@@ -359,6 +361,7 @@ const run = async () => {
bulkMaxBytes: bulkMaxBytes ?? 50 * 1024 * 1024,
credentialEnvName: apiKeyEnvironmentName,
endpointHostname,
+ endpointAuthentication: elasticsearchApiKey ? 'api_key' : 'none',
endpointEnvName: urlEnvironmentName,
expectedHostPrefix: expectedHostPrefix ?? null,
batchSizeByEntity,
@@ -385,7 +388,8 @@ const run = async () => {
);
const client = new FtsSearchReindexHttpClient({
- apiKey: elasticsearchApiKey!,
+ allowInsecureHttp,
+ apiKey: elasticsearchApiKey,
requestTimeoutMs,
url: elasticsearchUrl!,
});
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
index 02418df423f..f0ceef2be8e 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
@@ -50,6 +50,37 @@ describe('FtsSearchReindexHttpClient', () => {
).not.toThrow();
});
+ it('rejects an API key over plaintext HTTP even when insecure HTTP is allowed', () => {
+ expect(
+ () =>
+ new FtsSearchReindexHttpClient({
+ allowInsecureHttp: true,
+ apiKey: 'secret-key',
+ url: 'http://elasticsearch:9200',
+ }),
+ ).toThrow('must not be sent over plaintext HTTP');
+ });
+
+ it('requires an API key unless insecure private-network access is explicitly allowed', () => {
+ expect(() => new FtsSearchReindexHttpClient({ url: 'https://search.example.com' })).toThrow(
+ 'API key is required unless ES_ALLOW_INSECURE_HTTP=true',
+ );
+ });
+
+ it('sends unauthenticated requests to an explicitly insecure private-network endpoint', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ count: 3 }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ allowInsecureHttp: true,
+ url: 'http://elasticsearch:9200',
+ });
+
+ await expect(client.count('lobehub-agents-v1')).resolves.toBe(3);
+ const [endpoint, init] = fetchMock.mock.calls[0];
+ expect(String(endpoint)).toBe('http://elasticsearch:9200/lobehub-agents-v1/_count');
+ expect(Object.keys(init.headers)).not.toContain('Authorization');
+ });
+
it('creates a missing index without exposing credentials in the URL', async () => {
const fetchMock = vi
.fn()
diff --git a/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts b/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
index ed3fe6ec2d3..c6a7f0fcd9a 100644
--- a/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
+++ b/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
@@ -2,7 +2,7 @@ import { isDeepStrictEqual } from 'node:util';
import { z } from 'zod';
-import { parseElasticsearchUrl } from '../../../packages/database/src/repositories/ftsSearch/elasticsearch/url';
+import { resolveElasticsearchTransport } from '../../../packages/database/src/repositories/ftsSearch/elasticsearch/url';
import type {
FtsSearchReindexBulkItemResult,
FtsSearchReindexElasticsearchClient,
@@ -73,7 +73,10 @@ const settingsResponseSchema = z.record(
);
export interface FtsSearchReindexHttpClientOptions {
- apiKey: string;
+ /** Explicit opt-in for plaintext HTTP / no API key on a private container network. */
+ allowInsecureHttp?: boolean;
+ /** Required unless `allowInsecureHttp` is enabled; never sent over plaintext HTTP. */
+ apiKey?: string;
requestTimeoutMs?: number;
url: string;
}
@@ -90,21 +93,27 @@ export class FtsSearchReindexRequestError extends Error {
/** Minimal credential-safe Elasticsearch transport for the self-host reindex command. */
export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearchClient {
- private readonly apiKey: string;
+ private readonly authorizationHeader: string | undefined;
private readonly requestTimeoutMs: number;
private readonly url: URL;
- constructor({ apiKey, requestTimeoutMs = 30_000, url }: FtsSearchReindexHttpClientOptions) {
- this.apiKey = apiKey;
+ constructor({
+ allowInsecureHttp,
+ apiKey,
+ requestTimeoutMs = 30_000,
+ url,
+ }: FtsSearchReindexHttpClientOptions) {
+ const transport = resolveElasticsearchTransport({ allowInsecureHttp, apiKey, url });
+ this.authorizationHeader = transport.authorizationHeader;
this.requestTimeoutMs = requestTimeoutMs;
- this.url = parseElasticsearchUrl(url);
+ this.url = transport.url;
}
private async request(path: string, init: RequestInit = {}) {
return fetch(new URL(path, this.url), {
...init,
headers: {
- Authorization: `ApiKey ${this.apiKey}`,
+ ...(this.authorizationHeader ? { Authorization: this.authorizationHeader } : {}),
...init.headers,
},
signal: AbortSignal.timeout(this.requestTimeoutMs),
diff --git a/scripts/elasticsearchSync/index.test.ts b/scripts/elasticsearchSync/index.test.ts
index fcb10c768f6..88706beb975 100644
--- a/scripts/elasticsearchSync/index.test.ts
+++ b/scripts/elasticsearchSync/index.test.ts
@@ -57,6 +57,27 @@ describe('runElasticsearchFtsSearchSync', () => {
expect(drainOnce).toHaveBeenCalledOnce();
});
+ it('stops after the current step when the stop signal aborts mid-run', async () => {
+ const controller = new AbortController();
+ const { drainOnce, runtime } = createRuntime([]);
+ drainOnce
+ .mockImplementationOnce(async () => {
+ controller.abort();
+ return drainResult({ hasMore: true });
+ })
+ .mockResolvedValueOnce(drainResult({ hasMore: true }));
+
+ await expect(
+ runElasticsearchFtsSearchSync({
+ loadRuntime: async () => runtime,
+ maxSteps: 8,
+ stopSignal: controller.signal,
+ }),
+ ).resolves.toMatchObject({ hasMore: true, steps: 1 });
+ // The claimed work of the finished step is settled; no further step is started.
+ expect(drainOnce).toHaveBeenCalledOnce();
+ });
+
it('fails before draining when durable dead letters already exist', async () => {
const { runtime } = createRuntime([]);
const service = runtime.getFtsSearchSyncService();
@@ -122,4 +143,57 @@ describe('runElasticsearchFtsSearchSyncCli', () => {
expect.stringContaining('"type":"fts_search_sync_completed"'),
);
});
+
+ it('keeps draining in interval mode until the stop signal aborts', async () => {
+ const { drainOnce, runtime } = createRuntime([
+ drainResult({ hasMore: true }),
+ drainResult(),
+ drainResult(),
+ ]);
+ const controller = new AbortController();
+ const sleep = vi.fn(async (_milliseconds: number, signal: AbortSignal) => {
+ expect(signal).toBe(controller.signal);
+ if (sleep.mock.calls.length === 2) controller.abort();
+ });
+ const logSuccess = vi.fn();
+
+ await expect(
+ runElasticsearchFtsSearchSyncCli({
+ args: ['--interval-seconds=15', '--max-steps=1', '--yes'],
+ loadRuntime: async () => runtime,
+ logSuccess,
+ sleep,
+ stopSignal: controller.signal,
+ }),
+ ).resolves.toBe(0);
+
+ // Run 1 reports hasMore, so the worker continues immediately; runs 2 and 3 sleep.
+ expect(drainOnce).toHaveBeenCalledTimes(3);
+ expect(sleep).toHaveBeenCalledTimes(2);
+ expect(sleep).toHaveBeenCalledWith(15_000, controller.signal);
+ expect(logSuccess).toHaveBeenLastCalledWith(
+ JSON.stringify({ type: 'fts_search_sync_interval_stopped' }),
+ );
+ });
+
+ it('exits non-zero from interval mode when a bounded run fails', async () => {
+ const { runtime } = createRuntime([drainResult({ dead: 1, failed: 1 })]);
+ const sleep = vi.fn();
+ const logError = vi.fn();
+
+ await expect(
+ runElasticsearchFtsSearchSyncCli({
+ args: ['--interval-seconds=15', '--yes'],
+ loadRuntime: async () => runtime,
+ logError,
+ sleep,
+ stopSignal: new AbortController().signal,
+ }),
+ ).resolves.toBe(1);
+ expect(sleep).not.toHaveBeenCalled();
+ expect(logError).toHaveBeenCalledWith(
+ 'Elasticsearch full-text search sync failed:',
+ 'Elasticsearch full-text search sync created dead-letter work',
+ );
+ });
});
diff --git a/scripts/elasticsearchSync/index.ts b/scripts/elasticsearchSync/index.ts
index 6157d2cd932..d013afda0c4 100644
--- a/scripts/elasticsearchSync/index.ts
+++ b/scripts/elasticsearchSync/index.ts
@@ -28,6 +28,11 @@ export interface RunElasticsearchFtsSearchSyncOptions {
loadRuntime?: () => Promise<FtsSearchSyncRuntime>;
logStep?: (summary: ElasticsearchFtsSearchSyncRunSummary) => void;
maxSteps: number;
+ /**
+ * When aborted, the run stops after the current drain step instead of using the whole bound,
+ * so a supervisor stop only has to wait for one step rather than `maxSteps` of them.
+ */
+ stopSignal?: AbortSignal;
}
const loadRuntime = () => import('../../apps/server/src/services/ftsSearchSync');
@@ -37,6 +42,7 @@ export const runElasticsearchFtsSearchSync = async ({
loadRuntime: load = loadRuntime,
logStep = () => undefined,
maxSteps,
+ stopSignal,
}: RunElasticsearchFtsSearchSyncOptions): Promise<ElasticsearchFtsSearchSyncRunSummary> => {
const runtime = await load();
await runtime.verifyFtsSearchSyncReadiness();
@@ -77,6 +83,7 @@ export const runElasticsearchFtsSearchSync = async ({
throw new Error('Elasticsearch full-text search sync left retryable failed work');
}
if (drained.claimed === 0 || !drained.hasMore) break;
+ if (stopSignal?.aborted) break;
}
if (await service.hasDeadLetters()) {
@@ -93,13 +100,48 @@ export interface RunElasticsearchFtsSearchSyncCliOptions {
loadRuntime?: () => Promise<FtsSearchSyncRuntime>;
logError?: Logger;
logSuccess?: Logger;
+ /** Injectable sleep for the long-running interval mode. */
+ sleep?: (milliseconds: number, signal: AbortSignal) => Promise<void>;
+ /** Aborting this signal stops interval mode after the current bounded run finishes. */
+ stopSignal?: AbortSignal;
}
+const defaultSleep = (milliseconds: number, signal: AbortSignal) =>
+ new Promise<void>((resolve) => {
+ if (signal.aborted) {
+ resolve();
+ return;
+ }
+ const timer = setTimeout(() => {
+ signal.removeEventListener('abort', onAbort);
+ resolve();
+ }, milliseconds);
+ const onAbort = () => {
+ clearTimeout(timer);
+ resolve();
+ };
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+
+/**
+ * SIGINT / SIGTERM stop interval mode gracefully so a container supervisor can stop the worker
+ * between bounded runs without abandoning claimed Outbox work mid-run.
+ */
+const createProcessStopSignal = () => {
+ const controller = new AbortController();
+ const stop = () => controller.abort();
+ process.once('SIGINT', stop);
+ process.once('SIGTERM', stop);
+ return controller.signal;
+};
+
export const runElasticsearchFtsSearchSyncCli = async ({
args = process.argv.slice(2),
loadRuntime: load,
logError = console.error,
logSuccess = console.log,
+ sleep = defaultSleep,
+ stopSignal,
}: RunElasticsearchFtsSearchSyncCliOptions = {}): Promise<number> => {
try {
const options = parseElasticsearchFtsSearchSyncCliOptions(args);
@@ -109,12 +151,43 @@ export const runElasticsearchFtsSearchSyncCli = async ({
);
}
- const summary = await runElasticsearchFtsSearchSync({
- loadRuntime: load,
- logStep: (step) => logSuccess(JSON.stringify({ ...step, type: 'fts_search_sync_step' })),
- maxSteps: options.maxSteps,
- });
- logSuccess(JSON.stringify({ ...summary, success: true, type: 'fts_search_sync_completed' }));
+ const runOnce = async (signal?: AbortSignal) => {
+ const summary = await runElasticsearchFtsSearchSync({
+ loadRuntime: load,
+ logStep: (step) => logSuccess(JSON.stringify({ ...step, type: 'fts_search_sync_step' })),
+ maxSteps: options.maxSteps,
+ stopSignal: signal,
+ });
+ logSuccess(JSON.stringify({ ...summary, success: true, type: 'fts_search_sync_completed' }));
+ return summary;
+ };
+
+ if (options.intervalSeconds === undefined) {
+ await runOnce();
+ return 0;
+ }
+
+ /**
+ * Interval mode is the Compose-friendly long-running form of the same bounded drain. Each
+ * iteration keeps the bounded semantics; a drain that leaves failed or dead work still exits
+ * non-zero so the supervisor restart policy and logs make the failure visible. A stop signal
+ * ends the run after the current step, so the supervisor's grace period only has to cover one
+ * step, never a whole bounded run.
+ */
+ const signal = stopSignal ?? createProcessStopSignal();
+ logSuccess(
+ JSON.stringify({
+ intervalSeconds: options.intervalSeconds,
+ maxSteps: options.maxSteps,
+ type: 'fts_search_sync_interval_started',
+ }),
+ );
+ while (!signal.aborted) {
+ const summary = await runOnce(signal);
+ if (signal.aborted) break;
+ if (!summary.hasMore) await sleep(options.intervalSeconds * 1000, signal);
+ }
+ logSuccess(JSON.stringify({ type: 'fts_search_sync_interval_stopped' }));
return 0;
} catch (error) {
logError('Elasticsearch full-text search sync failed:', summarizeFtsSearchReindexError(error));
diff --git a/scripts/elasticsearchSync/options.test.ts b/scripts/elasticsearchSync/options.test.ts
index 1892ba665db..760330f28f0 100644
--- a/scripts/elasticsearchSync/options.test.ts
+++ b/scripts/elasticsearchSync/options.test.ts
@@ -23,6 +23,28 @@ describe('parseElasticsearchFtsSearchSyncCliOptions', () => {
},
);
+ it('accepts an optional interval for the long-running Compose worker mode', () => {
+ expect(
+ parseElasticsearchFtsSearchSyncCliOptions([
+ '--max-steps=8',
+ '--interval-seconds=15',
+ '--yes',
+ ]),
+ ).toEqual({ intervalSeconds: 15, maxSteps: 8, yes: true });
+ expect(parseElasticsearchFtsSearchSyncCliOptions(['--yes'])).not.toHaveProperty(
+ 'intervalSeconds',
+ );
+ });
+
+ it.each(['--interval-seconds=0', '--interval-seconds=3601', '--interval-seconds=1.5'])(
+ 'rejects invalid interval %s',
+ (argument) => {
+ expect(() => parseElasticsearchFtsSearchSyncCliOptions([argument])).toThrow(
+ '--interval-seconds must be an integer between 1 and 3600',
+ );
+ },
+ );
+
it('rejects duplicate or unknown arguments', () => {
expect(() =>
parseElasticsearchFtsSearchSyncCliOptions(['--max-steps=1', '--max-steps=2']),
diff --git a/scripts/elasticsearchSync/options.ts b/scripts/elasticsearchSync/options.ts
index 95d90aa840e..61ec270e6e4 100644
--- a/scripts/elasticsearchSync/options.ts
+++ b/scripts/elasticsearchSync/options.ts
@@ -1,33 +1,61 @@
export interface ElasticsearchFtsSearchSyncCliOptions {
+ /**
+ * When set, the CLI keeps repeating bounded drains and sleeps this many seconds between runs
+ * that found no more work. Undefined means one bounded run, which suits cron-style scheduling.
+ */
+ intervalSeconds?: number;
maxSteps: number;
yes: boolean;
}
const MAX_ALLOWED_STEPS = 100;
+const MAX_ALLOWED_INTERVAL_SECONDS = 3600;
+
+const readIntegerArgument = (
+ args: readonly string[],
+ name: string,
+ { max, min }: { max: number; min: number },
+): number | undefined => {
+ const matches = args.filter((argument) => argument.startsWith(`${name}=`));
+ if (matches.length > 1) throw new Error(`${name} can only be provided once`);
+
+ const raw = matches[0]?.slice(name.length + 1);
+ if (raw === undefined) return;
+
+ const value = Number.parseInt(raw, 10);
+ if (
+ !Number.isInteger(value) ||
+ raw === '' ||
+ String(value) !== raw ||
+ value < min ||
+ value > max
+ ) {
+ throw new Error(`${name} must be an integer between ${min} and ${max}`);
+ }
+ return value;
+};
export const parseElasticsearchFtsSearchSyncCliOptions = (
args: readonly string[],
): ElasticsearchFtsSearchSyncCliOptions => {
const knownFlags = new Set(['--yes']);
+ const knownValueArguments = ['--interval-seconds=', '--max-steps='];
const unknownArgument = args.find(
- (argument) => !knownFlags.has(argument) && !argument.startsWith('--max-steps='),
+ (argument) =>
+ !knownFlags.has(argument) &&
+ !knownValueArguments.some((prefix) => argument.startsWith(prefix)),
);
if (unknownArgument) throw new Error(`Unknown argument: ${unknownArgument}`);
- const maxStepArguments = args.filter((argument) => argument.startsWith('--max-steps='));
- if (maxStepArguments.length > 1) throw new Error('--max-steps can only be provided once');
-
- const rawMaxSteps = maxStepArguments[0]?.slice('--max-steps='.length);
- const maxSteps = rawMaxSteps === undefined ? 1 : Number.parseInt(rawMaxSteps, 10);
- if (
- !Number.isInteger(maxSteps) ||
- rawMaxSteps === '' ||
- (rawMaxSteps !== undefined && String(maxSteps) !== rawMaxSteps) ||
- maxSteps < 1 ||
- maxSteps > MAX_ALLOWED_STEPS
- ) {
- throw new Error(`--max-steps must be an integer between 1 and ${MAX_ALLOWED_STEPS}`);
- }
+ const maxSteps = readIntegerArgument(args, '--max-steps', { max: MAX_ALLOWED_STEPS, min: 1 });
+ const intervalSeconds = readIntegerArgument(args, '--interval-seconds', {
+ max: MAX_ALLOWED_INTERVAL_SECONDS,
+ min: 1,
+ });
- return { maxSteps, yes: args.includes('--yes') };
+ return {
+ ...(intervalSeconds === undefined ? {} : { intervalSeconds }),
+ maxSteps: maxSteps ?? 1,
+ yes: args.includes('--yes'),
+ };
};
diff --git a/scripts/pgSearchCleanup/index.ts b/scripts/pgSearchCleanup/index.ts
new file mode 100644
index 00000000000..bc082c5abeb
--- /dev/null
+++ b/scripts/pgSearchCleanup/index.ts
@@ -0,0 +1,39 @@
+import pg from 'pg';
+
+import { readPgSearchInventory } from './inventory';
+import { assertElasticsearchCutover, runPgSearchCleanup } from './operations';
+import { parsePgSearchCleanupOptions } from './options';
+
+const { Client } = pg;
+
+const run = async () => {
+ const options = parsePgSearchCleanupOptions(process.argv.slice(2));
+ const databaseUrl = process.env.DATABASE_URL;
+ if (!databaseUrl) throw new Error('DATABASE_URL is required');
+
+ if (options.mode === 'apply') assertElasticsearchCutover(process.env.FTS_SEARCH_PROVIDER);
+
+ const client = new Client({
+ application_name: 'lobehub-pg-search-cleanup',
+ connectionString: databaseUrl,
+ connectionTimeoutMillis: 8000,
+ statement_timeout: 600_000,
+ });
+ await client.connect();
+
+ try {
+ if (options.mode === 'status') {
+ console.log(JSON.stringify(await readPgSearchInventory(client), null, 2));
+ return;
+ }
+
+ console.log(JSON.stringify(await runPgSearchCleanup(client), null, 2));
+ } finally {
+ await client.end();
+ }
+};
+
+void run().catch((error) => {
+ console.error('pg_search cleanup failed:', error);
+ process.exitCode = 1;
+});
diff --git a/scripts/pgSearchCleanup/inventory.test.ts b/scripts/pgSearchCleanup/inventory.test.ts
new file mode 100644
index 00000000000..1741f3599e8
--- /dev/null
+++ b/scripts/pgSearchCleanup/inventory.test.ts
@@ -0,0 +1,36 @@
+import type { Client } from 'pg';
+import { describe, expect, it, vi } from 'vitest';
+
+import { readPgSearchInventory } from './inventory';
+
+describe('readPgSearchInventory', () => {
+ it('returns only the extension version and BM25 index identity', async () => {
+ const query = vi.fn().mockImplementation(async (sql: string) =>
+ sql.includes('FROM pg_extension')
+ ? { rows: [{ extversion: '0.15.26' }] }
+ : {
+ rows: [
+ {
+ index_name: 'messages_bm25_idx',
+ is_valid: true,
+ schema_name: 'public',
+ table_name: 'messages',
+ },
+ ],
+ },
+ );
+ const client = { query } as unknown as Client;
+
+ await expect(readPgSearchInventory(client)).resolves.toEqual({
+ bm25Indexes: [
+ {
+ name: 'messages_bm25_idx',
+ schema: 'public',
+ table: 'messages',
+ valid: true,
+ },
+ ],
+ extensionVersion: '0.15.26',
+ });
+ });
+});
diff --git a/scripts/pgSearchCleanup/inventory.ts b/scripts/pgSearchCleanup/inventory.ts
new file mode 100644
index 00000000000..2affa4e770b
--- /dev/null
+++ b/scripts/pgSearchCleanup/inventory.ts
@@ -0,0 +1,74 @@
+import type { Client, QueryResultRow } from 'pg';
+
+export const PG_SEARCH_BM25_INDEXES = [
+ { name: 'agents_bm25_idx', table: 'agents' },
+ { name: 'chat_groups_bm25_idx', table: 'chat_groups' },
+ { name: 'documents_bm25_idx', table: 'documents' },
+ { name: 'files_bm25_idx', table: 'files' },
+ { name: 'knowledge_bases_bm25_idx', table: 'knowledge_bases' },
+ { name: 'messages_bm25_idx', table: 'messages' },
+ { name: 'topics_bm25_idx', table: 'topics' },
+ { name: 'user_memories_activities_bm25_idx', table: 'user_memories_activities' },
+ { name: 'user_memories_bm25_idx', table: 'user_memories' },
+ { name: 'user_memories_contexts_bm25_idx', table: 'user_memories_contexts' },
+ { name: 'user_memories_experiences_bm25_idx', table: 'user_memories_experiences' },
+ { name: 'user_memories_identities_bm25_idx', table: 'user_memories_identities' },
+ { name: 'user_memories_preferences_bm25_idx', table: 'user_memories_preferences' },
+ {
+ name: 'user_memory_persona_documents_bm25_idx',
+ table: 'user_memory_persona_documents',
+ },
+] as const;
+
+export interface PgSearchBm25Index {
+ name: string;
+ schema: string;
+ table: string;
+ valid: boolean;
+}
+
+export interface PgSearchInventory {
+ bm25Indexes: PgSearchBm25Index[];
+ extensionVersion: null | string;
+}
+
+interface ExtensionRow extends QueryResultRow {
+ extversion: string;
+}
+
+interface IndexRow extends QueryResultRow {
+ index_name: string;
+ is_valid: boolean;
+ schema_name: string;
+ table_name: string;
+}
+
+export const readPgSearchInventory = async (client: Client): Promise<PgSearchInventory> => {
+ const [extension, indexes] = await Promise.all([
+ client.query<ExtensionRow>(`SELECT extversion FROM pg_extension WHERE extname = 'pg_search'`),
+ client.query<IndexRow>(`
+ SELECT
+ index_namespace.nspname AS schema_name,
+ index_relation.relname AS index_name,
+ table_relation.relname AS table_name,
+ index_record.indisvalid AS is_valid
+ FROM pg_index AS index_record
+ JOIN pg_class AS index_relation ON index_relation.oid = index_record.indexrelid
+ JOIN pg_namespace AS index_namespace ON index_namespace.oid = index_relation.relnamespace
+ JOIN pg_class AS table_relation ON table_relation.oid = index_record.indrelid
+ JOIN pg_am AS access_method ON access_method.oid = index_relation.relam
+ WHERE access_method.amname = 'bm25'
+ ORDER BY index_namespace.nspname, index_relation.relname
+ `),
+ ]);
+
+ return {
+ bm25Indexes: indexes.rows.map((row) => ({
+ name: row.index_name,
+ schema: row.schema_name,
+ table: row.table_name,
+ valid: row.is_valid,
+ })),
+ extensionVersion: extension.rows[0]?.extversion ?? null,
+ };
+};
diff --git a/scripts/pgSearchCleanup/operations.test.ts b/scripts/pgSearchCleanup/operations.test.ts
new file mode 100644
index 00000000000..8c6c8a71fd8
--- /dev/null
+++ b/scripts/pgSearchCleanup/operations.test.ts
@@ -0,0 +1,118 @@
+import type { Client } from 'pg';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { PgSearchInventory } from './inventory';
+import { PG_SEARCH_BM25_INDEXES } from './inventory';
+import {
+ assertElasticsearchCutover,
+ assertOnlyLobeHubBm25Indexes,
+ runPgSearchCleanup,
+} from './operations';
+
+const readPgSearchInventory = vi.hoisted(() => vi.fn());
+
+vi.mock('./inventory', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ readPgSearchInventory,
+}));
+
+const createInventory = ({
+ extensionVersion = '0.15.26',
+ indexes = true,
+}: {
+ extensionVersion?: null | string;
+ indexes?: boolean;
+} = {}): PgSearchInventory => ({
+ bm25Indexes: indexes
+ ? PG_SEARCH_BM25_INDEXES.map(({ name, table }) => ({
+ name,
+ schema: 'public',
+ table,
+ valid: true,
+ }))
+ : [],
+ extensionVersion,
+});
+
+const createClient = () =>
+ ({ query: vi.fn().mockResolvedValue({ rows: [] }) }) as unknown as Client;
+
+beforeEach(() => {
+ readPgSearchInventory.mockReset();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('pg_search cleanup operations', () => {
+ it('requires Elasticsearch to serve search before cleanup', () => {
+ expect(() => assertElasticsearchCutover('pg_search')).toThrow(
+ 'Set FTS_SEARCH_PROVIDER=elasticsearch',
+ );
+ expect(() => assertElasticsearchCutover(undefined)).toThrow(
+ 'Set FTS_SEARCH_PROVIDER=elasticsearch',
+ );
+ expect(() => assertElasticsearchCutover('elasticsearch')).not.toThrow();
+ });
+
+ it('rejects BM25 indexes not managed by LobeHub', () => {
+ const inventory = createInventory();
+ inventory.bm25Indexes.push({
+ name: 'custom_bm25_idx',
+ schema: 'public',
+ table: 'custom_documents',
+ valid: true,
+ });
+
+ expect(() => assertOnlyLobeHubBm25Indexes(inventory)).toThrow(
+ 'Refusing to remove unrecognized BM25 indexes',
+ );
+ });
+
+ it('drops known indexes concurrently before removing the extension', async () => {
+ const client = createClient();
+ readPgSearchInventory
+ .mockResolvedValueOnce(createInventory())
+ .mockResolvedValueOnce(createInventory({ indexes: false }))
+ .mockResolvedValueOnce(createInventory({ extensionVersion: null, indexes: false }));
+
+ const result = await runPgSearchCleanup(client);
+ const queries = vi.mocked(client.query).mock.calls.map(([sql]) => String(sql));
+ const indexDrops = queries.filter((sql) => sql.startsWith('DROP INDEX CONCURRENTLY'));
+ const extensionDropIndex = queries.indexOf('DROP EXTENSION IF EXISTS pg_search');
+
+ expect(indexDrops).toHaveLength(PG_SEARCH_BM25_INDEXES.length);
+ expect(extensionDropIndex).toBeGreaterThan(queries.lastIndexOf(indexDrops.at(-1)!));
+ expect(queries.some((sql) => sql.includes('CASCADE'))).toBe(false);
+ expect(result.removedIndexCount).toBe(PG_SEARCH_BM25_INDEXES.length);
+ });
+
+ it('does not mutate when the initial inventory contains an unknown index', async () => {
+ const client = createClient();
+ const inventory = createInventory();
+ inventory.bm25Indexes.push({
+ name: 'custom_bm25_idx',
+ schema: 'custom',
+ table: 'documents',
+ valid: true,
+ });
+ readPgSearchInventory.mockResolvedValueOnce(inventory);
+
+ await expect(runPgSearchCleanup(client)).rejects.toThrow(
+ 'Refusing to remove unrecognized BM25 indexes',
+ );
+ expect(client.query).not.toHaveBeenCalled();
+ });
+
+ it('is safe to rerun after cleanup has completed', async () => {
+ const client = createClient();
+ const emptyInventory = createInventory({ extensionVersion: null, indexes: false });
+ readPgSearchInventory.mockResolvedValue(emptyInventory);
+
+ const result = await runPgSearchCleanup(client);
+
+ expect(result.removedIndexCount).toBe(0);
+ });
+});
diff --git a/scripts/pgSearchCleanup/operations.ts b/scripts/pgSearchCleanup/operations.ts
new file mode 100644
index 00000000000..1c4fa3912bb
--- /dev/null
+++ b/scripts/pgSearchCleanup/operations.ts
@@ -0,0 +1,67 @@
+import type { Client } from 'pg';
+
+import { PG_SEARCH_BM25_INDEXES, type PgSearchInventory, readPgSearchInventory } from './inventory';
+
+const EXPECTED_INDEXES_BY_NAME = new Map<string, { name: string; table: string }>(
+ PG_SEARCH_BM25_INDEXES.map((index) => [index.name, index]),
+);
+
+export const assertOnlyLobeHubBm25Indexes = (inventory: PgSearchInventory) => {
+ const unexpectedIndexes = inventory.bm25Indexes.filter(({ name, schema, table }) => {
+ const expected = EXPECTED_INDEXES_BY_NAME.get(name);
+ return !expected || schema !== 'public' || table !== expected.table;
+ });
+
+ if (unexpectedIndexes.length > 0) {
+ throw new Error(
+ `Refusing to remove unrecognized BM25 indexes: ${unexpectedIndexes
+ .map(({ name, schema, table }) => `${schema}.${name} on ${table}`)
+ .join(', ')}`,
+ );
+ }
+};
+
+export const assertElasticsearchCutover = (provider: string | undefined) => {
+ if (provider !== 'elasticsearch') {
+ throw new Error(
+ 'Set FTS_SEARCH_PROVIDER=elasticsearch and complete the search cutover before cleanup',
+ );
+ }
+};
+
+const recordIndexDrop = (index: string, status: 'started' | 'succeeded') => {
+ console.log(JSON.stringify({ event: 'pg_search_index_drop', index, status }));
+};
+
+export const runPgSearchCleanup = async (client: Client) => {
+ const before = await readPgSearchInventory(client);
+ assertOnlyLobeHubBm25Indexes(before);
+
+ await client.query(`SET lock_timeout = '2s'`);
+ await client.query(`SET statement_timeout = '10min'`);
+
+ for (const { name } of PG_SEARCH_BM25_INDEXES) {
+ recordIndexDrop(name, 'started');
+ await client.query(`DROP INDEX CONCURRENTLY IF EXISTS public."${name}"`);
+ recordIndexDrop(name, 'succeeded');
+ }
+
+ const afterIndexes = await readPgSearchInventory(client);
+ assertOnlyLobeHubBm25Indexes(afterIndexes);
+ if (afterIndexes.bm25Indexes.length > 0) {
+ throw new Error('BM25 indexes remain after cleanup');
+ }
+
+ await client.query('DROP EXTENSION IF EXISTS pg_search');
+
+ const after = await readPgSearchInventory(client);
+ if (after.extensionVersion || after.bm25Indexes.length > 0) {
+ throw new Error('pg_search objects remain after cleanup');
+ }
+
+ return {
+ after,
+ before,
+ removedIndexCount: before.bm25Indexes.length,
+ };
+};
diff --git a/scripts/pgSearchCleanup/options.test.ts b/scripts/pgSearchCleanup/options.test.ts
new file mode 100644
index 00000000000..1f4150debdd
--- /dev/null
+++ b/scripts/pgSearchCleanup/options.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import { parsePgSearchCleanupOptions } from './options';
+
+describe('parsePgSearchCleanupOptions', () => {
+ it('defaults to read-only status', () => {
+ expect(parsePgSearchCleanupOptions([])).toEqual({ mode: 'status' });
+ expect(parsePgSearchCleanupOptions(['--status'])).toEqual({ mode: 'status' });
+ });
+
+ it('requires explicit confirmation before applying cleanup', () => {
+ expect(() => parsePgSearchCleanupOptions(['--apply'])).toThrow('--apply requires --yes');
+ expect(parsePgSearchCleanupOptions(['--apply', '--yes'])).toEqual({
+ mode: 'apply',
+ yes: true,
+ });
+ });
+
+ it('rejects ambiguous or unknown arguments', () => {
+ expect(() => parsePgSearchCleanupOptions(['--apply', '--status', '--yes'])).toThrow(
+ 'Choose exactly one',
+ );
+ expect(() => parsePgSearchCleanupOptions(['--force'])).toThrow('Unknown argument: --force');
+ expect(() => parsePgSearchCleanupOptions(['--status', '--yes'])).toThrow(
+ '--status does not accept mutation arguments',
+ );
+ });
+});
diff --git a/scripts/pgSearchCleanup/options.ts b/scripts/pgSearchCleanup/options.ts
new file mode 100644
index 00000000000..fa078e0082e
--- /dev/null
+++ b/scripts/pgSearchCleanup/options.ts
@@ -0,0 +1,24 @@
+export type PgSearchCleanupOptions = { mode: 'status' } | { mode: 'apply'; yes: true };
+
+export const parsePgSearchCleanupOptions = (args: readonly string[]): PgSearchCleanupOptions => {
+ const knownArguments = new Set(['--apply', '--status', '--yes']);
+ const unknownArgument = args.find((argument) => !knownArguments.has(argument));
+ if (unknownArgument) throw new Error(`Unknown argument: ${unknownArgument}`);
+
+ const modes = ['--apply', '--status'].filter((mode) => args.includes(mode));
+ if (modes.length > 1) throw new Error('Choose exactly one of --apply or --status');
+
+ const mode = modes[0] ?? '--status';
+ if (mode === '--status') {
+ if (args.some((argument) => argument !== '--status')) {
+ throw new Error('--status does not accept mutation arguments');
+ }
+ return { mode: 'status' };
+ }
+
+ if (!args.includes('--yes')) {
+ throw new Error('--apply requires --yes after reviewing the cleanup status');
+ }
+
+ return { mode: 'apply', yes: true };
+};
diff --git a/tsconfig.json b/tsconfig.json
index 23a90c43b3d..981aec0b9c4 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -64,6 +64,7 @@
"scripts/elasticsearchReindex/**/*.ts",
"scripts/elasticsearchSync/**/*.ts",
"scripts/installFtsSearchSyncCapture/**/*.ts",
+ "scripts/pgSearchCleanup/**/*.ts",
"*.ts",
"*.mts",
"*.cts",