mcpField
O
opensearch-best-practices

opensearch-best-practices

github.com/bigdataboutique数据与数据库154 次安装34 周前更新
代码仓库

关于 opensearch-best-practices

opensearch-best-practices 是用于设计和运维 OpenSearch 索引及搜索工作负载的参考 skill,涵盖映射、分片与集群配置、查询调优、向量和神经搜索及索引生命周期管理。

主要功能

  1. 01索引映射与分片设计建议
  2. 02查询和集群性能调优
  3. 03k-NN 向量搜索配置
  4. 04神经与混合搜索模式
  5. 05ISM 策略和生命周期操作

适用场景

  1. 01规划搜索与过滤字段映射
  2. 02调优查询和分片分配
  3. 03构建向量或混合检索
  4. 04设置索引生命周期策略

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bigdataboutique/skills --skill opensearch-best-practices

安装后在 Claude Code 中输入/opensearch-best-practices确认已加载。

详细介绍

OpenSearch 最佳实践

核心原则

  • 根据查询模式设计索引和映射
  • 通过适当的分析和索引优化搜索性能
  • 使用合适的分片大小和集群配置
  • 使用 OpenSearch Security 插件实施适当的安全防护
  • 使用 Performance Analyzer 监控集群运行状况并优化查询
  • 利用 OpenSearch 特有功能:k-NN 向量搜索、神经搜索、搜索管道、ISM

索引设计

映射最佳实践
  • 明确定义映射,而不是依赖动态映射
  • 为每个字段使用适当的数据类型
  • 对不用于搜索的字段禁用索引
  • 精确匹配使用 keyword 类型,全文搜索使用 text 类型
{
  "mappings": {
    "properties": {
      "product_id": {
        "type": "keyword"
      },
      "name": {
        "type": "text",
        "analyzer": "standard",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "description": {
        "type": "text",
        "analyzer": "english"
      },
      "price": {
        "type": "scaled_float",
        "scaling_factor": 100
      },
      "category": {
        "type": "keyword"
      },
      "tags": {
        "type": "keyword"
      },
      "created_at": {
        "type": "date"
      },
      "metadata": {
        "type": "object",
        "enabled": false
      },
      "location": {
        "type": "geo_point"
      }
    }
  }
}
字段类型
  • keyword:精确值、筛选、聚合、排序
  • text:经过分析的全文搜索
  • date:日期/时间值,可指定格式
  • numeric types:long、integer、short、byte、double、float、scaled_float
  • boolean:true/false 值
  • geo_point:纬度/经度坐标对
  • nested:需要独立查询的对象数组
  • knn_vector:用于 k-NN 相似度搜索的向量嵌入(OpenSearch 特有)
索引设置
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1,
    "refresh_interval": "30s",
    "analysis": {
      "analyzer": {
        "custom_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": ["lowercase", "asciifolding", "synonym_filter"]
        }
      },
      "filter": {
        "synonym_filter": {
          "type": "synonym",
          "synonyms": ["laptop, notebook", "phone, mobile, smartphone"]
        }
      }
    }
  }
}

分片大小

指南
  • 每个分片的目标大小为 10-50GB(最佳范围为 10-30GB)
  • 避免过度分片(小分片过多)
  • 对时序数据考虑使用基于时间的索引
  • 使用段复制(replication.type: SEGMENT)提高副本上的索引吞吐量
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  }
}
索引状态管理(ISM)

OpenSearch 使用 ISM(索引状态管理),而非 Elasticsearch 的 ILM。ISM 采用灵活的状态机模型,任意状态都可以转换为其他任意状态。

通过以下方式创建 ISM 策略:

