Full text search using Mongoid - ruby

Is there a way to use MongoDB (v 2.4)'s full text search feature via Mongoid? I tried the answer from google group link but kept on getting the following error.
In one tab, I started mongod as such: ~$ mongod --setParameter textSearchEnabled=true
The line that caused the error:
Article.mongo_session.command({:text => {:search => 'Ruby'}})
It would be great if someone could point out a way to execute MongoDB runCommand within Ruby, so that I could directly run the command db.collection.runCommand( "text", { search: <string> })
failed with error 13111: "exception: wrong type for field (text) 3 != 2"
See https://github.com/mongodb/mongo/blob/master/docs/errors.md
for details about this error.

For anyone finding this, Mongoid 4.0 allows for full text search like this:
Model.text_search('query')
You can chain as you normally would:
Listings.in(category: sections).where(listing_type: 'Website').text_search(params[:q]).to_a
Indexes are pretty easy as well:
index({name: "text", description: "text"}, {weights: {name: 10, description: 2}, name: "TextIndex"})
EDIT: July 2017
As reported below, text_search is deprecated. I've been using where() like this:
Model.where('$text' => { '$search' => "\"#{params[:q]}\"" })

I've just tried mongo 2.4 text search via mongoid and bumped into the same issue as you. I've played a little bit with it and found the following solution. Here is how I've made it working
Example:
User.mongo_session.command(text: 'users', search: 'search string')
Here 'text' key should point to the collection name.
You will get Moped::BSON::Document that have information about found documents.
Hope it will help you as well

Based on Durran Jordan answer on a question about 'Mongo 2.4 full text search with Moped?' in this link: https://groups.google.com/forum/?fromgroups=#!topic/mongoid/hJRbaNMy6w4, I will suggest you change your command from:
Article.mongo_session.command({:text => {:search => 'Ruby'}})
to this:
Article.with(database: "text").mongo_session.command({:text => {:search => 'Ruby'}})

For me this one worked.
Here
Favorite.mongo_session.command(:text =>'table_name', search: 'search parameter')
Make sure the :text 's value is the table name and not the field.

Related

Pre-filtering in a Kendo grid

