2016-07-07 7 views
0

저는 ElasticSearch를 사용하는 레일 앱을 만들고 있습니다. 내가 뭘 하려는지 레일 애플 리케이션 ElasticSearch 결과와 함께 클라이언트 JSON 개체를 보내도록해야합니다. 도움말을 사용할 수있는 곳은 웹 클라이언트에 전송되는 개체를 올바르게 만드는 방법입니다.루비에서 복잡한 해시를 만드는 방법은 무엇입니까?

지금 내 레일 컨트롤러에서 해시를 만들고 있습니다. 해시가 올바른 방향일까요? 해시를 올바르게 작성하고 있습니까?

# 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 

개체를 올바르게 작성합니까? 나는 이것을/최적으로하는 법을 배우려하고 있습니다.

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 

이것은를 생성합니다 : 당신이 찾고있는 것을 정말 확실히 당신에게

답변

1

하지 감사하지만이 구조는 JSON 객체로 당신을 위해 더 좋은 것 같아요 ... 등 충고, 조언을 주셔서 감사합니다

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

과 같은 결과는 그럼 그냥이 객체가 다시 전달 될위한 JSON 문자열을 얻기 위해이 해시에 .to_json를 호출 할 수 있습니다.

+0

정말 대단합니다. 고맙습니다 – AnnaSm

관련 문제