1

I am creating an index based on 2 fields in RethinkDB, in javascript (actually with rethinkdbdash driver). The code is like this : r.table('someTable').indexList().contains("indexName").do(containsIndex => { return r.branch( containsIndex, {created: 0}, r.table('someTable').indexCreate("indexName", [r.row("field1"), r.row("field2")]) ); }).run();

So it conditionnally creates the index if it doesn't exist already. The branching does work for single-field indexes. But it returns a ReqlCompileError: Cannot use r.row in nested queries. Use functions instead in this case.

The docs (https://www.rethinkdb.com/api/javascript/index_create/) clearly give this example : r.table('comments').indexCreate('postAndDate', [r.row("postId"), r.row("date")]).run(conn, callback)

So what am I missing? Is using the rethinkdbdash driver changing anything? If I do use a function (as suggested by the error message) I can concatenate my 2 fields, but then how do I query with that index?

Thanks.

Spiky
  • 509
  • 4
  • 11

2 Answers2

2

You can use r.row in un-nested queries like the example in the docs, but for nested queries you need to use an actual function. When you put the indexCreate inside a do it became part of a nested query.

If instead of r.table('someTable').indexCreate("indexName", [r.row("field1"), r.row("field2")]) you write r.table('someTable').indexCreate('indexName', function(row) { return [row('field1'), row('field2')]; }) in your query it should work.

mlucy
  • 5,249
  • 1
  • 17
  • 21
  • Fantastic. The way to write the function was not so easy to find, either, and it works. Thanks also for the nested query explanation. – Spiky Dec 09 '15 at 14:14
1

I don't know how to do this type of branching correctly when creating compound indexes, but RethinkDB will just warn you if you try to create an index that already exists, so there is no worry if you just catch it and continue:

function createPostAndDateIndex() {
  return r.table('comments').indexCreate('postAndDate', 
    [r.row("postId"), r.row("date")]).run();
}

function createDateIndex() {
  return r.table('comments').indexCreate('d', 'date').run() 
}

function initDb() {
  return createPostAndDateIndex().error(console.warn)
    .then(createDateIndex).error(console.warn);
}
Tholle
  • 108,070
  • 19
  • 198
  • 189