如何用jq处理Elasticsearch别名输出生成合法的别名操作JSON?
用JQ转换Elasticsearch索引别名数据为合法更新JSON
输入示例
假设你从ES获取的索引别名数据结构如下:
{ "testindex_123": { "aliases": { "testindex": {} } }, "testindex_122": { "aliases": { "testindex": {} } } }
JQ处理命令
直接用以下jq命令即可生成符合ES _update_aliases API要求的操作JSON:
jq '{ actions: [ (. | keys[] | select(endswith("_123"))) as $write_idx | { add: { index: $write_idx, alias: "testindex", is_write_index: true } }, (. | keys[] | select(endswith("_122"))) as $read_idx | { add: { index: $read_idx, alias: "testindex", is_write_index: false } } ] }' input.json
输出结果
执行后会生成可直接提交给ES的合法JSON:
{ "actions": [ { "add": { "index": "testindex_123", "alias": "testindex", "is_write_index": true } }, { "add": { "index": "testindex_122", "alias": "testindex", "is_write_index": false } } ] }
关键逻辑说明
- 用
keys[]提取所有索引名,通过select(endswith("_123"))筛选出要设为写入索引的目标;如果是按时间戳后缀匹配,也可以改成更通用的时间戳匹配逻辑,比如select(test(".*_\\d+$") | .[-3:] == "123") - 分别生成
add操作,给目标索引设置is_write_index的对应值 - 最终结构符合ES
_update_aliasesAPI的要求,直接POST到/_aliases端点即可完成别名配置
通用化调整
如果你的索引后缀是动态时间戳(比如按日期生成),可以修改筛选逻辑,自动把时间戳最大的索引设为写入索引,其余设为非写入,更适配按时间轮转的索引场景:
jq '{ actions: [ (. | keys[] | capture("(?<prefix>.*)_(?<ts>\\d+)") | {name: ., ts: .ts|tonumber}) | sort_by(.ts) | (.[-1] | { add: { index: .name, alias: (.name | capture("(?<prefix>.*)_\\d+").prefix), is_write_index: true } }), (. | keys[] | capture("(?<prefix>.*)_(?<ts>\\d+)") | {name: ., ts: .ts|tonumber}) | sort_by(.ts)[:-1][] | { add: { index: .name, alias: (.name | capture("(?<prefix>.*)_\\d+").prefix), is_write_index: false } } ] }' input.json
内容的提问来源于stack exchange,提问作者user19692907
相关产品推荐
相关产品推荐

