背景
需要将 elasticsearch 数据导出至 JSON(或 csv)
步骤
前置依赖:需要 Node.js 环境(npm)
# 安装
$ npm install -g elasticdump
查看帮助
# 详情见:https://github.com/elasticsearch-dump/elasticsearch-dump
$ elasticdump --help
脚本示例
# 编写导出脚本
$ vim run.sh
#!/bin/sh
# 查询语句
searchbody=`cat << EOF
{
"query": {
"bool": {
"must": [
{
"term": {
"goods.category": 20
}
},
{
"range": {
"@timestamp": {
"gte": 1679414400000,
"lt": 1679500800000,
"format":"epoch_millis"
}
}
}
]
}
}
}
EOF`
index=goods-2023.03.23
endpoint="http://username:[email protected]:9200/goods-2023.03.23"
outputpath=es-data/2023-03-23.json
# --input 指定来源
# --output 导出的路径(如果以 csv 结尾,则会自动保存为 csv 格式)
# --quiet 不输出任何日志信息
# --scrollTime 用来指定每次滚动查询的时间间隔(当我们需要从 elasticsearch 中检索大量数据时,通常需要使用滚动查询来避免一次性检索过多数据导致内存溢出或性能下降的问题)
# --limit 指定每次滚动查询的文档数量
# --noRefresh 禁用索引的自动刷新功能(当需要执行大量索引操作时,如果每次操作都会自动刷新索引,将导致性能下降)
# --maxRows 指定每次滚动查询的最大文档数量
# --concurrency 并发执行的数量
# --transform 对结果进行转换(如提取特定字段、转换数据格式等)
# --searchBody 查询语句
elasticdump --input="$endpoint/$index" \
--output=$outputpath \
--quiet --scrollTime=30m --limit=10000 --noRefresh --maxRows=1000000 \
--concurrency=2 \
--transform @transform.js \
--searchBody "$searchbody"
# 结果转换脚本
$ vim transform.js
module.exports = function (doc, options = {
}) {
var item = doc._source.goods
var timestamp = new Date(doc._source["@timestamp"]).valueOf()
for (var k in doc) {
delete doc[k]
}
for (var k in item) {
doc[k] = item[k]
}
doc.timestamp = timestamp
}
# 运行导出脚本即导出数据
$ sh run.sh
参考
- https://github.com/elasticsearch-dump/elasticsearch-dump
- https://help.aliyun.com/document_detail/461655.htm
- https://www.cnblogs.com/resn/p/9082663.html