如何通过elasticsearch rails中的ID获取文档

jdk*_*aly 4 elasticsearch elasticsearch-rails

我在elasticsearch文档中看到,您可以通过其ID获取文档.elasticsearch rails中有没有相应的东西?我正在通过API提供"as_indexed_json"并且这是一个有点昂贵的查询,我想在我的API中直接从弹性搜索中返回JSON.

Nat*_*han 12

您可以使用get方法on,通过id从给定索引中获取特定文档Elasticsearch::Transport::Client.该get方法需要一个哈希参数,其中包含要从中获取的索引的键以及要获取的文档的ID.

所以,你们需要三件事:

  1. 客户端对象
  2. 索引的名称
  3. 文档的ID(即您的模型ID)
client = YourModel.__elasticsearch__.client
document = client.get({ index: YourModel.index_name, id: id_to_find })
Run Code Online (Sandbox Code Playgroud)


Mis*_*sha 5

在这里,您如何完成它。这是来自控制器的动作,对我来说效果很好。

def show
  client = Elasticsearch::Client.new host:'127.0.0.1:9200', log: true
  response = client.search index: 'example', body: {query: { match: {_id: params[:id]} } }
  @example = response['hits']['hits'][0]['_source']
   respond_to do |format|
     format.html # show.html.erb
     format.js # show.js.erb
     format.json { render json: @example }
   end
  @records = Example.search(@example['name']).per(12).results
end
Run Code Online (Sandbox Code Playgroud)