const { Client } = require('@elastic/elasticsearch');
const { MongoClient } = require('mongodb');
const host = process.env.AWS_OPENSEARCH_HOST;
const esClient = new Client({ node: `https://${host}:443` });
const mongoUrl = process.env.MONGO_URL;
const client = await MongoClient.connect(mongoUrl, { useNewUrlParser: true });
const collection = client.db("mydb").collection("mycollection");
const records = await collection.find().limit(10000).toArray();
const bulk = [];
records.forEach((r) => {
bulk.push({ index: { _index: 'myindex', _id: r._id } });
bulk.push(r);
});
await esClient.bulk({
refresh: true,
body: bulk,
});
await client.close();
以上代码使用Elasticsearch Node.js客户端和MongoDB Node.js驱动程序来连接MongoDB和OpenSearch。它将MongoDB的数据批量导入到OpenSearch中。要运行此示例代码,请分别将AWS_OPENSEARCH_HOST和MONGO_URL替换为适当的值。