首页 > 解决方案 > mongo db 在使用数字进行文本搜索时性能不佳

问题描述

我有一个名为“torrent”的集合,其中包含大约 320 万个文档。它基本上包含公共洪流元数据。

架构:

let mongoose = require('mongoose');

let TorrentSchema = mongoose.Schema({
  infohash: {type: String, index: true, unique: true},
  title: {type: String, index: true},
  category: {type: String, default: "Unknown", index: true},
  size: {type: Number, default: 0},
  trackers: [{
    downloads: {type: Number},
    peers: {type: Number},
    seeds: {type: Number},
    tracker: {type: String}
  }],
  files: [{path: String, length: Number}],
  swarm: {
    seeders: {type: Number, default: 0, index: -1},
    leechers: {type: Number, default: 0}
  },
  imported: {type: Date, default: Date.now, index: true},
  lastmod: {type: Date, default: Date.now, index: true}
});

TorrentSchema.virtual('getFiles').set(function () {
  return this.map(res => {
    if (typeof res === "string") return [{path: res, length: 0}];
    return res;
  })
});

TorrentSchema.virtual('downloads').get(function () {
  let downloads = 0;
  for (let download of this.trackers) {
    downloads += download.downloads
  }
  return downloads;
});

TorrentSchema.index({title: 'text'}, { language_override: 'none' });
module.exports = mongoose.model('Torrent', TorrentSchema);

现在问题是当我使用关键字进行文本搜索时,该关键字还包含编号,搜索查询需要很长时间才能执行。

  let q = req.query.q;
  q = q.split(/[\s]/).filter(n => n).map( str => `"${str}"`).join(" ");
  let PERPAGE = 20;
  let query = {$text: {$search: q}};
  // Tottent Is the same schema as above.
  let search = await Torrent.find(query).sort({"swarm.seeders" : -1}).select("-files").limit(PERPAGE).skip(skip);

现在的问题是。当使用“ubuntu”之类的字母进行搜索时,它的速度非常快。但是在使用也包含数字的字符串进行搜索时会出现问题。像“ubuntu 18”一样,没有数字的字符串,比如“ubuntu iso”,几乎没有时间。搜索“somevideo 1080p”、“somemovie 2”等其他关键字时也会发生同样的事情。

你有解决这个问题的办法吗?

标签: node.jsmongodbmongoose

解决方案


看起来,在用相同的关键字查询几次后,查询速度似乎显着提高。


推荐阅读