I am trying to pre-filter a kendo grid, and I have a problem.
For pre-sorting and pre-grouping I am using first 2 lines, that work great:
grid.DataSource(ds =>
{
var ajaxDsBuilder = ds.Ajax();
// ...
ajaxDsBuilder.Sort(sort => sort.Add(col.Name).Ascending());
ajaxDsBuilder.Group(grp => grp.Add(col.Name, typeof(string)));
// problem at the next line with filter
ajaxDsBuilder.Filter(f=> f.Add(c=>col.Name.ToString()).IsEqualTo("something"));
which is giving me a server error after running.
For pre-filtering I found this :
.Filter(filter => filter.Add(/* your filter rule */))
If I remove the ToString() I get the error: Property with specified name: col.Name cannot be found on type: System.Data.DataRowView
If I try:
ajaxDsBuilder.Filter(f=> f.Add(c=> c.col.Name).IsEqualTo("something"));
I get the error:
An expression tree may not contain a dynamic operation
I have also tried to use dynamic lambda but the same problems appear ...
What am I missing?
P.S. I am new to all this, so any help will be highly appreciated.
I answered the same question on Telerik forum and I got my answer:
.Filter(filter => filter.AddRange(new [] {
new Kendo.Mvc.FilterDescriptor(col.Name, Kendo.Mvc.FilterOperator.IsEqualTo, "TEST") })
In case someone needs this :)

Mongodb update document through ruby not working

I want to update documents in MongoDB via Ruby code. I have document ids of documents I want to update only a specific field. I tried the following code.
collection.update({"_id".to_s => doc_id},{"$set"=> {"selected" => "false"}})
and also
collection.update({"_id".to_s => doc_id},{"selected" => "false"})
Both commands execute without any error but the database remains unaffected.
According to the documentation, the way to update a document are
collection.update({"_id" => id}, doc)
or
collection.update({"_id" => id}, {"$set" => {"name" => "MongoDB Ruby"}})
The ID is expected to be a valid id. I'm not sure if a string is accepted, in case make sure to convert it to a BSON::ObjectId.
collection.update({"_id" => BSON::ObjectId.from_string(doc_id) }, {"$set" => {"selected" => "false" }})
Make sure to check the command returns true.
Also note that if you are using a driver version < 1.8, you should be using :safe => true.
The driver will send a getlasterror command after every write to ensure that the write succeeded by default. Prior to version 1.8 of the driver, writes were not acknowledged by default and it was necessary to explicitly specify the option ':safe => true' for write confirmation. This is no longer the case.

How to use Tire for "MoreLikeThis" query of ElasticSearch

I would like execute this exemple :
$ curl -XGET 'http://localhost:9200/twitter/tweet/1/_mlt?mlt_fields=tag,content&min_doc_freq=1'
with Tire gem. It's poossible ?
My goal to search document related to another document.
It is not implemented directly in tire. Karmi, however, has implemented it as a tire extension in the tire-contrib repository.
Source Code: more_like_this.rb
Add by adding gem 'tire-contrib'
more_like_this_field(:tag, like_text, options = {min_doc_freq: 1})
Okay the internet forgot to include a single example of this call (including the source project), so here is one style of it.
related_articles = Article.search {
query {
more_like_this("#{current_article.title} #{current_article.body}",
fields: [:title, :description],
percent_terms_to_match: 0.1,
min_term_freq: 1,
min_doc_freq: 1
)
}
}
puts related_articles.results.count
puts related_articles.results.first.title if related_articles.present?
The gotcha here are the min_term_freq and min_doc_freq params above. They default to 2 and 5 respectively in ElasticSearch, which makes it easy to get confused while testing this.

Mongodb simple update does not work in Ruby/Mongoid

I have the following MongoDB update operation, but it doesnt seem to work, anyone know why?
User.collection.update({ _id: BSON::ObjectId("5018ed448712ff240e0000a0") },
{ "$set" => { name: "ben" } })
It does not throw an error, but just some integer which I am guessing is the doc size.
I am using Mongoid 2.4.10/Rails 3.2.7
If you are using Mongoid, you coule just do a find and update:
User.find("5018ed448712ff240e0000a0").update_attributes!(name: "ben")
or you could use set:
User.find("5018ed448712ff240e0000a0").set(:name, "ben")
Note that set() takes 2 arguments; it does not accept a hash as an argument
Can you use mongoid API instead and use following command:
User.find("5018ed448712ff240e0000a0").set(name: "ben")

Find documents including element in Array field with mongomapper?

I am new to mongodb/mongomapper and can't find an answer to this.
I have a mongomapper class with the following fields
key :author_id, Integer
key :partecipant_ids, Array
Let's say I have a "record" with the following attributes:
{ :author_id => 10, :partecipant_ids => [10,15,201] }
I want to retrieve all the objects where the partecipant with id 15 is involved.
I did not find any mention in the documentation.
The strange thing is that previously I was doing this query
MessageThread.where :partecipant_ids => [15]
which worked, but after (maybe) some change in the gem/mongodb version it stopped working.
Unfortunately I don't know which version of mongodb and mongomapper I was using before.
In the current versions of MongoMapper, this will work:
MessageThread.where(:partecipant_ids => 15)
And this should work as well...
MessageThread.where(:partecipant_ids => [15])
...because plucky autoexpands that to:
MessageThread.where(:partecipant_ids => { :$in => [15] })
(see https://github.com/jnunemaker/plucky/blob/master/lib/plucky/criteria_hash.rb#L121)
I'd say take a look at your data and try out queries in the Mongo console to make sure you have a working query. MongoDB queries translate directly to MM queries except for the above (and a few other minor) caveats. See http://www.mongodb.org/display/DOCS/Querying

Resources