Running with Ruby

Tag: Mongo (page 2 of 7)

Mongoid and Aggregation Framework: Get similar elements based on tags, ordered by total number of matches (similarity level)

So, lets say we want have an Article model with tags array:

class Article
  include Mongoid::Document
  include Mongoid::Timestamps

  field :content, type: String, default: ''
  field :tags, type: Array, default: []
end

Let’s try to pick any similar first (without similarity level)

We have an article, that has some tags (%w{ ruby rails mongoid mongodb }) and we would like to get similar articles. Nothing special (yet):

current_article = Article.first
similar = Article.in tags: current_article.tags

Let’s also pick elements without our base article (current_article) though we decided to get similar articles, not similar or equal:

Article
  .ne(_id: current_article.id)
  .in(tags: current_article.tags)

We could even refactor it a bit…

class Article
  include Mongoid::Document
  include Mongoid::Timestamps

  scope :exclude, -> article { ne(_id: article.id) }
  scope :similar_to, -> article { exclude(article).in(tags: article.tags ) }

  field :content, type: String, default: ''
  field :tags, type: Array, default: []

  def similar
    @similar ||= self.class.similar_to self
  end
end

# Example usage:
current_article.similar #=> [Article, Article]

Seems pretty decent, but this won’t give us most similar articles. It will just return most recent, that have equal at least one tag with our current_article. What should we do then?

Mongo Aggregation Framework to the rescue

To get such information, sorted in a proper way, we need to perform following steps:

  1. Don’t include current_article in resultset
  2. Get all articles (except current one), that have at least one tag as current_article (we did this earlier)
  3. Count how many similar tags occurred in each of articles
  4. Sort articles by similarity
  5. Take first 10 articles

Step 1 – Excluding

# Mongoid
Article.where(id: {"$ne" => current_article.id})
# Mongo (this is still in Ruby - not in Mongo shell!)
"$match" => { 
  _id: { "$ne" => current_article.id }
}

Step 2 – All articles with at least one similar tag

# Mongoid
Article.in(tags: current_article.tags )
# Mongo (this is still in Ruby - not in Mongo shell!)
"$match" => { 
  tags: { "$in" => %w{ ruby rails mongoid mongodb } }
}

Step 3 – Unwind by tags

If you’re not familiar with unwind look here. That way, we get article copy for every tag for each article.

{ "$unwind" => "$tags" }

Step 4 – Second matching

You may wonder, why we filter results again. Well The initial filtering was not required, but we did this to remove all non-related articles, so the data set is much smaller. Unfortunately unwind created document copy per each of the tags – even those that we don’t want to. That’s why we have to filter it again.

"$match" => { 
  tags: { "$in" => %w{ ruby rails mongoid mongodb } }
}

Note that we don’t need to filter out again by ID, since in incoming dataset we already don’t have the current_article document instance.

Step 5 – Grouping

Now we can group by documents ID. Also we will add sum for grouping, so we will know similarity level for each document. One point in sum equals one similar matching tag.

{ "$group" => {
    _id: "$_id", 
    matches: {"$sum" =>1}
  }
}

Step 6 – Sorting

Now we can sort by sum to have elements in descending order (most similar on top):

{ "$sort" => {matches:-1} }

Step 7 – 10 first elements

And the last step – limiting:

{ "$limit" => 10 }

Making it all work together

In order to execute this whole code in Ruby, we need to use Article.collection.aggregate method:

results = Article.collection.aggregate(
  {
    "$match" => { 
      tags: { 
        "$in" => current_article.tags 
      },
      _id: { 
        "$ne" => current_article.id 
      }
    },
  },  
  { 
    "$unwind" => "$tags" 
  },
  { 
    "$match" => { 
      tags: { 
        "$in" => current_article.tags 
      } 
    }
  },
  { 
    "$group" => {
      _id: "$_id", 
      matches: { "$sum" =>1 }
    }
  },
  { 
    "$sort" => { matches: -1 }  
  },
  { 
    "$limit" => 10 
  }
)

We won’t get Ruby objects as a result (we’ll get an array of hashes). We can process it further if we need similarity level, but if we just need similar articles (for example to display them) we can just:

