| h4. Basics |
| |
| MongoDB doesn't require that you specify indices to query, but like a relational database without specifying indices your queries will be significantly slower. |
| |
| With that in mind it is important to specify the properties you plan to query using the mapping block: |
| |
| {code} |
| class Person { |
| String name |
| static mapping = { |
| name index:true |
| } |
| } |
| {code} |
| |
| With the above mapping a MongoDB index will be automatically created for you. You can customize the index options using the @indexAttributes@ configuration parameter: |
| |
| {code} |
| class Person { |
| String name |
| static mapping = { |
| name index:true, indexAttributes: [unique:true, dropDups:true] |
| } |
| } |
| {code} |
| |
| You can use MongoDB [Query Hints|http://docs.mongodb.org/manual/reference/operator/meta/hint/] by passing the @hint@ argument to any dynamic finder: |
| |
| {code} |
| def people = Person.findByName("Bob", [hint:[name:1]]) |
| {code} |
| |
| Or in a criteria query using the query "arguments" method |
| |
| {code} |
| Person.withCriteria { |
| eq 'firstName', 'Bob' |
| arguments hint:["firstName":1] |
| } |
| {code} |
| |
| h4. Compound Indices |
| |
| MongoDB supports the notion of [compound keys|http://docs.mongodb.org/manual/core/index-compound/]. GORM for MongoDB enables this feature at the mapping level using the @compoundIndex@ mapping: |
| |
| {code} |
| class Person { |
| ... |
| static mapping = { |
| compoundIndex name:1, age:-1 |
| } |
| } |
| {code} |
| |
| As per the MongoDB docs 1 is for ascending and -1 is for descending. |
| |
| h4. Indexing using the 'index' method |
| |
| In addition to the convenience features described above you can use the @index@ method to define any index you want. For example: |
| |
| {code} |
| static mapping = { |
| index( ["person.address.postCode":1], [unique:true] ) |
| } |
| {code} |
| |
| In the above example I define an index on an embedded attribtue of the document. In fact what arguments you pass to the @index@ method get passed to the underlying MongoDB [createIndex|http://api.mongodb.org/java/2.12/com/mongodb/DBCollection.html#createIndex(com.mongodb.DBObject,%20com.mongodb.DBObject)] method. |