Elasticsearch is just an amazing search engine with a lot of flexibility.
You can think, that working with this tool is very hard, but actually, it is not.
Today I will show you, how to use Elasticsearch through the Searchkick gem.
At first, we need to install elasticsearch on our local development.
We can use a brew command.
brew install elasticsearch
Installation should be very easy - just follow the instructions.
When you are ready, just add searchkick gem to your Gemfile.
gem "searchkick"
Then of course update your gem list with bundler:
bundle install
And you should be ready to go by now. :)
To work with searchkick, we need to create a search index for the model, we want to search in.
We should add searchkick call inside this model:
# frozen_string_literal: true
class Blog < ApplicationRecord
searchkick
end
Then we can go into rails console and type:
Blog.reindex
This will take all your Blog posts and send them to the elasticsearch in a nice format to read for this engine.
Now, when you type:
Blog.search("sql")
It will return all the blogs that include SQL inside any column. The result can be kind of awkward though. It turns, that
this simple command will just return some Searchkick::Results object.
If you want to receive pure data, you have found, you can convert the result into an array.
Blog.serach("sql").to_a
This will return an array of objects:
[#<Blog id: 1, title: "Test1", content: "Opis 1", created_at: "2020-12-31 16:43:03", updated_at: "2021-05-17 20:15:06", blog_category_id: 1, views: 0, slug: "test1", state: "published">,
#<Blog id: 2, title: "Test2", content: "Opis 2", created_at: "2020-12-31 17:00:31", updated_at: "2021-05-17 20:15:06", blog_category_id: 1, views: 0, slug: "test2", state: "published">,
#<Blog id: 3, title: "Test3", content: "Opis 3", created_at: "2020-12-31 17:01:16", updated_at: "2021-05-17 20:15:06", blog_category_id: 1, views: 0, slug: "test3", state: "published">,
#<Blog id: 4, title: "Test4", content: "Opis 4", created_at: "2020-12-31 17:02:17", updated_at: "2021-05-17 20:15:06", blog_category_id: 1, views: 0, slug: "test4", state: "published">]
And that's all! If you want to know more about this gem, you can just visit its github page with the full documentation.