【问题标题】:How to create a complex hash in ruby?如何在 ruby​​ 中创建复杂的哈希?
【发布时间】:2016-07-07 17:16:39
【问题描述】:

我正在构建一个使用 ElasticSearch 的 rails 应用程序。我想要做的是让 rails 应用程序向客户端发送一个带有 ElasticSearch 结果的 JSON 对象。我可以使用帮助的地方是如何正确创建发送到 Web 客户端的对象。

现在,在我的 Rails 控制器中,我正在创建一个哈希。哈希是正确的方法吗?我是否正确创建了哈希?

# 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

我是否正确地创建了对象?我正在寻找学习如何正确/最佳地做到这一点。感谢您的建议、提示等...谢谢

【问题讨论】:

    标签: ruby-on-rails ruby json hash


    【解决方案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'}
               ]}
             ]
      }
    

    然后你可以在这个 Hash 上调用 .to_json 来获取这个对象的 json 字符串被传回。

    【讨论】:

    • 这真的很棒。谢谢
    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2015-10-11
    • 2014-07-20
    • 2014-10-20
    • 2012-11-23
    相关资源
    最近更新 更多