Elasticsearch JavaScript 客户端「基础配置」全指南(Node/TS)

发布于:2025-08-13 ⋅ 阅读:(15) ⋅ 点赞:(0)

一、最小可用配置

const { Client } = require('@elastic/elasticsearch')

const client = new Client({
  cloud: { id: '<cloud-id>' },       // 或 node/nodes 连接自管集群
  auth: { apiKey: 'base64EncodedKey' },
  maxRetries: 5,
  sniffOnStart: true                  // ⚠️ Cloud 场景请勿启用
})

二、连接目标:node / nodes

  • 单个端点:

    node: 'http://localhost:9200'
    
  • 多个端点(负载均衡):

    nodes: ['http://localhost:9200', 'http://localhost:9201']
    
  • 完整对象(或对象数组)形式,可细化 TLS、Agent、Header、角色等:

    node: {
      url: new URL('http://localhost:9200'),
      tls: {/* tls options */},
      agent: {/* http agent options */},
      id: 'custom-node-id',
      headers: { 'x-tenant': 'A' },
      roles: { master: true, data: true, ingest: true, ml: false }
    }
    

三、认证方式:auth

  • Basic

    auth: { username: 'elastic', password: 'changeme' }
    
  • ApiKey(字符串或对象):

    auth: { apiKey: 'base64EncodedKey' }
    // 或
    auth: { apiKey: { id: 'foo', api_key: 'bar' } }
    
  • Bearer(服务账号令牌,不自动刷新):

    auth: { bearer: 'token' }
    

同时提供 Basic 与 ApiKey 时,ApiKey 优先生效

四、稳定性与时序:maxRetries / requestTimeout / pingTimeout

  • maxRetries(默认 3):单次请求最大重试次数。
  • requestTimeout(默认无):单次请求最大耗时(毫秒),覆盖客户端默认。
  • pingTimeout(默认 3000ms):健康探测(ping)的超时。

建议:面对慢查询,同时设置 requestTimeout(SDK 级)与查询体中的 "timeout"(分片收集窗口),双层兜底。

五、嗅探(Sniff)相关:谨慎开启

  • sniffInterval(ms/boolean,默认 false):定时嗅探。
  • sniffOnStart(默认 false):启动即嗅探。
  • sniffOnConnectionFault(默认 false):故障时嗅探。
  • sniffEndpoint(默认 '_nodes/_all/http'):嗅探端点。

提示:嗅探并非万能,先确认你的部署是否需要。Elastic Cloud 场景不要嗅探(节点在 LB 后面)。

六、节点“复活”策略:resurrectStrategy

  • 取值:'ping'(默认)、'optimistic''none'

    • ping:定期 ping 失活节点,成功则恢复。
    • optimistic:直接尝试使用,失败再标记。
    • none:不做自动复活(自行兜底)。

七、压缩与传输:suggestCompression / compression / tls

  • suggestCompression(默认 false):为每次请求添加 accept-encoding
  • compression'gzip'/false,默认 false):请求体压缩。
  • tls:传入 Node 的 http.SecureContextOptions(CA、证书校验等)。

八、代理与 Agent:proxy / agent

  • HTTP(S) 代理

    const client = new Client({
      node: 'http://localhost:9200',
      proxy: 'http://localhost:8080'
      // 或带认证:'http://user:pwd@localhost:8080'
    })
    
  • 自定义/禁用 Agent(影响 keep-alive、连接池等):

    // 传入 Agent 配置
    agent: { /* http.AgentOptions */ }
    
    // 传入函数(拿到 Connection 构造参数)
    agent: (opts) => new CustomAgent()
    
    // 禁用 agent(=禁用 keep-alive)
    agent: false
    

备注:若你使用的运行时/连接器不支持代理,需切换到支持代理的 HttpConnection 实现(来自 @elastic/transport)。

九、节点选择与过滤:nodeFilter / nodeSelector

  • 默认过滤器会避开仅 master 的节点:

    function defaultNodeFilter (conn) {
      if (conn.roles != null) {
        if (conn.roles.master && !conn.roles.data && !conn.roles.ingest && !conn.roles.ml) return false
      }
      return true
    }
    
  • 选择策略:'round-robin'(默认)、'random'、或自定义函数:

    function nodeSelector (connections) {
      const index = calculateIndex()
      return connections[index]
    }
    

