SQL >> Database teknologi >  >> RDS >> Mysql

Sequelize geospatial query: find N nærmeste punkter

Når du pakker sequelize.fn i parenteser, skal du også angive et streng-alias:

[sequelize.fn('ST_Distance_Sphere', sequelize.literal('geolocation'), location), 'ALIASNAME']

Prøv også at skifte ST_Distance ud med ST_Distance_Sphere:

const location = sequelize.literal(`ST_GeomFromText('POINT(${lng} ${lat})', 4326)`);

User.findAll({
  attributes: [[sequelize.fn('ST_Distance_Sphere', sequelize.literal('geolocation'), location), 'distance']],
  order: 'distance',
  limit: 10,
  logging: console.log
}).then(function(instance) {
  console.log(instance);
});

Det virkede for mig. Erstat blot 'User' med den model, der har din geometridatatype.

Opdatering: hvis du stadig ikke kan sortere med order: 'distance', skal du erklære det i en variabel og sende det uden quotes:

var lat = parseFloat(json.lat);
var lng = parseFloat(json.lng);
var attributes = Object.keys(User.attributes);
var location = sequelize.literal(`ST_GeomFromText('POINT(${lng} ${lat})')`);
var distance = sequelize.fn('ST_Distance_Sphere', sequelize.literal('geolocation'), location);
attributes.push([distance, 'distance']);

var query = {
  attributes: attributes,
  order: distance,
  include: { model: Address, as: 'address' },
  where: sequelize.where(distance, { $lte: maxDistance }),
  logging: console.log
};

Opdatering om afstandspræcision: løsningen, som sarikaya nævnte, ser ud til at være mere præcis. Sådan gør du i Postgres:

var distance = sequelize.literal("6371 * acos(cos(radians("+lat+")) * cos(radians(ST_X(location))) * cos(radians("+lng+") - radians(ST_Y(location))) + sin(radians("+lat+")) * sin(radians(ST_X(location))))");
  1. Ret limit og offset i Sequelize

  2. Find radius i en cirkel, der omslutter flere bredde-/længdegradspunkter

  3. Forespørg om den nærmeste bredde- og længdegrad i CakePHP 3

  4. Find det bedste præfiks-match i MySQL