Reputation: 509
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.
Upvotes: 1
Views: 232
Reputation: 5289
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.
Upvotes: 2
Reputation: 112927
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);
}
Upvotes: 1