使用 Node.js Elasticsearch 客户端索引大型 CSV 文件

作者:来自 Elastic joshmock

使用 bulk API 可以轻松地将大量文档索引到 Elasticsearch:将你的数据记录转换为 JSON 文档,并插入指示它们应该添加到哪个索引的指令,然后将这个大的换行分隔 JSON blob 作为请求体,通过单个 HTTP 请求发送到 Elasticsearch 集群。或者,使用 Node.js 客户端的 bulk 函数。

更多阅读:Elasticsearch:使用最新的 Nodejs client 8.x 来创建索引并搜索

下面演示如何读取 CSV 文件,将其行转换为 JSON 对象,并进行索引:

php 复制代码
`

1.  import { Client } from '@elastic/elasticsearch'
2.  import { parse } from "csv-parse/sync"
3.  import { readFileSync } from 'node:fs'

5.  const csv = parse(readFileSync('data.csv', 'utf8'), { columns: true })
6.  const operations = csv.flatMap(row => [
7.    { index: { _index: "my_index" } },
8.    row
9.  ])

11.  const client = new Client({ node: 'http://localhost:9200' })
12.  await client.bulk({ operations })

`AI写代码![](https://csdnimg.cn/release/blogv2/dist/pc/img/runCode/icon-arrowwhite.png)

但是,如果你需要发送的数据量超过 Elasticsearch 单次请求能接收的大小,或者你的 CSV 文件太大,无法一次性全部加载到内存中,该怎么办?这时可以使用 bulk helper

虽然 bulk API 本身已经很简单,但对于更复杂的场景,helper 提供了对流式输入的支持,可以将大型数据集拆分为多个请求等。

例如,如果你的 Elasticsearch 服务器只能接收小于 10MB 的 HTTP 请求,你可以通过设置 flushBytes 值来指示 bulk helper 拆分数据。每当请求即将超过设置值时,就会发送一次 bulk 请求:

php 复制代码
`

1.  const csv = parse(readFileSync('data.csv', 'utf8'), { columns: true })
2.  await client.helpers.bulk({
3.    datasource: csv,
4.    onDocument(doc) {
5.      return { index: { _index: "my_index" } }
6.    },
7.    // send a bulk request for every 9.5MB
8.    flushBytes: 9500000
9.  })

`AI写代码

或者,如果你的 CSV 文件太大无法一次性加载到内存中,helper 可以将作为数据源,而不是使用数组:

php 复制代码
`

1.  import { createReadStream } from 'node:fs'
2.  import { parse } from 'csv-parse'

4.  const parser = parse({ columns: true })
5.  await client.helpers.bulk({
6.    datasource: createReadStream('data.csv').pipe(parser),
7.    onDocument(doc) {
8.      return { index: { _index: "my_index" } }
9.    }
10.  })

`AI写代码![](https://csdnimg.cn/release/blogv2/dist/pc/img/runCode/icon-arrowwhite.png)

这会将 CSV 文件中的行缓冲到内存中,解析为 JSON 对象,并让 helper 将结果刷新为一个或多个 HTTP 请求发送出去。这个解决方案不仅节省内存,而且阅读起来也和将整个文件加载到内存中的方法一样简单!

原文:discuss.elastic.co/t/dec-9th-2...

相关推荐
要记得喝水4 分钟前
适用于 Git Bash 的脚本,批量提交和推送多个仓库的修改
git·elasticsearch·bash
二十七剑16 分钟前
Elasticsearch的索引问题
大数据·elasticsearch·搜索引擎
A__tao9 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
A__tao11 小时前
Elasticsearch Mapping 一键生成 Proto 文件(支持嵌套 + 注释过滤)
大数据·elasticsearch·jenkins
Devin~Y11 小时前
高并发电商与AI智能客服场景下的Java面试实战:从Spring Boot到RAG与向量数据库落地
java·spring boot·redis·elasticsearch·spring cloud·kafka·rag
Elastic 中国社区官方博客14 小时前
使用 Jina-VLM 小型多语言视觉语言模型来和图片对话
大数据·人工智能·elasticsearch·语言模型·自然语言处理·jina
LDG_AGI14 小时前
【搜索引擎】Elasticsearch(二):基于function_score的搜索排序
数据库·人工智能·深度学习·elasticsearch·机器学习·搜索引擎·推荐算法
历程里程碑16 小时前
Protobuf总结
大数据·数据结构·elasticsearch·链表·搜索引擎
ACGkaka_16 小时前
ES 学习(七)性能陷阱
大数据·学习·elasticsearch
LDG_AGI17 小时前
【搜索引擎】Elasticsearch(三):基于script_score的自定义搜索排序
大数据·人工智能·深度学习·elasticsearch·机器学习·搜索引擎·推荐算法