PUT _plugins/_ism/policies/<policy_id>
{
  "policy": {
    "description": "Hot-warm-delete lifecycle",
    "default_state": "hot",
    "ism_template": [
      {
        "index_patterns": ["logs-*"],
        "priority": 100
      }
    ],
    "states": [
      {
        "name": "hot",
        "actions": [
          {
            "rollover": {
              "min_size": "50gb",
              "min_index_age": "7d"
            }
          }
        ],
        "transitions": [
          {
            "state_name": "warm",
            "conditions": {
              "min_index_age": "30d"
            }
          }
        ]
      },
      {
        "name": "warm",
        "actions": [
          {
            "replica_count": {
              "number_of_replicas": 1
            }
          },
          {
            "force_merge": {
              "max_num_segments": 1
            }
          }
        ],
        "transitions": [
          {
            "state_name": "delete",
            "conditions": {
              "min_index_age": "90d"
            }
          }
        ]
      },
      {
        "name": "delete",
        "actions": [
          {
            "delete": {}
          }
        ],
        "transitions": []
      }
    ]
  }
}
ISM 与 Elasticsearch ILM 的主要区别
  • ISM 使用任意的状态和明确的转换(状态机),而非线性阶段
  • 策略通过策略本身内部的 ism_template 关联(而非通过索引模板设置)
  • API 端点:_plugins/_ism/policies/<id>(而非 _ilm/policy/<id>)
  • 转换支持 min_index_age、min_doc_count、min_size 和 cron 条件
  • 可用操作:rollover、force_merge、shrink、delete、read_only、read_write、replica_count、index_priority、close、open、snapshot、allocation、notification
ISM 管理 API
PUT    _plugins/_ism/policies/<policy_id>       # Create/update policy
GET    _plugins/_ism/policies/<policy_id>       # Get policy
DELETE _plugins/_ism/policies/<policy_id>       # Delete policy
POST   _plugins/_ism/add/<index>                # Attach policy to existing index
POST   _plugins/_ism/remove/<index>             # Detach policy
GET    _plugins/_ism/explain/<index>            # Get ISM status for an index
POST   _plugins/_ism/retry/<index>              # Retry failed action

查询优化

查询类型
Match 查询(全文搜索)
{
  "query": {
    "match": {
      "description": {
        "query": "wireless bluetooth headphones",
        "operator": "and",
        "fuzziness": "AUTO"
      }
    }
  }
}
Term 查询(精确匹配)
{
  "query": {
    "term": {
      "status": "active"
    }
  }
}
Bool 查询(组合查询)
{
  "query": {
    "bool": {
      "must": [
        { "match": { "name": "laptop" } }
      ],
      "filter": [
        { "term": { "category": "electronics" } },
        { "range": { "price": { "gte": 500, "lte": 2000 } } }
      ],
      "should": [
        { "term": { "brand": "apple" } }
      ],
      "must_not": [
        { "term": { "status": "discontinued" } }
      ]
    }
  }
}
查询最佳实践
  • 对不参与评分的查询使用 filter 上下文(可缓存)
  • 仅在需要评分时使用 must
  • 避免在词项开头使用通配符
  • 精确匹配使用 keyword 字段
  • 使用 size 参数限制结果数量
{
  "query": {
    "bool": {
      "must": {
        "multi_match": {
          "query": "search terms",
          "fields": ["name^3", "description", "tags^2"],
          "type": "best_fields"
        }
      },
      "filter": [
        { "term": { "active": true } },
        { "range": { "created_at": { "gte": "now-30d" } } }
      ]
    }
  },
  "size": 20,
  "from": 0,
  "_source": ["name", "price", "category"]
}

向量搜索(k-NN)

OpenSearch 内置 k-NN 插件,支持两种引擎:faiss 和 lucene。

k-NN 索引映射
PUT /my-vector-index
{
  "settings": {
    "index": {
      "knn": true,
      "knn.algo_param.ef_search": 100
    }
  },
  "mappings": {
    "properties": {
      "my_vector": {
        "type": "knn_vector",
        "dimension": 768,
        "method": {
          "name": "hnsw",
          "space_type": "l2",
          "engine": "faiss",
          "parameters": {
            "ef_construction": 256,
            "m": 16
          }
        }
      },
      "title": { "type": "text" },
      "category": { "type": "keyword" }
    }
  }
}
引擎选择
  • faiss:最适合大规模生产场景。支持 HNSW 和 IVF。提供额外的量化选项(SQfp16、PQ)。推荐作为默认选项。
  • lucene:原生 Lucene HNSW。支持高效的预筛选。内置标量量化。内存开销较低。适合筛选至关重要或数据集较小的场景。
