4

在 Algolia 的文档中,对于他们指定使用 MySQL 而不是 MongoDB 进行索引的 node.js 部分,我对这个问题还有另一个问题,但这是一个更普遍的问题,请查看此处

有些人要求我使用mongo-connector但尝试了它,但我遇到了一些未知错误,这让我解决了问题

我真正的问题是,我如何将 mongodb 中的集合列表迭代到 algolia?

这是 Node.js 中 Algolia 的 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')
};

具体来说,我使用猫鼬作为我的 ORM,所以我在其他库中没有经验。请帮助我,这样我就可以找到一些搜索界面了:(。

4

1 回答 1

9

您可以使用以下代码迭代整个 MongoDBmydb.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);
    }
  });
});
于 2015-10-17T08:36:07.043 回答