十、可观测与标识:generateRequestId / name / opaqueIdPrefix / headers / context / enableMetaHeader

  • generateRequestId:自定义同步请求 ID 生成逻辑。
  • name(默认 'elasticsearch-js'):用于标识客户端实例。
  • opaqueIdPrefix:为 X-Opaque-Id 统一加前缀(链路追踪好用)。
  • headers:为所有请求追加统一头部。
  • context:自定义对象,会与 API 级 context 合并(埋点/日志)。
  • enableMetaHeader(默认 true):发送 x-elastic-client-meta 轻量遥测头。

十一、安全与资源上限:disablePrototypePoisoningProtection / caFingerprint / maxResponseSize / maxCompressedResponseSize / redaction

  • disablePrototypePoisoningProtection(默认 true):是否禁用原型污染防护。

    • 取值含义:false=启用全部防护'proto'/'constructor'=启用其中一种检查,true=禁用(默认,为性能考虑)。
  • caFingerprint:校验证书签发 CA 的 SHA256 指纹(pinning)。

  • maxResponseSize:限制未压缩响应体大小,超出则中止。

  • maxCompressedResponseSize:限制压缩后响应体大小。

  • redaction:错误元数据的敏感信息脱敏策略(可自定义来源与替换规则)。

十二、Cloud 与 Serverless:cloud / serverMode

  • cloud:Cloud ID + 认证的便捷封装:

    const client = new Client({
      cloud: { id: '<cloud-id>' },
      auth: { username: 'elastic', password: 'changeme' }
    })
    
  • serverMode(默认 "stack"):

    • "stack":传统多节点集群假设。
    • "serverless":为 Elastic Cloud Serverless 预设更合理的默认(如开启压缩、禁用依赖多节点的特性)。

十三、常用配置「配方」

1)本地开发单节点 + TLS CA 文件

const fs = require('node:fs')
const client = new Client({
  node: 'https://localhost:9200',
  auth: { username: 'elastic', password: 'changeme' },
  tls: { ca: fs.readFileSync('./http_ca.crt') },
  requestTimeout: 30_000
})

2)多节点自管集群 + 自定义选择器 + 超时/重试

const client = new Client({
  nodes: ['https://es1:9200','https://es2:9200','https://es3:9200'],
  auth: { apiKey: 'base64EncodedKey' },
  nodeSelector: (conns) => conns[Math.floor(Math.random() * conns.length)],
  maxRetries: 5,
  requestTimeout: 20_000,
  pingTimeout: 3_000,
  sniffOnConnectionFault: true
})

3)Elastic Cloud Serverless

const client = new Client({
  cloud: { id: '<cloud-id>' },
  auth: { username: 'elastic', password: 'changeme' },
  serverMode: 'serverless'
})

4)代理出网 + 限制响应体大小

const { HttpConnection } = require('@elastic/transport')
const client = new Client({
  node: 'https://es.example.com',
  proxy: 'http://user:pwd@proxy.local:8080',
  Connection: HttpConnection,
  maxResponseSize: 16 * 1024 * 1024,           // 16MB
  maxCompressedResponseSize: 4 * 1024 * 1024   // 4MB
})

5)可观测与链路标识

const client = new Client({
  node: 'https://es.example.com',
  opaqueIdPrefix: 'webapp',
  headers: { 'x-tenant': 'acme' },
  context: { service: 'web', region: 'us-west-2' },
  generateRequestId: (p, o) => `req-${Date.now()}-${Math.random().toString(16).slice(2)}`
})

结语

把「基础配置」理解为三层开关:

  1. 连得上(node/nodes、auth、TLS/代理);
  2. 跑得稳(超时/重试、嗅探/复活、压缩/连接池);
  3. 可运营(选择器/过滤、链路标识、脱敏与限流、响应上限)。

按你的部署形态(Cloud/自管/Serverless)套用上面的配方,再逐步收紧安全与配额,就能把 ES 客户端稳定地跑进生产。


网站公告

今日签到

点亮在社区的每一天
去签到