繁体   English   中英

如何在Rails中使用Elasticsearch

[英]How to use elasticsearch in rails

我是弹性搜索的新手。 我在系统中安装了弹性搜索。 在localhost:9200处显示

{
  "ok" : true,
  "status" : 200,
  "name" : "Unseen",
  "version" : {
    "number" : "0.90.10",
    "build_hash" : "0a5781f44876e8d1c30b6360628d59cb2a7a2bbb",
    "build_timestamp" : "2014-01-10T10:18:37Z",
    "build_snapshot" : false,
    "lucene_version" : "4.6"
  },
  "tagline" : "You Know, for Search"
}

我在宝石文件中包含了这两个宝石。

gem 'tire'
gem 'elasticsearch'

我有一个电影模型和一个名为search_controller的控制器。

movie.rb

class Movie < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks
mapping do
    indexes :title
end
def self.search(params)
        binding.pry
        tire.search(load: true, page: 1, per_page: 10) do
        query { string params[:query]} if params[:query].present?
     end

迁移电影模型

class CreateMovies < ActiveRecord::Migration
  def self.up
    create_table :movies do |t|
        t.string :title
      t.timestamps
    end
    def self.down
        drop_table movies
    end
  end
end

search_controller

class SearchController < ApplicationController
  def index
    if(params[:query]).present?
    @results=Movie.search(params)
    else
    @results=[]
    end
  end
end

view/search/index
<h1>Search#index</h1>
<p>Find me in app/views/search/index.html.erb</p>

<%= form_tag search_index_path, method: :get do %>
  <p>
    <%= text_field_tag :query, params[:query] %>
    <%= submit_tag "Search", name: nil %>
  </p>
<% end %>
<% if @results %>
<% @results.each do |fetchresults| %>
<%= fetchresults.title %> 
<%= fetchresults.year %><br/>
<% end %>
<% end %>

route.rb资源:搜索根目录“ search#index”

我知道我应该索引我的记录以在弹性搜索中使用它,但不知道如何以及在何处保存这些文件以及如何使用它们。 当我尝试搜索时显示错误

404 : {"error":"IndexMissingException[[movies] missing]","status":404}

当我将Elasticsearch添加到我的Rails应用程序中时,我使用了searchkick:

https://github.com/ankane/searchkick

它真的是用户友好和快速设置。 您可以使用rake searchkick:reindex:all命令来索引所有数据。

自从我从事轮胎工作已经有一段时间了,但是从我的头顶开始:

  • 解决方案1:启动Rails控制台并保存一个新的Movie对象(例如Move.create(...) )。 可能会为您创建索引,但不确定。
  • 解决方案2:运行rake environment tire:import:all在项目的根文件夹中这应该将所有模型重新索引到ElasticSearch中。

希望有所帮助。

更新:

index = Tire::Index.new('oldskool')
index.delete
index.create

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM