Full text search

19 views
Skip to first unread message

John Croucher

unread,
Apr 2, 2017, 8:05:44 AM4/2/17
to MongoMapper
I posted this on stack exchange before finding this group.

Using this command directly on the database I get the results I am after

db.products.find({$text: {$search: "some product"}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})

But using it in MongoMapper I am getting errors. The search without the score field doesn't produce any errors

@products = Product.where(
    '$text' => {'$search' => @search_string}
)

However, when I try to add the sort field is where I get issues

@products = Product.where(
    '$text' => {'$search' => @search_string}, :score => {'$meta' => "textScore"}
)

Mongo::OperationFailure at /search unknown operator: $meta

It also fails using the raw query method

@products = MongoMapper.database['products'].find(
    '$text' => {'$search' => @search_string}, :score => {'$meta' => "textScore"}
)

The full query I am trying to run is

 @products = Product.where(
    '$text' => {'$search' => @search_string},:score => {'$meta' => "textScore"}
).sort(:score => {'$meta' => "textScore"}).limit(5)

This gives the error

Mongo::OperationFailure at /search must have $meta projection for all $meta sort keys

Does anyone have suggestions of where I am going wrong? I assume I am using it wrong.



Jamie Orchard-Hays

unread,
Apr 2, 2017, 10:39:28 AM4/2/17
to mongo...@googlegroups.com
Notice that on your example for mongo shell, score is used in the second document object, not the first. This indicates it’s part of the fields clause—those fields you wish to include or exclude from the results.

MongoMapper can use Plucky (included) to build where and fields clauses (as well as a sort clause). See if something like this works:

@products = Product.where(
    '$text' => {'$search' => @search_string}).fields(:score => {'$meta' => "textScore"}
)
For the Ruby Mongodb driver, you also separate the query doc from the options doc:

Collection.find({<query}, {<options})

You’re not doing that in your example. You have the score included in the query.


--
You received this message because you are subscribed to the Google
Groups "MongoMapper" group.
For more options, visit this group at
http://groups.google.com/group/mongomapper?hl=en?hl=en
---
You received this message because you are subscribed to the Google Groups "MongoMapper" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongomapper...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

John Croucher

unread,
Apr 2, 2017, 7:38:16 PM4/2/17
to MongoMapper
That example works perfectly. 
Thank you for the explanation, I see where I was going wrong. 
Reply all
Reply to author
Forward
0 new messages