You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch特定格式索引批量重索引脚本报错求助

解决Elasticsearch批量重索引时的JSON解析异常问题

嘿,我看你遇到的是reindex命令的JSON解析错误,这个问题其实很常见——就是请求体里的索引名称没加引号,导致Elasticsearch没法正确识别JSON格式。

先看你贴的错误信息:Unrecognized token 'abc_58b888be': was expecting ('true', 'false' or 'null'),这就说明你的reindex请求体里,索引名是裸写的(比如"index": abc_xxxx),但JSON要求字符串必须用双引号包起来,所以Elasticsearch把这个索引名当成了非法的token,直接报错了。

问题根源

你的Shell脚本在构造reindex的JSON请求时,肯定是没给索引变量加双引号。比如原本应该写成"index": "abc_xxxx",结果写成了"index": abc_xxxx,这就触发了解析异常。

修正后的脚本示例

我给你改了一份脚本,重点把JSON里的索引名部分加上了正确的引号,还加了一些实用的细节(比如用jq复制索引映射和设置):

#!/bin/bash

# 替换成你的Elasticsearch地址
ES_URL="http://localhost:9200"
# 如果有账号密码,取消下面注释并填写
# ES_AUTH="-u username:password"

# 遍历所有以abc_开头的索引
for index in $(curl -s ${ES_AUTH} "${ES_URL}/_cat/indices/abc_*?h=index"); do
  temp_index="temp_${index}"
  echo "开始处理索引: ${index},临时索引: ${temp_index}"

  # 1. 创建临时索引,复制原索引的设置和映射
  curl -XPUT ${ES_AUTH} "${ES_URL}/${temp_index}" -H "Content-Type: application/json" -d "{
    \"settings\": $(curl -s ${ES_AUTH} "${ES_URL}/${index}/_settings" | jq '.settings'),
    \"mappings\": $(curl -s ${ES_AUTH} "${ES_URL}/${index}/_mappings" | jq '.["'${index}'"].mappings')
  }"

  # 2. 把原索引数据同步到临时索引 --- 这里必须给索引名加双引号
  curl -XPOST ${ES_AUTH} "${ES_URL}/_reindex?wait_for_completion=true" -H "Content-Type: application/json" -d "{
    \"source\": {
      \"index\": \"${index}\"
    },
    \"dest\": {
      \"index\": \"${temp_index}\"
    }
  }"

  # 3. 删除原索引
  curl -XDELETE ${ES_AUTH} "${ES_URL}/${index}"

  # 4. 重建原索引,复用临时索引的设置和映射
  curl -XPUT ${ES_AUTH} "${ES_URL}/${index}" -H "Content-Type: application/json" -d "{
    \"settings\": $(curl -s ${ES_AUTH} "${ES_URL}/${temp_index}/_settings" | jq '.settings'),
    \"mappings\": $(curl -s ${ES_AUTH} "${ES_URL}/${temp_index}/_mappings" | jq '.["'${temp_index}'"].mappings')
  }"

  # 5. 把临时索引数据同步回原索引 --- 同样要加引号
  curl -XPOST ${ES_AUTH} "${ES_URL}/_reindex?wait_for_completion=true" -H "Content-Type: application/json" -d "{
    \"source\": {
      \"index\": \"${temp_index}\"
    },
    \"dest\": {
      \"index\": \"${index}\"
    }
  }"

  # 6. 删除临时索引
  curl -XDELETE ${ES_AUTH} "${ES_URL}/${temp_index}"

  echo "索引 ${index} 处理完成!"
done

几个关键提醒

  1. JSON引号的转义:在Shell里用-d参数传JSON时,JSON里的双引号必须用\"转义,不然Shell会把它当成命令的结束符,导致格式混乱。
  2. 用jq处理JSON:jq是个非常好用的JSON处理工具,能帮你避免手动拼接JSON时的格式错误。如果你的机器上没有,用apt install jq(Debian/Ubuntu)或者brew install jq(Mac)就能安装。
  3. 先测试单个命令:在跑批量脚本之前,先单独执行一个reindex命令测试格式对不对,比如:
curl -XPOST "http://localhost:9200/_reindex?wait_for_completion=true" -H "Content-Type: application/json" -d '{
  "source": {
    "index": "abc_2ab99742-94d2-43f8-a582-ce10a0f031dc"
  },
  "dest": {
    "index": "temp_abc_2ab99742-94d2-43f8-a582-ce10a0f031dc"
  }
}'

如果这个命令能成功,说明格式没问题,再放到脚本里批量执行。

内容的提问来源于stack exchange,提问作者Arpan Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:25:24