reThinkDB join / where存在等效太慢

时间:2015-12-02 14:05:29

标签: node.js join rethinkdb

我正在执行与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);
        });
}

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

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

注意:我无法在网页界面中对其进行分析,该查询只会运行很长时间。

1 个答案:

答案 0 :(得分:1)

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

所以我会重新编写它以符合您的评论

  

//前。 rWeather(123)应该返回[{id:1,city:' abc',数据:   一些数据' }] //首先在app表中找到city' abc'   然后在天气表中

创建索引:

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'})
        })

 }
相关问题