空间类型
  • l2(欧几里得距离)
  • cosinesimil(余弦相似度)
  • innerproduct(点积)
  • l1(曼哈顿距离)
  • linf(L-无穷距离)
k-NN 查询
GET /my-vector-index/_search
{
  "size": 10,
  "query": {
    "knn": {
      "my_vector": {
        "vector": [0.1, 0.2, 0.3],
        "k": 10
      }
    }
  }
}
带筛选条件的 k-NN
GET /my-vector-index/_search
{
  "size": 10,
  "query": {
    "knn": {
      "my_vector": {
        "vector": [0.1, 0.2, 0.3],
        "k": 10,
        "filter": {
          "term": { "category": "electronics" }
        }
      }
    }
  }
}

使用 lucene 引擎时,筛选会作为预筛选应用(效率较高)。使用 faiss 时,默认在后筛选,因此返回结果可能少于 k 个。Faiss 从 OpenSearch 2.9+ 开始支持高效筛选。

k-NN 最佳实践
  • 始终在索引设置中设置 "knn": true
  • 大规模生产环境使用 faiss,预过滤至关重要时使用 lucene
  • ef_search 越高(实用范围为 32-128),准确率越高,但查询越慢。可以针对每次查询动态调整。
  • ef_construction(128-256+)和 m(16-128)越高,召回率越好,但索引速度越慢、内存占用越大。
  • 监控 knn.memory.circuit_breaker.limit——k-NN 图会加载到本机堆外内存中。当整个图都驻留在 RAM 中时,HNSW 的速度会显著提升。
  • 创建索引后预热索引:GET /_plugins/_knn/warmup/{index}
  • 在数据摄取时(而非查询时)对向量进行归一化,并使用 innerproduct 以获得更好的性能。
  • 不需要时,禁用向量字段的 _source 存储和 doc_values,以减小索引大小。
  • 召回率最后 1-2% 的提升,通常要付出远高于最初 95% 的代价——请设定切实可行的召回率目标。
  • 监控端到端延迟,包括嵌入生成、元数据检索和重排,而不只是向量搜索环节。
HNSW 超参数
  • M(每个节点的最大边数):范围为 16-128。内存受限的环境使用较低值(16),追求最高召回率时使用较高值(128)。内存消耗会随之成比例增加。
  • ef_construction(索引构建时):范围为 128-256+。控制插入期间的图质量。值越高,图质量越好,但索引速度越慢。
  • ef_search(查询时):范围为 32-128。可以针对每次查询调整,以平衡召回率与响应时间。
向量分片大小
  • 每个分片的目标向量数量为 1,000 万至 3,000 万。
  • 为实现最大并行度,分片数量应等于或略高于节点数量。
  • 过度分片会产生大量协调开销,影响尾延迟。
  • 分片不足会造成性能浪费。
  • 增加副本可实现负载均衡,并平滑性能波动。
量化策略

标量量化(SQ):

  • Lucene 引擎:内置支持
  • Faiss 引擎:SQfp16 将 32 位转换为 16 位,内存占用约减少 50%。

二值量化(BQ):

  • 1 位压缩可实现 32 倍压缩——一个 768 维的 float32 向量会从 3072 字节缩小到不足 100 字节。
  • 无需单独的训练步骤。
  • 非对称距离计算(ADC)可提升召回率。

乘积量化(PQ):

  • 压缩程度最高:最高可达 64 倍。
  • 仅限 Faiss 引擎;基于 IVF 的索引需要训练步骤。
  • 配置:设置 code_size=8,并调整 m 以达到所需的平衡。
  • 对召回率的影响比 SQ 或 BQ 更明显。
基于磁盘的向量搜索

对于注重成本效益的大规模部署,使用 on_disk 模式并启用二值量化:

