首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用elasticsearch-model创建索引,批量索引不起作用

如何使用elasticsearch-model创建索引,批量索引不起作用
EN

Stack Overflow用户
提问于 2014-12-25 04:19:00
回答 1查看 2.9K关注 0票数 2

我使用elasticsearch-model gem集成了activerecord和elasticsearch,我正在使用这个模块:

代码语言:javascript
复制
#http://www.codinginthecrease.com/news_article/show/409843?referrer_id=
module PostImport

  def self.import
    Post.find_in_batches do |posts|
      bulk_index(posts)
    end
  end


  def self.prepare_records(posts)
    posts.map do |post|
      { index: { _id: post.id, data: post.as_indexed_json } }
    end
  end

  def self.delete_index
    Post.__elasticsearch__.client
      .indices.delete index: ::Post.__elasticsearch__.index_name rescue nil
  end

  def self.create_index
    Post.__elasticsearch__.create_index!
  end

  def self.bulk_index(posts)
    Post.__elasticsearch__.client
      .bulk({
             index: ::Post.__elasticsearch__.index_name,
             type: ::Post.__elasticsearch__.document_type,
             body: prepare_records(posts),
             refresh: true
            })
  end
end

根据elasticsearch-model example的说法

它使用它来批量创建索引:

代码语言:javascript
复制
client.bulk index: 'articles',
            type:  'article',
            body:  Article.all.as_json.map { |a| { index: { _id: a.delete('id'), data: a } } },
            refresh: true

但这引发了以下问题:

代码语言:javascript
复制
Elasticsearch::Transport::Transport::Errors::NotFound: [404] {"error":"IndexMissingException[[posts] missing]","status":404}
from /home/ubuntu/.rvm/gems/ruby-2.1.3/gems/elasticsearch-transport-1.0.6/lib/elasticsearch/transport/transport/base.rb:132:in `__raise_transport_error'

所以在我的模块中等效的代码:PostImport::import会引发这个异常,如果我先调用Post.__elasticsearch__.create_index!,然后再导入,它工作得很好。

使用elasticsearch-model gem初始化elasticsearch和创建索引的正确方式是什么?

EN

回答 1

Stack Overflow用户

发布于 2016-07-02 00:24:51

您可以使用elasticsearch-rails gem来实现这一点。请参阅此处的文档:https://github.com/elastic/elasticsearch-rails/tree/master/elasticsearch-rails

为了便于将数据从模型导入到Elasticsearch中,需要在应用程序中定义任务,例如。创建包含以下内容的lib/task/elasticsearch.rake文件:

代码语言:javascript
复制
require 'elasticsearch/rails/tasks/import'

要首次从文章模型导入记录并创建索引,请运行以下命令:

代码语言:javascript
复制
$ bundle exec rake environment elasticsearch:import:model CLASS='Article' FORCE=y
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27641822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档