From ae10ab7bf68dfd3d954c3015f609a06adfe03695 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Fri, 14 Apr 2023 14:14:18 -0400 Subject: [PATCH] use single `$search` pipeline stage rather than separate `$match` --- search/index.js | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/search/index.js b/search/index.js index e61897a..95d0209 100644 --- a/search/index.js +++ b/search/index.js @@ -9,7 +9,8 @@ const contentSchema = new mongoose.Schema({ title: { type: String, required: true }, body: { type: String, required: true }, url: { type: String, required: true }, - version: { type: String } + version: { type: String }, + versionNumber: { type: Number } }); module.exports = async function search(context, req) { @@ -22,27 +23,24 @@ module.exports = async function search(context, req) { Content = conn.model('Content', contentSchema, 'Content'); const query = req.query.search.toString(); - const version = req.query.version; + const version = req.query.version ? +req.query.version.replace(/\.x$/, '') : null; let results = await Content.aggregate([ { $search: { index: 'mongoose-content', - text: { - query, - path: { wildcard: '*' }, - fuzzy: {} + compound: { + must: [ + ...(version ? [{ + equals: { + path: 'versionNumber', + value: version + } + }] : []), + { text: { query, path: { wildcard: '*' }, fuzzy: {} } } + ] } } }, - { $match: { version } }, - { - $addFields: { - score: { - $meta: 'searchScore' - } - } - }, - { $sort: { score: -1 } }, { $limit: 10 } ]);