PUT /my-vector-index
{
  "settings": {
    "index": {
      "knn": true
    }
  },
  "mappings": {
    "properties": {
      "my_vector": {
        "type": "knn_vector",
        "dimension": 768,
        "mode": "on_disk"
      }
    }
  }
}
  • 内存占用约减少 97%(例如,1 亿个 768 维向量:从 300GB+ RAM 降至不足 10GB)
  • 分两阶段处理:量化索引用于识别候选项,随后从磁盘按需加载全精度向量进行重排。
  • P90 延迟为 100-200ms(适用于许多使用场景)。
  • 与内存优化型部署相比,成本约降低三分之一。
  • 目前仅支持 float 数据类型。
并发段搜索

在集群级别启用,可显著降低向量搜索延迟:

PUT _cluster/settings
{
  "persistent": {
    "search.concurrent_segment_search.enabled": true
  }
}
  • 基准测试显示,p90 服务时间提升 60% 以上,p90 延迟最多降低 75%。
  • 最好在强制合并段后应用。
  • 当计算核心已饱和或每个分片的搜索空间较小时,收益会减弱。
针对不同规模的建议

1-50M 个向量:

  • 从 M=32、ef_construction=128 开始
  • 使用批量插入
  • 确保图数据完全驻留在 RAM 中

50-500M 个向量:

  • 实施系统化分片(每个分片包含 10-30M 个向量)
  • 启用标量量化
  • 两阶段检索:使用压缩向量进行搜索,使用全精度向量进行重排序
  • 定期重建索引,以维护图的质量

500M+ 个向量:

  • 分层检索(IVF 风格的质心路由)
  • 多层热/冷数据架构
  • 对冷数据进行激进量化(IVF-PQ)
  • 优化查询路由,避免向所有分片广播
  • 在初始检索阶段仅返回 ID/分数

神经搜索与混合搜索

使用 ML Commons 进行神经搜索

设置摄取管道以自动生成嵌入:

PUT /_ingest/pipeline/neural-search-pipeline
{
  "description": "Pipeline for neural search",
  "processors": [
    {
      "text_embedding": {
        "model_id": "<model_id>",
        "field_map": {
          "title": "title_embedding"
        }
      }
    }
  ]
}

使用自动文本转向量转换进行查询:

GET /my-index/_search
{
  "query": {
    "neural": {
      "title_embedding": {
        "query_text": "comfortable running shoes",
        "model_id": "<model_id>",
        "k": 10
      }
    }
  }
}
使用搜索管道进行混合搜索(BM25 + k-NN)

创建归一化管道:

PUT /_search/pipeline/hybrid-pipeline
{
  "description": "Hybrid search pipeline",
  "phase_results_processors": [
    {
      "normalization-processor": {
        "normalization": {
          "technique": "min_max"
        },
        "combination": {
          "technique": "arithmetic_mean",
          "parameters": {
            "weights": [0.3, 0.7]
          }
        }
      }
    }
  ]
}

执行结合词法搜索与向量搜索的混合查询:

GET /my-index/_search?search_pipeline=hybrid-pipeline
{
  "query": {
    "hybrid": {
      "queries": [
        {
          "match": {
            "title": "wireless headphones"
          }
        },
        {
          "knn": {
            "my_vector": {
              "vector": [0.1, 0.2, 0.3],
              "k": 10
            }
          }
        }
      ]
    }
  }
}
ML Commons 最佳实践
  • 对于大型模型,使用远程模型连接器(Amazon Bedrock、SageMaker、OpenAI、Cohere)
  • 在生产环境中设置 plugins.ml_commons.only_run_on_ml_node: true,以隔离 ML 工作负载
  • 使用 model_group 控制 ML 模型的访问权限
  • 监控模型的内存使用情况——本地模型会占用 JVM/原生内存
