2016-07-07 99 views
0

我正在构建使用ElasticSearch的Rails应用程序。我想要做的是让Rails应用程序向客户端发送带有ElasticSearch结果的JSON对象。在哪里我可以使用帮助,是如何正确地创建发送到Web客户端的对象。如何在ruby中创建一个复杂的哈希?

现在,在我的轨道控制器中,我创建了一个散列。散列正确的路要走吗?我是否正确创建散列?

# 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 

我是否正确创建对象?我期待着学习如何正确/最佳地做到这一点。我很欣赏的意见,建议等..谢谢

回答

1

不能确定你在找什么,但是我觉得作为一个JSON对象这种结构可能是你更好:

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 

这将产生一个结果,看起来像

{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'} 
      ]} 
     ] 
    } 

然后,你可以调用.to_json这个哈希以获取该对象被传递回JSON字符串。

+0

这真的很棒。谢谢 – AnnaSm