在Postgres查询中调用本地函数

问题描述 投票:0回答:1

我有一个查询我的数据库以查找附近用户的函数。但是,我的数据库存储用户的经度和纬度,并且为了找到与用户的距离,我需要调用一个函数(距离)来检查在查询中返回哪些用户。有没有办法在代码中执行我所拥有的操作(在我的查询字符串中调用我的本地距离函数?)

exports.getNearby = function (longitude, latitude) {
var long1 = longitude;
var lat1 = latitude;
return new Promise(((resolve, reject) => {
    const queryString = `SELECT ${userModel.userId}
     FROM ${userModel.collectionName} where SELECT distance(${userLocationModel.latitude},
     ${userLocationModel.longitude}, ${lat1}, ${long1}) < 4`;
    db.query(queryString, (err, res) => {
        if (err) {
            logger.log('error', ` getUser - ${userIdArr} - ${err}`);
            reject(err);
        } else {
            resolve(res.rows[0]);
        }
    });
}));
};

function distance(lat1, lon1, lat2, lon2) {             //returns in km
  return 12742 * asin(sqrt(0.5 - cos((lat2 - lat1) * 0.01745329252)/2 
    + cos(lat1 * 0.01745329252) * cos(lat2 * 0.01745329252) * 
    (1 - cos((lon2 - lon1) * 0.01745329252)) / 2));
}

用Postgres编写的函数(由@LaurenzAlbe建议)

CREATE FUNCTION distance(
lat1 double precision,
lng1 double precision,
lat2 double precision,
lng2 double precision
) RETURNS double precision AS 
'SELECT 12742
     * asin(
         |/ (
             0.5 - cos(
                 (lat2 - lat1) * 0.01745329252
             )/2 
             + cos(lat1 * 0.01745329252)
             * cos(lat2 * 0.01745329252)
             * (1 - cos(
                 (lon2 - lon1) * 0.01745329252
             )) / 2
         )
    )'
LANGUAGE sql IMMUTABLE;
node.js postgresql stored-functions
1个回答
1
投票

如果要在SQL语句中使用该函数,则必须使用CREATE FUNCTION在数据库中定义它。

对于这样的功能,我选择LANGUAGE sql

如果要在数据库中进行地理数据处理,您是否考虑过使用PostGIS扩展?它提供了开箱即用的所有可想象的功能。

以下是您的函数看起来像SQL函数:

CREATE FUNCTION distance(
    lat1 double precision,
    lng1 double precision,
    lat2 double precision,
    lng2 double precision
) RETURNS double precision AS 
'SELECT 12742
         * asin(
             |/ (
                 0.5 - cos(
                     (lat2 - lat1) * 0.01745329252
                 )/2 
                 + cos(lat1 * 0.01745329252)
                 * cos(lat2 * 0.01745329252)
                 * (1 - cos(
                     (lon2 - lon1) * 0.01745329252
                 )) / 2
             )
        )'
    LANGUAGE sql IMMUTABLE;
© www.soinside.com 2019 - 2024. All rights reserved.