Article.find results.map(&:first).map(&:last)

Learning Mongoid – Build scalable, efficient Rails web applications with Mongoid – Book review

First of all I will point one thing: I’m not a professional book reviewer. I don’t do this too often. Probably because I don’t have enough time. However, I’ve decided to do a review of “Learning Mongoid” because I wanted to learn something new and Packt Publishing was kind enough to lend me a copy for this review. So here it is. I’ll start with things that I really liked. As usual, there were some things that could be corrected, but if you have Rails experience, this book will be really helpful for you.

7501OS_Learning Mongoid

Things I did like about this book

It’s not extremely long

You may consider this an issue, but I’ve found this really helpful. Chapters aren’t long, so getting through them is not painful. I bet you’ve sometimes wondered “what is the author getting at?”. Not with this one. Chapters (and the book itself) are really consistent. You won’t get bored reading this one or feel like giving up.

A lot of examples

I don’t like theoretical texts and books, without any examples of good practices. We’re developers, we should be able to play around with new stuff that we learn! And one of the things that I really liked about Learning Mongoid is that I was able to copy-paste almost every example and play-around with it on my computer.

Field aliases

Even now I can recall times, where I had to rename fields, so I would be able to create an index for them :). I don’t know why, but this is not a thing that is covered in tutorials or other books (at least not in those that I know). On the other hand this is super useful. I was really surprised to see this one here. It made me realize one thing – this book was written by other guys who develop Rails-Mongoid software.

Geospatial searches and querying in general

When doing a lot of Geolocalization stuff – Mongo can be really helpful and can simplify a lot of things. All basic geo-search options are covered in this book. In general, the whole querying chapter is well-written and together with aggregation framework, it covers all common cases that you may want to use.

Performance tuning and maintenance

Performance is really important. If you don’t do it right, you might end up with really slow application. This book covers the basics of both – performance tuning and Mongoid maintenance, so after reading it you will be able to use some of Mongo and Mongoid properties to gain few seconds of users life ;)

Things I didn’t like about this book

A good book – but not sure whether or not for pros or beginners

Learning Mongoid by Packt Publishing is a solid book about Mongoid, although it lacks some information that would be super useful for beginners. I’ve got a feeling that it covers most of “stuff you need to know to start working with Mongo and Mongoid”, but as mentioned above, when it comes to people who want to start using Mongoid and they know only a bit about Ruby – it can be harsh.

Install RVM – but do this on your own

I know that this book should be (and it is!) about Mongoid, but since we’re talking about it, it is worth at least mentioning how to install RVM, especially because it is one of the prerequisites. 1-2 pages about RVM would be really helpful.

Need some config hints? Well not this time

The second thing that is lacking is a Mongoid setup instruction. Not even a word on what should/should not be in mongoid.yml, what are the most important options, etc. There is even mention of it in the book:

There are entirely new options in mongoid.yml for database configuration

Although none of the changes are listed. No information about replica_set, allow_dynamic_fields, preload_models or any other important setup options. This is a must be in any good Mongoid book.

Want to upgrade to most recent Mongoid version? We won’t help you out :(

I’ve mentioned that below, but I will point it out again. Authors say, that there are several differences between new and old Mongoid, although they don’t list them (except IdentityMap). I think they should.

Want to migrate your app to Mongoid?

Maybe you want to move your app from ActiveRecord to Mongoid (I did it few times myself)? If so, “Learning Mongoid” will help you handle Mongo part, but it won’t help you with the migration process itself. Sodibee (example book app) is a Mongoid base app. Maybe authors assumed, that if you master ActiveRecord and Mongoid, you don’t need any extra help to switch between them…

Summary

Would I recommend this book? Yes – I already have! It can be a solid Mongo and Mongoid starting point for begginers (apart some issues that I’ve mentioned) and a “knowledge refresher” for people that use Mongoid longer that few weeks. It is well written and it has a lot of examples. Really a good one about Mongoid.

If you’re interested in buying this book, you can get it here.

Olderposts Newerposts

Copyright © 2017 Running with Ruby

Theme by Anders NorenUp ↑