Skip to content

Commit 378f7e2

Browse files
committed
use atlas search instead of text search for docs search
1 parent 801ded9 commit 378f7e2

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

search/index.js

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ const contentSchema = new mongoose.Schema({
1111
url: { type: String, required: true },
1212
version: { type: String }
1313
});
14-
contentSchema.index({ title: 'text', body: 'text' });
1514

1615
module.exports = async function search(context, req) {
1716
let Content;
@@ -22,16 +21,30 @@ module.exports = async function search(context, req) {
2221

2322
Content = conn.model('Content', contentSchema, 'Content');
2423

25-
const $search = req.query.search.toString();
24+
const query = req.query.search.toString();
2625
const version = req.query.version;
27-
const filter = { $text: { $search } };
28-
if (version) {
29-
filter.version = version;
30-
}
31-
let results = await Content.
32-
find(filter, { score: { $meta: 'textScore' } }).
33-
sort({ score: { $meta: 'textScore' } }).
34-
limit(10);
26+
let results = await Content.aggregate([
27+
{
28+
$search: {
29+
index: 'mongoose-content',
30+
text: {
31+
query,
32+
path: { wildcard: '*' },
33+
fuzzy: {}
34+
}
35+
}
36+
},
37+
{ $match: { version } },
38+
{
39+
$addFields: {
40+
score: {
41+
$meta: 'searchScore'
42+
}
43+
}
44+
},
45+
{ $sort: { score: -1 } },
46+
{ $limit: 10 }
47+
]);
3548

3649
results = results.map(doc => {
3750
const $ = cheerio.load(doc.body);

0 commit comments

Comments
 (0)