user1917603 user1917603 - 5 months ago 17
JSON Question

How to create a complex hash in ruby?

I'm building a rails app that is using ElasticSearch. What I'm trying to do is have the rails app send the client a JSON object with the ElasticSearch results. Where I could use help, is how to properly create the object that is sent to the web client.

Right now, in my rails controller, I'm creating a hash. Is hash the right way to go? Am I creating the hash correctly?

# Get the search results
@documents = current_user.documents.search(params[:q], current_user.id)

# Create the HASH
if @documents.count > 0
@documents.aggregations.by_authentication_id.buckets.each_with_index do |bucket, index|
# Create buckets
@json[ :buckets ][ index ] = {}
@json[ :buckets ][ index ][ :key ] = bucket["key"]
@json[ :buckets ][ index ][ :documents ] = {}
bucket["by_top_hit"].hits.hits.each_with_index do |d,i|
@json[ :buckets ][ index ][ :documents ][i] = {
title: d._source.document_title,
snippet: d.text
}
end
end

logger.debug @json


Am I creating the object correctly? I'm looking to learn how to do this right/optimally. I appreciate the advice, tips etc... Thank you

Answer

Not really sure what you are looking for but I think this structure might be nicer for you as a JSON object:

json = {}
json[:buckets] = @documents.aggregations.by_authentication_id.buckets.map do |bucket|

  {
    key: bucket["key"],
    documents:  bucket["by_top_hit"].hits.hits.map do |doc| 
                  { title: doc._source.document_title,
                    snippet: doc.text
                  }
                end  
  }
end

This will produce a result that looks like

 {buckets: [
          {key: 'bucket_key',
           documents: [
                    {title: 'Some Title',
                     snippet: 'snippet'},
                    {title: 'Some Title2',
                     snippet: 'snippet2'}
           ]},
           {key: 'bucket_key2',
           documents: [
                    {title: 'Some Title3',
                     snippet: 'snippet3'},
                    {title: 'Some Title4',
                     snippet: 'snippet4'}
           ]}
         ]
  }

Then you can just call .to_json on this Hash to get the json string for this object to be passed back.