reThinkDB join / where exists equivalent 太慢了

reThinkDB join / where exists equivalent too slow

我正在做的事情与 reThinkDB SQL cheatsheet 中的最后一个 SELECT 示例非常相似:

SQL :

SELECT *
  FROM posts
  WHERE EXISTS
    (SELECT * FROM users
     WHERE posts.author_id
         = users.id)

反思:

r.table("posts")
  .filter(function (post) {
    return r.table("users")
      .filter(function (user) {
        return user("id").eq(post("authorId"))
      }).count().gt(0)
    })

这是我正在执行的确切查询(尽管我认为这不重要):

// Sample data :
// app table :
// [{id : 123, city : 'abc' }, { id : 234 }, ...]

// weather table :
// [{id : 1, city : 'abc', data : 'some data' }, { id : 2 }, ...]

// ex. rWeather(123) should return [{id : 1, city : 'abc', data : 'some data' }]
// by finding the city 'abc', first in the app table, then in the weather table

/**
 * Returns the weather for a given app
 */
export function rWeather (id) {

    var appCity = function(weather) {
        return r.db('gfi')
            .table('app')
            .withFields(['city'])
            .filter(function (app) {
                return app('id').eq(weather('appId'));
            });
    };

    return r.db('gfi')
        .table('weather')
        .filter(function(weather) {
            return  appCity(weather).count().gt(0);
        });
}

所以问题是:如何加快速度?

我应该更改查询的形式吗?我应该添加索引(在哪里)?

注意:我无法在 Web 界面中对其进行分析,查询运行了很长时间。

您的代码注释与您的代码不匹配。在您的代码中,您似乎是在 weather table 上使用 appId 字段加入。在 rWeather 中,您不使用变量 id...

所以我会重写它以匹配您的评论

// ex. rWeather(123) should return [{id : 1, city : 'abc', data : 'some data' }] // by finding the city 'abc', first in the app table, then in the weather table

创建索引:

r.table('weather').indexCreate('city')

这是一个函数:

export function rWeather (id) {

  return r.db('gfi')
        .table('app').get(id).do(function(app) {
          return r.table('weather').getAll(app('city').default(''), {index: 'city'})
        })

 }