2015-07-21 28 views
0

我有一個控制器顯示幾個視圖,但不支持模型,這些視圖只是簡單地呈現爲erb的html如何使用Elasticsearch爲視圖內容編制索引?

我需要做的是從Elasticsearch索引這些視圖中獲取文本,但我想到了缺乏相關文檔。

一個額外的複雜因素是翻譯了視圖,因此它們不直接包含它們的文本。

我應該怎麼做才能讓這些頁面被索引和搜索?我應該如何維護索引,因爲我不能依賴activerecord回調?

+0

你能想到的一些網絡爬蟲,像nutch或ES的一些河流插件像這樣 - https://github.com/codelibs/elasticsearch-river-web – Mysterion

回答

0

基於刮網站的想法解決方案:在WelcomeController

format.json { render json: {body:view_to_text(view), title:@title, url:request.original_url.gsub(/\.json$/,'')} } 
... 
def view_to_text(view) 
    html = render_to_string view, layout: false, formats: :html 
    strip_tags(html).strip.gsub(/^[\s]+/,'').squeeze("\n") 
end 

,並在耙子任務:

require 'open-uri' 

namespace :scrape do 
    desc "scrape view content and send to elasticsearch" 
    task scrape: :environment do 
    client = Elasticsearch::Model.client 
    session = ActionDispatch::Integration::Session.new(Rails.application) 
    session.host! Rails.application.config.action_mailer.default_url_options[:host] 

    Rails.application.routes.routes.to_a.select{|r| r.defaults[:controller] == 'welcome'}.map{|r| r.path.spec.to_s.gsub(/\(\.\:format\)/, '.json') }.reject{|r| '/'==r}.each_with_index{|path,i| 
     session.get path 
     page_string = session.response.body 
     client.index index: Rails.env, type: 'welcome', id: i, body: page_string 
    } 
    end 

end 
相關問題