我有一个表,其中包含用户及其位置,保存为 r.point
数据类型以及在其上设置的 geo
索引。我正在尝试运行 .getNearest()
查询,该查询返回最接近给定用户(例如,X 先生)的所有用户。结果返回与 Mr. 最接近的所有用户。 X,但也包括先生。 X。如何过滤除之外的所有用户 Mr. X?
到目前为止我已经尝试过的 -
在 RethinkDB 的数据浏览器中(普通 ReQL 命令)
r.db('myDb').table('myTable').getNearest(r.point(-20, 39), {index: 'location'}).filter(function(user) {return user.id !== '2ff8902e-97f0-431a-a51c-900a57532967'}); // Assuming Mr.X's `id` is `2ff8902e-97f0-431a-a51c-900a57532967`
这将返回所有用户,包括 Mr. X。尝试 #2 是 -
r.db('myDb').table('myTable').getNearest(r.point(-20, 39), {index: 'location', maxDist:9000000}).filter(r.row('id').ne('2ff8902e-97f0-431a-a51c-900a57532967'));
这不会返回任何内容。
在 thinky ,RethinkDB 的 Node.js ORM。
UserModel.getNearest(r.point(-20, 39), {index: 'location'}).filter(function(user) {return user.id !== '2ff8902e-97f0-431a-a51c-900a57532967'}).run();
这将返回所有用户,包括 Mr. X。
我已经知道的一个解决方案 -
使用 Thinky,我可以做到这一点。
const userId = '2ff8902e-97f0-431a-a51c-900a57532967';
const location = r.point(-20, 39);
const queryOptions = {index: 'location'};
UserModel.getNearest(location, queryOptions).run().then(function (users) {
return users.filter(function(user) {
return user.doc.id !== userId;
});
});
我有一种感觉,我可以做得更快;确保 .filter()
或其他替代函数在 RethinkDB 服务器上运行,而不是在我这边运行。这里还有改进的空间吗?或者也许是我忽略的更好的解决方案?
最佳答案
你实际上做得正确并且几乎完成了。您只是碰巧使用 filter
和错误的 key 。
r.db('myDb').table('myTable').getNearest(r.point(-20, 39), {index: 'location'})
.filter(function(user) {
return user('doc')('id').ne('2ff8902e-97f0-431a-a51c-900a57532967')
})
关键是:
getNearest
返回文档数组。每个文档都有两个字段:dist
和doc
(这是表本身中的文档)。因此,这里我们使用user('doc')('id')
来获取 key 。 https://rethinkdb.com/api/javascript/get_nearest/- 在
filter
函数中,我们必须使用ReQL命令,在这种情况下,ne
的意思是不等于。 https://www.rethinkdb.com/api/javascript/ne/
这很快,因为我们有位置索引。 filter
函数在RethinkDB服务器上执行。
关于javascript - 如何在 RethinkDB 中对 getNearest() 查询运行过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33255750/