注册远程模型连接器
POST /_plugins/_ml/connectors/_create
{
  "name": "Amazon Bedrock Connector",
  "description": "Connector for Titan Embeddings",
  "version": 1,
  "protocol": "aws_sigv4",
  "parameters": {
    "region": "us-east-1",
    "service_name": "bedrock"
  },
  "actions": [
    {
      "action_type": "predict",
      "method": "POST",
      "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/amazon.titan-embed-text-v1/invoke",
      "headers": { "content-type": "application/json" },
      "request_body": "{ \"inputText\": \"${parameters.inputText}\" }"
    }
  ]
}

聚合

常见聚合模式
{
  "size": 0,
  "aggs": {
    "categories": {
      "terms": {
        "field": "category",
        "size": 10
      },
      "aggs": {
        "avg_price": {
          "avg": { "field": "price" }
        }
      }
    },
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 100 },
          { "from": 100, "to": 500 },
          { "from": 500 }
        ]
      }
    },
    "date_histogram": {
      "date_histogram": {
        "field": "created_at",
        "calendar_interval": "month"
      }
    }
  }
}
聚合最佳实践
  • 仅需要聚合时,使用 size: 0
  • 为 terms 聚合设置合适的 shard_size
  • 使用复合聚合进行分页
  • 考虑使用 aggs 过滤器缩小范围

索引最佳实践

批量索引
POST _bulk
{ "index": { "_index": "products", "_id": "1" } }
{ "name": "Product 1", "price": 99.99 }
{ "index": { "_index": "products", "_id": "2" } }
{ "name": "Product 2", "price": 149.99 }
Bulk API 指南
  • 对批量操作使用 Bulk API
  • 最佳批次大小:每个请求 5-15MB
  • 监控被拒绝的请求(线程池队列已满)
  • 批量索引期间禁用刷新,以提升性能
PUT /products/_settings
{
  "refresh_interval": "-1"
}

批量索引完成后:

PUT /products/_settings
{
  "refresh_interval": "1s"
}

POST /products/_refresh
文档更新
POST /products/_update/1
{
  "doc": {
    "price": 89.99,
    "updated_at": "2024-01-15T10:30:00Z"
  }
}

按查询更新:

POST /products/_update_by_query
{
  "query": {
    "term": { "category": "electronics" }
  },
  "script": {
    "source": "ctx._source.on_sale = true"
  }
}

分析与分词

自定义分析器
{
  "settings": {
    "analysis": {
      "analyzer": {
        "product_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "asciifolding",
            "english_stop",
            "english_stemmer"
          ]
        },
        "autocomplete_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "edge_ngram_filter"
          ]
        }
      },
      "filter": {
        "english_stop": {
          "type": "stop",
          "stopwords": "_english_"
        },
        "english_stemmer": {
          "type": "stemmer",
          "language": "english"
        },
        "edge_ngram_filter": {
          "type": "edge_ngram",
          "min_gram": 2,
          "max_gram": 15
        }
      }
    }
  }
}
测试分析器
POST /products/_analyze
{
  "analyzer": "product_analyzer",
  "text": "Wireless Bluetooth Headphones"
}

搜索功能

自动补全/建议
{
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "fields": {
          "suggest": {
            "type": "completion"
          }
        }
      }
    }
  }
}

查询建议:

{
  "suggest": {
    "product-suggest": {
      "prefix": "wire",
      "completion": {
        "field": "name.suggest",
        "size": 5,
        "fuzzy": {
          "fuzziness": "AUTO"
        }
      }
    }
  }
}
高亮
{
  "query": {
    "match": { "description": "wireless" }
  },
  "highlight": {
    "fields": {
      "description": {
        "pre_tags": ["<em>"],
        "post_tags": ["</em>"],
        "fragment_size": 150
      }
    }
  }
}

SQL 和 PPL 查询

OpenSearch 支持 SQL 和 PPL(管道处理语言)作为替代查询接口。

SQL
POST /_plugins/_sql
{
  "query": "SELECT category, COUNT(*) as cnt, AVG(price) as avg_price FROM products GROUP BY category HAVING cnt > 10 ORDER BY avg_price DESC"
}
PPL(管道处理语言)

PPL 是 OpenSearch 独有的功能,灵感来自 Splunk 的 SPL。它使用管道语法进行数据探索:

