rethinkdbrethinkdb-python

Sum two fields in a nested array in RethinkDB


The following document exists in a table in RethinkDB:

{  
   u'destination_addresses':[  
      u'1 Rockefeller Plaza,
      New York,
      NY 10020,
      USA',
      u'Meadowlands,
      PA 15301,
      USA'
   ],
   u'origin_addresses':[  
      u'1600 Pennsylvania Ave SE,
      Washington,
      DC 20003,
      USA'
   ],
   u'rows':[  
      {  
         u'elements':[  
            {  
               u'distance':{  
                  u'text':u'288 mi',
                  u'value':464087
               },
               u'duration':{  
                  u'text':u'5 hours 2 mins',
                  u'value':18142
               },
               u'status':u'OK'
            },
            {  
               u'distance':{  
                  u'text':u'266 mi',
                  u'value':428756
               },
               u'duration':{  
                  u'text':u'4 hours 6 mins',
                  u'value':14753
               },
               u'status':u'OK'
            }
         ]
      }
   ],
   u'status':u'OK'
}

I am trying to sum the 'value' field for both duration and distance (so, getting the total distance and duration for a given trip, which is what one of these documents is from the Google Maps Distance API). I have tried a great many combinations of pluck (from the nested fields documentation) but cannot seem to get this working. I'm working in Python, and thanks in advance for any help.


Solution

  • Does this do what you want?

    document['rows'].concat_map(lambda row: row['elements'])['distance']['value'].sum()