Reputation: 4907
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.
Upvotes: 6
Views: 4424
Reputation: 1896
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
Upvotes: 5
Reputation: 8026
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:
client = YourModel.__elasticsearch__.client
document = client.get({ index: YourModel.index_name, id: id_to_find })
Upvotes: 15