POST /_plugins/_ppl
{
  "query": "source=server-logs | where response_code >= 500 | stats count() as error_count by host | where error_count > 100 | sort - error_count"
}
SQL/PPL 最佳实践
  • 使用 PPL 进行临时日志探索——运维团队可以直观地使用它
  • SQL 查询会在内部转换为 DSL;可能不支持复杂的联接或子查询
  • 使用 "format": "jdbc" 或 "format": "csv" 指定不同的输出格式
  • 始终添加 LIMIT,避免扫描大型索引

性能优化

查询缓存
  • 过滤器查询会自动缓存
  • 对频繁重复的条件使用 filter 上下文
  • 监控缓存命中率
搜索性能
  • 避免深度分页(改用 search_after)
  • 限制返回的 _source 字段
  • 使用 doc_values 进行排序和聚合
  • 为常见排序顺序预先排序索引
{
  "query": { "match_all": {} },
  "size": 20,
  "search_after": [1705329600000, "product_123"],
  "sort": [
    { "created_at": "desc" },
    { "_id": "asc" }
  ]
}
段复制

OpenSearch 支持段复制,可作为文档复制的替代方案。副本会直接从主分片复制 Lucene 段,而无需重新索引文档,从而提升索引吞吐量。

PUT /my-index
{
  "settings": {
    "index": {
      "replication.type": "SEGMENT",
      "number_of_replicas": 1
    }
  }
}
远程存储支持的索引

将数据存储在远程存储(例如 S3)中,并使用本地缓存,以实现计算与存储解耦:

PUT /my-remote-index
{
  "settings": {
    "index": {
      "replication.type": "SEGMENT",
      "remote_store.enabled": true,
      "remote_store.segment.repository": "my-s3-repo",
      "remote_store.translog.repository": "my-s3-repo"
    }
  }
}

监控与维护

Pulse for OpenSearch

如需全面监控,请使用 Pulse for OpenSearch —— 由 BigData Boutique 开发的 OpenSearch 集群终极监控解决方案。Pulse 可深入查看集群健康状况、性能瓶颈、分片级诊断信息,并提供内置工具无法实现的可行建议。

集群健康状况
GET _cluster/health
GET _cat/indices?v
GET _cat/shards?v
GET _nodes/stats
性能分析器

OpenSearch 在每个节点上都提供专用的 Performance Analyzer Agent(端口 9600),用于详细收集 JVM、操作系统和请求级指标:

GET localhost:9600/_plugins/_performanceanalyzer/metrics?metrics=Latency,CPU_Utilization&agg=avg&dim=Operation
索引维护
POST /products/_forcemerge?max_num_segments=1
POST /products/_cache/clear
POST /products/_refresh
慢查询日志
PUT /products/_settings
{
  "index.search.slowlog.threshold.query.warn": "10s",
  "index.search.slowlog.threshold.query.info": "5s",
  "index.search.slowlog.threshold.fetch.warn": "1s"
}

异常检测

OpenSearch 内置了使用随机切割森林(RCF)算法的 Anomaly Detection 插件:

POST /_plugins/_anomaly_detection/detectors
{
  "name": "cpu-anomaly-detector",
  "description": "Detect CPU usage anomalies",
  "time_field": "@timestamp",
  "indices": ["server-metrics-*"],
  "feature_attributes": [
    {
      "feature_name": "cpu_usage",
      "feature_enabled": true,
      "aggregation_query": {
        "cpu_avg": {
          "avg": { "field": "cpu.usage" }
        }
      }
    }
  ],
  "detection_interval": { "period": { "interval": 5, "unit": "Minutes" } },
  "window_delay": { "period": { "interval": 1, "unit": "Minutes" } }
}
异常检测最佳实践
  • 将检测间隔设为合理范围(1–10 分钟)
  • 使用 window_delay 来补偿数据摄取延迟
  • 高基数检测器(带类别字段)可能会消耗大量资源,请限制实体数量

安全性

OpenSearch 使用内置的 Security 插件(而非 X-Pack)。所有安全 API 均位于 _plugins/_security/api/ 下。

