krlawrence / graph

Practical Gremlin - An Apache TinkerPop Tutorial
Apache License 2.0
836 stars 253 forks source link

Add example of using math() to calculate Haversine Great Circle distance #169

Closed krlawrence closed 1 year ago

krlawrence commented 4 years ago

Add to the discussion of Geo Spatial queries that are possible in Gremlin using the examples below that demonstrate calculating the Haversine Great Circle Distance between two airports.

g.withSideEffect("PI", 3.1415926535).
  withSideEffect("rdeg", 0.017453293).
  withSideEffect("gcmiles",3956).        
  V().has('code','AUS').as('src').
  V().has('code','LHR').as('dst').
  select('src','dst').
    by(project('lat','lon').
         by('lat').
         by('lon')).as('grp').
    project('ladiff','lgdiff','lat1','lon1','lat2','lon2').
       by(project('la1','la2').
            by(select('grp').select('src').select('lat')).
            by(select('grp').select('dst').select('lat')).
          math('(la2 - la1) * rdeg')).
       by(project('lg1','lg2').
            by(select('grp').select('src').select('lon')).
            by(select('grp').select('dst').select('lon')).
          math('(lg2 - lg1) * rdeg')).
       by(select('grp').select('src').select('lat')).
       by(select('grp').select('src').select('lon')).
       by(select('grp').select('dst').select('lat')).
       by(select('grp').select('dst').select('lon')).
    math('(sin(ladiff/2))^2 + cos(lat1*rdeg) * cos(lat2*rdeg) * (sin(lgdiff/2))^2').
    math('gcmiles * (2 * asin(sqrt(_)))')              

g.withSideEffect("PI", 3.1415926535).
  withSideEffect("rdeg", 0.017453293).
  withSideEffect("gcmiles",3956).
  V().
  has('code',within('AUS','DFW')).
  group().
    by('code').
    by(project('lat','lon').
      by('lat').
      by('lon')).
  as('grp').
  project('ladiff','lgdiff','lat1','lon1','lat2','lon2').
    by(project('la1','la2').
         by(select('AUS').select('lat')).
         by(select('DFW').select('lat')).
       math('(la2 - la1) * rdeg')).
    by(project('lg1','lg2').
         by(select('AUS').select('lon')).
         by(select('DFW').select('lon')).
       math('(lg2 - lg1) * rdeg')).
    by(select('grp').select('AUS').select('lat')).
    by(select('grp').select('AUS').select('lon')).
    by(select('grp').select('DFW').select('lat')).
    by(select('grp').select('DFW').select('lon')).
    math('(sin(ladiff/2))^2 + cos(lat1*rdeg) * cos(lat2*rdeg) * (sin(lgdiff/2))^2').
    math('gcmiles * (2 * asin(sqrt(_)))')       
krlawrence commented 1 year ago

Closing as this is fixed and work has now started on the second edition. There will likely be one final release of the v283 first edition line before the V2 branch becomes the second edition. That release will include these fixes.