Uploaded image for project: 'Couchbase Server'
  1. Couchbase Server
  2. MB-35851

Allow local variable in N1QL Javascript functions

    XMLWordPrintable

Details

    • Improvement
    • Resolution: Done
    • Minor
    • feature-backlog
    • 6.5.0
    • query
    • Any

    Description

      Functions in N1QL currently don't allow local variables (nor do they support a return statement) for example implementing a Haversin function (for the distance in Km between two lon/lat pairs has to be implemented as an inline as follows:

      CREATE FUNCTION getDistanceFromLatLonInKm(lon1, lat1, lon2, lat2) {
        6371 * 2 * atan2(sqrt(
          (
            sin(((lat2-lat1) * (3.14159265359/180))/2) * 
            sin(((lat2-lat1) * (3.14159265359/180))/2) +
            cos((3.14159265359/180)*(lat1)) * cos((3.14159265359/180)*(lat2)) *
            sin(((lon2-lon1) * (3.14159265359/180))/2) * 
            sin(((lon2-lon1) * (3.14159265359/180))/2)
          )
       
        ), sqrt(1-
          (
            sin(((lat2-lat1) * (3.14159265359/180))/2) * 
            sin(((lat2-lat1) * (3.14159265359/180))/2) +
            cos((3.14159265359/180)*(lat1)) * cos((3.14159265359/180)*(lat2)) *
            sin(((lon2-lon1) * (3.14159265359/180))/2) * 
            sin(((lon2-lon1) * (3.14159265359/180))/2)
          )
        ))
      };

       

      Where the actual function I modeled it from would be much more readable and faster (due to eliminating repetitive calculations) using local variables and a return statement if such syntax were supported in a N1QL Javascript function

      CREATE FUNCTION function getDistanceFromLatLonInKm(lon1, lat1, lon2, lat2) {
        var PI = 3.14159265359
        var deg2rad = PI/180;
        var R = 6371; // Radius of the earth in km
        var dLat = deg2rad*(lat2-lat1);
        var dLon = deg2rad*(lon2-lon1);
        var a =
          sin(dLat/2) * sin(dLat/2) +
          cos(deg2rad*(lat1)) * cos(deg2rad*(lat2)) *
          sin(dLon/2) * sin(dLon/2)
          ;
        var c = 2 * atan2(sqrt(a), sqrt(1-a));
        var d = R * c; // Distance in km
        return d;
      };

      Oddly Eventing allows the user to use local variables as such it seems somewhat inconsistent between the two domains

       

       

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            keshav Keshav Murthy
            jon.strabala Jon Strabala
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes

                PagerDuty