Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch a document by its ID in elasticsearch rails

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.

like image 519
jdkealy Avatar asked Aug 25 '15 00:08

jdkealy


People also ask

How do I find Elasticsearch document ID?

When you index documents that don't have an ID, and ID is generated for you by ElasticSearch. That field name is "_id". The above query would return documents that have have _id equal to 1 OR 2.

What should you use to fetch a document in Elasticsearch?

Descriptionedit. You use GET to retrieve a document and its source or stored fields from a particular index. Use HEAD to verify that a document exists. You can use the _source resource retrieve just the document source or verify that it exists.

How do I retrieve data from Elasticsearch?

You can use the search API to search and aggregate data stored in Elasticsearch data streams or indices. The API's query request body parameter accepts queries written in Query DSL. The following request searches my-index-000001 using a match query. This query matches documents with a user.id value of kimchy .


2 Answers

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:

  1. A client object
  2. The name of the index
  3. 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 })
like image 176
Nathan Avatar answered Jan 04 '23 00:01

Nathan


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
like image 28
Misha Avatar answered Jan 04 '23 00:01

Misha