Text search not working with MongoDB 3.0.0 #358
Comments
Didnt know that 3.0 didnt accept text search anymore. |
Currently this works: module Origin
module Optional
def with_fields(fields_def = {})
fields_def ||= {}
fields_def.merge!({_id: 1})
option(fields_def) do |options|
options.store(:fields,
fields_def.inject(options[:fields] || {}) do |sub, field_def|
key, val = field_def
sub.tap { sub[key] = val }
end
)
end
end
def include_text_search_score
with_fields({score: {"$meta" => "textScore"}})
end
def sort_by_text_search_score
option({}) do |options, query|
add_sort_option(options, :score, {"$meta" => "textScore"})
end
end
end
end and using it like this: Model.where({"$text" => {"$search" => query}}).
include_text_search_score.
sort_by_text_search_score.
only(:name, :alternate_names, :coordinates). # you have to manually specify the fields because of including the score field
limit(10) |
Thanks for sharing @glampr! Definitely helps ... seems like there is no official way of doing this. |
When upgrading to mongoid >= 5 which doesn't use moped, you can use directly the ruby driver (>= 2.1) like this: Model.collection.
find({"$text" => {"$search" => query}}).
projection(field1: 1, field2: 1, field3: 1, score: {"$meta" => "textScore"}).
sort({score: {"$meta" => "textScore"}}).
limit(some_limit).
entries.
map { |g| Model.new(g) } # optional if you want objects and not hashes |
Beautiful, thanks @glampr 👍 |
Can anyone tell me how I can add text index in mongoid model?
|
hi @glampr, I have used your suggestion. But I am getting below error.
I have also put the below code for above with no luck.
How I reindex the existing data? Thanks :) |
@lalit-nga just adding the index statements in your model does not add the text index to the database. you also need to run |
Is @glampr answer still the best way to handle this? Running with success: def self.search query, limit=0
Location.collection.
find({"$text" => {"$search" => query}}).
projection(score: {"$meta" => "textScore"}).
sort({score: {"$meta" => "textScore"}}).
limit(limit).
entries.
map { |e| Location.new(e) }
end Just kind of wish I can chain |
On a side note, beware of both |
I get the following error when upgraded to MongoDB 3.0.0 :
This is the command I was using that was working in MongoDB 2.6
Tested against moped 2.0.4
The text was updated successfully, but these errors were encountered: