11import bencode from "bencode" ;
22import crypto from "crypto" ;
33import mongoose from "mongoose" ;
4- import { createNGrams } from "mongoose-fuzzy-searching/helpers" ;
4+ import { createNGrams , nGrams } from "mongoose-fuzzy-searching/helpers" ;
55import slugify from "slugify" ;
66import Torrent from "../schema/torrent" ;
77import User from "../schema/user" ;
@@ -463,7 +463,23 @@ export const getTorrentsPage = async ({
463463 userId,
464464 tracker,
465465} ) => {
466+ const queryNGrams = nGrams ( query , false , 2 , false ) . join ( " " ) ;
467+
466468 const torrents = await Torrent . aggregate ( [
469+ ...( query
470+ ? [
471+ {
472+ $match : {
473+ $text : {
474+ $search : queryNGrams ,
475+ } ,
476+ } ,
477+ } ,
478+ {
479+ $addFields : { confidenceScore : { $meta : "textScore" } } ,
480+ } ,
481+ ]
482+ : [ ] ) ,
467483 {
468484 $project : {
469485 infoHash : 1 ,
@@ -476,6 +492,7 @@ export const getTorrentsPage = async ({
476492 created : 1 ,
477493 freeleech : 1 ,
478494 tags : 1 ,
495+ confidenceScore : 1 ,
479496 } ,
480497 } ,
481498 ...( Array . isArray ( ids )
@@ -485,18 +502,6 @@ export const getTorrentsPage = async ({
485502 } ,
486503 ]
487504 : [ ] ) ,
488- ...( query
489- ? [
490- {
491- $match : {
492- $or : [
493- { name : { $regex : query , $options : "i" } } ,
494- { description : { $regex : query , $options : "i" } } ,
495- ] ,
496- } ,
497- } ,
498- ]
499- : [ ] ) ,
500505 ...( category
501506 ? [
502507 {
@@ -534,7 +539,9 @@ export const getTorrentsPage = async ({
534539 ]
535540 : [ ] ) ,
536541 {
537- $sort : { created : - 1 } ,
542+ $sort : query
543+ ? { confidenceScore : { $meta : "textScore" } }
544+ : { created : - 1 } ,
538545 } ,
539546 {
540547 $skip : skip ,
@@ -592,23 +599,24 @@ export const getTorrentsPage = async ({
592599 { $unwind : { path : "$fetchedBy" , preserveNullAndEmptyArrays : true } } ,
593600 ] ) ;
594601
602+ console . log ( torrents ) ;
603+
595604 const [ count ] = await Torrent . aggregate ( [
596- ...( Array . isArray ( ids )
605+ ...( query
597606 ? [
598607 {
599- $match : { expr : { $in : [ "$_id" , ids ] } } ,
608+ $match : {
609+ $text : {
610+ $search : queryNGrams ,
611+ } ,
612+ } ,
600613 } ,
601614 ]
602615 : [ ] ) ,
603- ...( query
616+ ...( Array . isArray ( ids )
604617 ? [
605618 {
606- $match : {
607- $or : [
608- { name : { $regex : query , $options : "i" } } ,
609- { description : { $regex : query , $options : "i" } } ,
610- ] ,
611- } ,
619+ $match : { expr : { $in : [ "$_id" , ids ] } } ,
612620 } ,
613621 ]
614622 : [ ] ) ,
0 commit comments