Last updated by Shailen 5 years ago

Mapping conventions

First please familiarise yourself with some essential Compass mapping concepts.

The easiest way to map a class to the search index is by declaring

static searchable = true

which maps all "mappable" properties in the class using built-in rules:

  1. Simple property types like numbers, dates and strings, or a collection of, are mapped as searchable-properties, which becomes the searchable text in the index.
  2. Non-embedded domain class properties or element type if a collection are mapped as searchable-references as long as they are searchable too.
  3. Embedded domain class properties are mapped as searchable-components as long as they are not specifically non-searchable.

The mapping DSL gives you more flexibility.

For example you can limit the searchable properties and override the conventions a per-class-property basis, and define class-level mapping options.

Example

Let's take this class to explain the built-in mapping conventions:

class Post {
    static searchable = true
    static embedded = ['metadata']
    static hasMany = [comments: Comment]
    String category, title, post
    User author
    Metadata metadata
    Date createdAt
}

Simple type properties become the searchable text in the index

The simple type properties category, title, post and createdAt are mapped as searchable-properties.

As is the case with searchable-properties, the values of these properties becomes searchable text in the index, in fields named after the property.

Additionally an "all" field is created which combines all searchable text for the object.

Therefore you can search for "title:grails" or "category:javascript" to target those specific fields, whereas if you search for just "grails" it will match any text in any searchable field.

Non-embedded domain class properties become searchable references

As long as associated domain classes are searchable too, they are normally mapped as searchable-references.

Here, if User and Comment are searchable, then the user and comments properties are both mapped as searchable-references.

This means that when an object is returned from the index as a search hit, it can be returned along with it's associated domain objects (and domain object collections) set on it.

Embedded domain class properties become searchable components

The embedded domain class property metadata is mapped as a searchable-component so any search query that matches the Post 's metadata will return that Post instance.

You have the choice of whether to declare the Metadata class as searchable:

  • If you don't declare it as searchable, the class is automatically mapped as a non-root class with the built-in conventions
  • To make Metadata non-searchable you can add static searchable = false
  • Otherwise whatever value of Metadata's static searchable property (or one of native the Compass mapping choices) defines how the class is mapped