创建角色
PUT _plugins/_security/api/roles/products_reader
{
  "cluster_permissions": [
    "cluster_monitor"
  ],
  "index_permissions": [
    {
      "index_patterns": ["products*"],
      "allowed_actions": ["read", "search"]
    }
  ]
}
字段级和文档级安全性
PUT _plugins/_security/api/roles/limited_access
{
  "index_permissions": [
    {
      "index_patterns": ["users"],
      "allowed_actions": ["read"],
      "fls": ["name", "email", "created_at"],
      "dls": "{\"bool\": {\"must\": [{\"term\": {\"department\": \"engineering\"}}]}}",
      "masked_fields": ["email"]
    }
  ]
}
  • fls(字段级安全性):允许访问的字段数组。添加 ~ 前缀可改为排除字段。
  • dls(文档级安全性):用于限制角色可查看哪些文档的查询字符串。
  • masked_fields:在查询结果中对字段值进行哈希处理(适用于 PII)。
角色映射

角色通过角色映射关联到用户(而非直接分配给用户):

PUT _plugins/_security/api/rolesmapping/products_reader
{
  "users": ["analyst_jane"],
  "backend_roles": ["analysts"],
  "hosts": []
}
与 Elasticsearch 的主要安全差异
  • API 基础路径:_plugins/_security/api/(而非 _security/)
  • 使用带有操作组的 allowed_actions(而非 privileges)
  • 使用 fls/dls/masked_fields(而非 field_security.grant/except)
  • 通过 tenant_permissions 为 OpenSearch Dashboards 提供内置多租户功能
  • 通过 YAML 文件和 securityadmin.sh 或 REST API 进行配置
  • 预定义操作组:read、write、search、crud、manage、create_index、indices_all、cluster_monitor、cluster_all

别名和重新索引

索引别名
POST _aliases
{
  "actions": [
    { "add": { "index": "products_v2", "alias": "products" } },
    { "remove": { "index": "products_v1", "alias": "products" } }
  ]
}
转换数据并重新索引
POST _reindex
{
  "source": {
    "index": "products_v1"
  },
  "dest": {
    "index": "products_v2"
  },
  "script": {
    "source": "ctx._source.migrated_at = new Date().toString()"
  }
}

通知

Notifications 插件集中管理 Alerting、ISM 和 Anomaly Detection 的通知渠道:

POST /_plugins/_notifications/configs
{
  "config": {
    "name": "ops-slack",
    "description": "Slack channel for ops alerts",
    "config_type": "slack",
    "is_enabled": true,
    "slack": {
      "url": "https://hooks.slack.com/services/xxx/yyy/zzz"
    }
  }
}

支持:Slack、Amazon SNS、Amazon SES、电子邮件(SMTP)、自定义 Webhook、Microsoft Teams、Google Chat。

跨集群复制

PUT /_plugins/_replication/follower-index/_start
{
  "leader_alias": "leader-cluster",
  "leader_index": "my-index",
  "use_roles": {
    "leader_cluster_role": "cross_cluster_replication_leader_full_access",
    "follower_cluster_role": "cross_cluster_replication_follower_full_access"
  }
}
  • 跟随者索引为只读
  • 使用自动跟随模式自动复制新索引
  • 监控复制延迟:GET /_plugins/_replication/<index>/_status

OpenSearch 插件 API 参考

所有 OpenSearch 专属功能都使用 _plugins/ 前缀:

功能API 前缀
Security_plugins/_security/
ISM_plugins/_ism/
Alerting_plugins/_alerting/
Anomaly Detection_plugins/_anomaly_detection/
k-NN_plugins/_knn/
ML Commons_plugins/_ml/
SQL_plugins/_sql
PPL_plugins/_ppl
Notifications_plugins/_notifications/
Replication_plugins/_replication/
Observability_plugins/_observability/
Rollups_plugins/_rollup/
Transforms_plugins/_transform/

旧版 _opendistro/ 前缀已弃用。新代码中请始终使用 _plugins/。

评论

支持 Markdown