Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I reindex all posts in Searchkick / Elasticsearch?

Arthur Truong asked in Rails

Hey, I discovered a problem with Rails app. When I run rails db:seed, I generate 10 posts and store them in the database. I also have an API where I pull data as JSON, which gets parsed and data is basically stored in the DB as a post. I run Post.reindex on both of them, however, despite reindexing, the seed.rb generated posts don't show up in the correct order and are always shown first instead of chronological order with the API-derived posts. How do I fix this?

In my posts_controller.rb, I sort the posts by created_at:
@posts = Post.search(query, page: params[:page], per_page: 10, order: { created_at: :asc })

My Rake Task:

namespace :api do
  desc "get jobs from job aggregator api"
  task get_posts: :environment do

      url = *url here*
      req = Net::HTTP::Get.new(url.to_s)
      res = Net::HTTP.start(url.host, url.port) {|http|
        http.request(req)
      }
      response = JSON.parse(res.body)

      Post.where(api: true).delete_all

      response.each do |post| 
        Post.create! do |f|
          f.company = post["company"]
          f.company_logo = post["company_logo"]
          f.description = post["description"]
          f.how_to_apply = post["how_to_apply"]
          f.title = post["title"]
          f.url = post["url"]
          f.api_created_at = post["created_at"]
          f.api = true
          f.user_id = 1 #user is required
          f.published_at = Time.parse(post["created_at"])
        end
      end
      Post.reindex
      p "#{response.count} posts pulled"
  end

end

And my seeds.rb file:

if Rails.env.development? 
  require 'faker'

  @post = Post.create(
    :company => "Tesla", 
    :title => "Tesla Web Engineer Required Immediately!", 
    :url => "http://www.tesla.com", 
    :content => "<div>This is a demo post</div>", 
    :tag_list => "react, node, expressjs",
    :user_id => 1,
    :published_at => DateTime.now.utc,
    :paymentstatus => true
  )

  @post.save!

  20.times do 
    @post2 = Post.create(
      :company => Faker::Company.name, 
      :title => Faker::Job.title, 
      :url => Faker::Company.logo, 
      :content => Faker::Quotes::Shakespeare.hamlet_quote, 
      :tag_list => "#{Faker::Job.field}, #{Faker::Job.field}, node, expressjs",
      :user_id => 1,
      :published_at => DateTime.now.utc,
      :paymentstatus => true

    )

    @post2.save!
  end

  p "done!"
end

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.