I see in the elasticsearch docs you can fetch a document by its ID. Is there any equivalent in elasticsearch rails? I'm feeding by API with "as_indexed_json" and it's a somewhat expensive query, I'd like to return ths JSON straight out of elasticsearch in my API.
Asked
Active
Viewed 3,897 times
2 Answers
14
You can fetch a particular document from a given index by id with the get
method on Elasticsearch::Transport::Client
. The get
method expects a single hash argument with keys for the index you want to fetch from and the id of the document you want to fetch.
So, all together you need 3 things:
- A client object
- The name of the index
- The id of the document (i.e. your model id)
client = YourModel.__elasticsearch__.client
document = client.get({ index: YourModel.index_name, id: id_to_find })

Nathan
- 7,816
- 8
- 33
- 44
5
Here how you can accomplish it. This is from controller action and works well for me.
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

Misha
- 1,876
- 2
- 17
- 24