如何在Node.js中迭代MongoDB数据库以将数据发送到Algolia?

4
在Algolia的文档中,他们针对node.js部分指定了使用MySQL进行索引而不是MongoDB。我有一个关于这个问题的更一般的问题,请点击查看
有些人让我使用mongo-connector,但我尝试后出现了一些未知错误,这让我回到了起点。
我的真正问题是,如何在mongodb中迭代集合列表以用于Algolia?
这是Algolia在Node.js中对MySQL的版本。
var _ = require('lodash');
var async = require('async');
var mysql = require('mysql');

var algoliasearch = require('algoliasearch');
var client = algoliasearch("RQGLD4LOQI", "••••••••••••••••••••••••••••••••");
var index = client.initIndex('YourIndexName');

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'mysql_user',
  password: 'mysql_password',
  database: 'YourDatabaseName'
});

connection.query('SELECT * FROM TABLE_TO_IMPORT', function(err, results, fields) {
  if (err) {
    throw err;
  }

  // let's use table IDS as Algolia objectIDs
  results = results.map(function(result) {
    result.objectID = result.id;
    return result;
  });

  // split our results into chunks of 5,000 objects, to get a good indexing/insert performance
  var chunkedResults = _.chunk(results, 5000);

  // for each chunk of 5,000 objects, save to algolia, in parallel. Call end() when finished
  // or if any save produces an error
  // https://github.com/caolan/async#eacharr-iterator-callback
  async.each(chunkedResults, index.saveObjects.bind(index), end);
});

function end(err) {
  if (err) {
    throw err;
  }

  console.log('MySQL<>Algolia import done')
};

具体来说,我正在使用mongoose作为我的ORM,因此在其他库方面没有经验。请帮助我解决这个问题,以便我可以拥有一个搜索接口 :(。

1个回答

4
你可以使用以下代码来遍历整个 MongoDB mydb.myCollection 集合并创建批次,这些批次将被发送到 Algolia 索引:
var Db = require('mongodb').Db,
    Server = require('mongodb').Server,
    algoliasearch = require('algoliasearch');

// init Algolia index
var client = algoliasearch("*********", "••••••••••••••••••••••••••••••••");
var index = client.initIndex('YourIndexName');

// init connection to MongoDB
var db = new Db('mydb', new Server('localhost', 27017));
db.open(function(err, db) {
  // get the collection
  db.collection('myCollection', function(err, collection) {
    // iterate over the whole collection using a cursor
    var batch = [];
    collection.find().forEach(function(doc) {
      batch.push(doc);
      if (batch.length > 10000) {
        // send documents by batch of 10000 to Algolia
        index.addObjects(batch);
        batch = [];
      }
    });
    // last batch
    if (batch.length > 0) {
      index.addObjects(batch);
    }
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接