0

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.

nacc
  • 311
  • 3
  • 8

1 Answers1

0

Does this do what you want?

document['rows'].concat_map(lambda row: row['elements'])['distance']['value'].sum()
mlucy
  • 5,249
  • 1
  • 17
  • 21
  • Is this supposed to be for ReQL? If so, I can't seem to get it to work and can't find a similar snippet in the documentation. And, I'm noob enough on Python to not know off-hand if it's supposed to be dropped in there? – nacc Aug 26 '16 at 15:19
  • It's ReQL code. If you replace `document` with whatever ReQL query gets your document, then the above query is meant to sum the distances. – mlucy Aug 26 '16 at 19:25
  • Gotcha, worked like a charm. I had to add a couple things to get it to work in Python interpreter, so for anyone else looking at this I ended up with: `r.table('stories').get('689bc43c-c8c3-45df-b38b-e52043a0bab4')['rows'].concat_map(lambda row: row['elements'])['distance']['value'].sum().run()` thanks @mlucy! – nacc Aug 29 '16 at 17:37