2013-02-22 76 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

相关问题