2013-02-22 66 views
3

我已經索引了一個Car模型與一個汽車記錄mercedes benz在數據庫中。如果我搜索的單詞benz我得到一個錯誤:鋼軌輪胎elasticsearch奇怪的錯誤

ActiveRecord::RecordNotFound in CarsController#index 

Couldn't find all Cars with IDs (1, 3) (found 1 results, but was looking for 2) 

如果我搜索hello我得到:

Couldn't find Car with id=2 

其他隨機搜索字詞工作返回準確的結果。

所以它基本上是由隨機搜索術語產生的隨機錯誤。這可能是什麼原因?

控制器:

def index 
if params[:query].present? 
    @cars = Car.search(params) 
else 
    @cars = Car.paginate(:page => params[:page], :per_page => 10) 
end  
end 

型號:

def self.search(params) 
    tire.search(load: true, page: params[:page], per_page: 10) do |s| 
    s.query { string params[:query]} if params[:query].present? 
    end 
    end 
+0

我覺得你的指數是不是在你的數據庫同步。您已從您的數據庫中刪除了一些汽車記錄,但它們並未從搜索索引中刪除。重新創建索引並嘗試搜索。 – 2013-02-22 15:00:04

+0

我找不到輪胎reindex命令。我可以運行rake db:drop + rake db:setup to reindex? – 2013-02-22 15:10:23

+0

您可以刪除索引(例如:curl -XDELETE'http:// localhost:9200/cars /'),然後重新索引(rake setup:tire)。 – 2013-02-22 15:15:08

回答

3

這是因爲,您正在使用負載=> true選項,從數據庫加載搜索結果。 activerecord似乎在數據庫中缺失,但elasticsearch索引包含相同的文檔。

Reindex並不總是解決方案恕我直言。

最好的解決辦法是刪除文件在db中刪除。你可以使用after_destroy回調。

Tire remove api用於從索引中刪除單個文檔。

Tire.index('my-index-name').remove('my-document-type', 'my-document-id') 

參考:https://github.com/karmi/tire/issues/43

+0

你能解釋一下/在哪裏使用after_destroy回調? – 2013-11-17 19:08:07

+0

只需在你的模型中使用它,即http://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/after_commit。 'after_commit:some_method,:on =>:destroy'。在some_method裏面實現從elasticsearch刪除文檔的代碼。我在答案中給出的一個。 – 2013-11-18 07:53:38