loopback icon indicating copy to clipboard operation
loopback copied to clipboard

query date : near & order filters doesn't work together

Open TuNi54 opened this issue 10 years ago • 13 comments

Hi all,

I have a query with a near & an order filters, but it doesn't work.

Someone knows why ?

Thank you :)

Location.find({
            filter : {
                order : "date desc",
                limit : 10,
                skip : 0,
                where : {
                    found : "false",
                    coords : {
                        near : [lat, lng], 
                        maxDistance : 50000, 
                        unit : 'meters'
                    },
                    userId : {
                        neq : "134"
                    }
                },
               
                include : [{
                  relation: "Car",
                  scope : {
                      fields:{
                         name : true
                      }       
                  }
                }]
            }

        })

TuNi54 avatar Nov 05 '16 19:11 TuNi54

@TuNi54 I am trying to reproduce your problem. Could you fork https://github.com/strongloop/loopback-sandbox and replace with your code? Thanks.

jannyHou avatar Nov 07 '16 15:11 jannyHou

Hi @jannyHou,

just try something like that

Location.find({
            order : "date desc",
            limit : 10,
            skip : 0,
            where : {
                found : "false",
                coords : {
                    near : [XX, YY], 
                    maxDistance : 50000, 
                    unit : 'meters'
                }
            }
    },  function(err, locations){
        console.log(locations);
    });

TuNi54 avatar Nov 07 '16 15:11 TuNi54

Any idea ? Thanks

TuNi54 avatar Nov 10 '16 20:11 TuNi54

@TuNi54 I am trying to help, can you follow https://github.com/strongloop/loopback/issues/2917#issuecomment-258868317 and provide some sample data to reproduce your problem?

jannyHou avatar Nov 11 '16 15:11 jannyHou

my two penny:

assuming you're working with MongoDB, hence you implicitly refer to loopback-connector-mongodb module, here is the chunk of code responsible of sorting:

function processResponse(err, cursor) {
    if (err) {
      return callback(err);
    }
    var order = {};

    // don't apply sorting if dealing with a geo query
    if (!hasNearFilter(filter.where)) {
      if (!filter.order) {
        var idNames = self.idNames(model);
        if (idNames && idNames.length) {
          filter.order = idNames;
        }
      }
      if (filter.order) {
        var keys = filter.order;
        if (typeof keys === 'string') {
          keys = keys.split(',');
        }
        for (var index = 0, len = keys.length; index < len; index++) {
          var m = keys[index].match(/\s+(A|DE)SC$/);
          var key = keys[index];
          key = key.replace(/\s+(A|DE)SC$/, '').trim();
          if (key === idName) {
            key = '_id';
          }
          if (m && m[1] === 'DE') {
            order[key] = -1;
          } else {
            order[key] = 1;
          }
        }
      } else {
        // order by _id by default
        order = { _id: 1 };
      }
      cursor.sort(order);
    }

    if (filter.limit) {
      cursor.limit(filter.limit);
    }
    if (filter.skip) {
      cursor.skip(filter.skip);
    } else if (filter.offset) {
      cursor.skip(filter.offset);
    }
    cursor.toArray(function(err, data) {
      if (self.debug) {
        debug('all', model, filter, err, data);
      }
      if (err) {
        return callback(err);
      }
      var objs = data.map(function(o) {
        if (idIncluded(fields, self.idName(model))) {
          self.setIdValue(model, o, o._id);
        }
        // Don't pass back _id if the fields is set
        if (fields || idName !== '_id') {
          delete o._id;
        }
        o = self.fromDatabase(model, o);
        return o;
      });
      if (filter && filter.include) {
        self._models[model].model.include(objs, filter.include, options, callback);
      } else {
        callback(null, objs);
      }
    });
  }

As you can see, if any field has a near filter, other sorting instructions are ignored. This is mainly because the near filter is, by itself, considered not a filtering clause (i.e. that slices the result set) but an order criterion (see docs). By combining near and maxDistance you should achieve what you meant, that is get results in a radius from a point, ordered by most recent, and this is supported by docs, too.

However, if you dig into the code above, you'll realize that this is never gonna happen.

balanza avatar Nov 21 '16 09:11 balanza

@balanza thank you for your explanation. However, I have already a near and maxDistance filters. I would like to add an order criterion by date, as you can see in my example above. Do you any idea?

TuNi54 avatar Nov 21 '16 10:11 TuNi54

Unfortunately I don't have a solution you can implement in your app straight away. But you can easily fork the loopback-connector-mongodb module and fix this issue (I think it's barely two lines of code). Then, eventually, propose a PR. If you fancy do it and you need some help, here I am.

Emanuele De Cupis emanuele.decup.is http://emanuele.decup.is

On 21 November 2016 at 11:37, TuNi54 [email protected] wrote:

@balanza https://github.com/balanza thank you for your explanation. However, I have already a near and maxDistance filters. I would like to add an order criterion by date, as you can see in my example above. Do you any idea?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/strongloop/loopback/issues/2917#issuecomment-261901801, or mute the thread https://github.com/notifications/unsubscribe-auth/AAQNXCV29YHrmp1fA9AsEKRxuinFG0qWks5rAXRQgaJpZM4KqWqi .

balanza avatar Nov 21 '16 13:11 balanza

it's strange, hasNearFilter method return always false :|

TuNi54 avatar Nov 21 '16 14:11 TuNi54

sure you're using the very latest version of the module? Here's the function:

function hasNearFilter(where) {
  if (!where) return false;

  for (var k in where) {
    if (where[k] && typeof where[k] === 'object' && where[k].near) {
      return true;
    }
  }

  return false;
}

Beware: if you put the near filter into an and/or/not clause, it doesn't work: https://github.com/strongloop/loopback-connector-mongodb/issues/271

balanza avatar Nov 21 '16 14:11 balanza

I didn't have the latest version, then I uninstalled loopback & the connector. My package.json is now like this :

"loopback": "^2.36.0",
 "loopback-connector-mongodb": "^1.17.0",

And my request something like that :

Location.find({
            order : "date desc",
            limit : 10,
            skip : 0,
            where : {
                found : "false",
                coords : {
                    near : [XX, YY], 
                    maxDistance : 50000, 
                    unit : 'meters'
                }
            }
    },  function(err, locations){
        console.log(locations);
    });

But if I do a console.log(hasNearFilter(filter.where)), it's still false

TuNi54 avatar Nov 21 '16 14:11 TuNi54

I reproduced it in loopback-connector-mongodb with test case https://github.com/strongloop/loopback-connector-mongodb/blob/07afdbfa02476d04bcc08b1cb7008d622987a51b/test/mongodb.test.js#L1527

filter:

order: '_id DESC',
where: {
       location: {
       near: new GeoPoint(coords),
       maxDistance: 17000,
       unit: 'meters',
      },
},

and result are not ordered by _id

@TuNi54 can you confirm which connector you use? Thanks. If it's a mongodb specific error I can open as issue in loopback-connector-mongodb to track fixing it or further discussion. If it's a problem with other connectors as well let's keep discussion here.

jannyHou avatar Nov 21 '16 19:11 jannyHou

Hi @jannyHou, thank you for your help.

Yes, I confirm the connector is loopback-connector-mongodb.

Thank you, I'm waiting your issue.

Regards

TuNi54 avatar Nov 21 '16 19:11 TuNi54

@TuNi54 @balanza I opened a new issue in mongodb and linked it to this issue to keep our discussion: https://github.com/strongloop/loopback-connector-mongodb/issues/310

closing this one as a dup :)

jannyHou avatar Nov 21 '16 19:11 jannyHou