Can a FOXX application automatically create an index? I have a collection (model) where I need a field to be used as a unique index for performance. I could create the hash after the fact, but I just wanted to be sure it wasn't available using the model definition. If so, where can I find documentation?
A secondary question is how to create an index in FOXX? I know how to do it in arangojs but I can't seem to find it in the FOXX documentation. Scratch this question. I figured this out: db.collection.createIndex(). But boy was that hidden deep in the "misc" section of the documentation.
The index API is not part of the Foxx API but the general ArangoDB API (Foxx is merely the framework ArangoDB provides for building and managing microservices) and can be found in the ArangoDB documentation: https://docs.arangodb.com/3.11/index-and-search/indexing/working-with-indexes/
'use strict';
var myCollection = applicationContext.collection('my-data');
myCollection.ensureIndex({type: 'hash', fields: ['a', 'b'], unique: true});
In ArangoDB 2.x Foxx provides wrappers around collections and documents (i.e. datasets stored in those collections) called repositories and models respectively. Each repository represents a collection and each model represents a document. ArangoDB 3.0 will provide a new, simplified API that gets rid of this additional complexity by encouraging you to use the underlying collection APIs ArangoDB already provides.
In order to use the index-specific methods on Foxx repositories (like the geo queries for collections with geo indexes) you need to define the repository with the additional indexes
property like so:
'use strict';
var Foxx = require('org/arangodb/foxx').Repository;
var MyModel = Foxx.Model.extend({/* ... */});
var MyRepo = Foxx.Repository.extend({
indexes: [
// same syntax as collection.ensureIndex:
{type: 'hash', fields: ['a', 'b'], unique: true}
]
});
var repo = new MyRepo(applicationContext.collection('my-data'), {
model: MyModel
});
When the repository is instantiated (i.e. new MyRepo(/* ... */)
is invoked), Foxx will ensure the indexes are created as necessary.
Alternatively if you don't want to use Foxx repositories you can simply define the indexes in your setup script after creating the collection, using the regular index API above. Either way you don't need to worry about running the code multiple times: ensureIndex
will do nothing if the index already exists.