Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full text search filter on text score

Tags:

mongodb

I have the following find query that retrieves results ordered by textScore, but how can I apply criteria to only return documents that have text score of greater than 1?

db.foods.find(
   { $text: { $search: "red blue green" } },
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
like image 742
Mook5ter Avatar asked Mar 24 '15 14:03

Mook5ter


Video Answer


1 Answers

Use the aggregation framework to get the documents that have a text score of greater than 1 by doing a $match pipeline operation which will match on either the term "red" or "blue" or "green", followed by a $project operator pipeline which projects the score fields, and then do another $match pipeline operattion to returns only those documents with a score greater than 1.0. The "textScore" metadata is available for projections, sorts, and conditions subsequent the $match stage that includes the $text operation:

db.foods.aggregate([
    { 
        "$match": { 
               "$text": { 
                     "$search": "red blue green" 
                } 
         } 
    },
    { 
         "$project": { 
               "_id": 0, 
               "score": { 
                     "$meta": "textScore" 
                } 
          } 
     },
     { 
          "$match": { 
                "score": { "$gt": 1.0 } 
           } 
     }
])
like image 101
chridam Avatar answered Oct 04 '22 02:10

chridam