[英]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
命令來索引所有數據。
自從我從事輪胎工作已經有一段時間了,但是從我的頭頂開始:
Movie
對象(例如Move.create(...)
)。 這可能會為您創建索引,但不確定。 rake environment tire:import:all
在項目的根文件夾中這應該將所有模型重新索引到ElasticSearch中。 希望有所幫助。
更新:
index = Tire::Index.new('oldskool')
index.delete
index.create
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.