Skip to content

Document (aka mapping)

Roughly speaking Document represents Elasticsearch's mapping. However, it is possible to merge multiple documents into a single mapping.

It is convenient to describe Document subclasses as singleton objects.

Read more about Elasticsearch mapping types

Simple fields

General way

You can use field method to describe a field in a document:


Fields can be used when building a search query:


Using shortcuts

There are some nice shortcuts for popular field types. You don't need to import all those field types:


Full list of available shortcuts can be found here

Enums

It is possible to map field values to kotlin enums. Use enum extension function for that:


Now you are able to use enum variants in your search queries:


Sub fields

It is possible to define sub-fields for any simple field:


Sub-fields also can be used in search queries:


Note

It is a mistake to use sub-fields twice. Following example will fail at runtime.


Show an error
Exception in thread "main" java.lang.ExceptionInInitializerError
        at samples.document.subfields.mistake.MistakeKt.main(Mistake.kt:17)
        at samples.document.subfields.mistake.MistakeKt.main(Mistake.kt)
Caused by: java.lang.IllegalStateException: Field [description] has already been initialized as [about]
        at dev.evo.elasticmagic.SubFields$UnboundSubFields.provideDelegate(Document.kt:363)
        at samples.document.subfields.mistake.UserDoc.<clinit>(Mistake.kt:13)
        ... 2 more

Object fields

Object

Object type just represents a hierarchical structure. It is similar to sub-fields but every field in a sub-document can have its own source value:


Note

The same as with the sub-fields sub-document should not be a singleton object.

Read more:

Nested

Using nested type it you can work with sub-documents independently. In the example below we find all users that have a moderator role with both article and order permissions:


If we tried to make it with object type, we would find users that have a moderator role with article permission and view role with order permission.

Read more:

Parent-child relationship

Parent/child relationship allows you to define a link between documents inside an index.

Join field


Read more:

Meta fields

Elasticsearch mapping has metadata fields. Some of those fields can be customized. In following example we make a value for _routing field required and keep only name field in document source:


Now you must provide the required routing value when indexing documents otherwise Elasticsearch will throw routing_missing_exceptions.

Merge multiple documents

To create a mapping for multiple documents you can use mergeDocuments function. Documents that are merged should not contradict each other.


Resulting document can be used when creating an index or updating an existing mapping.