Skip to content

Support returning the name of the index an entity was persisted to. #2435

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 38 additions & 28 deletions src/main/asciidoc/reference/elasticsearch-object-mapping.adoc
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
[[elasticsearch.mapping]]
= Elasticsearch Object Mapping

Spring Data Elasticsearch Object Mapping is the process that maps a Java object - the domain entity - into the JSON
representation that is stored in Elasticsearch and back. The class that is internally used for this mapping is the
Spring Data Elasticsearch Object Mapping is the process that maps a Java object - the domain entity - into the JSON representation that is stored in Elasticsearch and back.
The class that is internally used for this mapping is the
`MappingElasticsearcvhConverter`.

[[elasticsearch.mapping.meta-model]]
Expand Down Expand Up @@ -52,21 +52,15 @@ The mapping metadata infrastructure is defined in a separate spring-data-commons
[[elasticsearch.mapping.meta-model.annotations.read-write]]
==== Controlling which properties are written to and read from Elasticsearch

This section details the annotations that define if the value of a property is written to or
read from Elasticsearch.
This section details the annotations that define if the value of a property is written to or read from Elasticsearch.

`@Transient`: A property annotated with this annotation will not be written to the mapping, it's value will not be
sent to Elasticsearch and when documents are returned from Elasticsearch, this property will not be set in the
resulting entity.
`@Transient`: A property annotated with this annotation will not be written to the mapping, it's value will not be sent to Elasticsearch and when documents are returned from Elasticsearch, this property will not be set in the resulting entity.

`@ReadOnlyProperty`: A property with this annotaiton will not have its value written to Elasticsearch, but when
returning data, the proeprty will be filled with the value returned in the document from Elasticsearch. One use case
for this are runtime fields defined in the index mapping.

`@WriteOnlyProperty`: A property with this annotaiton will have its value stored in Elasticsearch but will not be set
with any value when reading document. This can be used for example for synthesized fields which should go into the
Elasticsearch index but are not used elsewhere.
`@ReadOnlyProperty`: A property with this annotaiton will not have its value written to Elasticsearch, but when returning data, the proeprty will be filled with the value returned in the document from Elasticsearch.
One use case for this are runtime fields defined in the index mapping.

`@WriteOnlyProperty`: A property with this annotaiton will have its value stored in Elasticsearch but will not be set with any value when reading document.
This can be used for example for synthesized fields which should go into the Elasticsearch index but are not used elsewhere.

[[elasticsearch.mapping.meta-model.annotations.date-formats]]
==== Date format mapping
Expand Down Expand Up @@ -110,8 +104,7 @@ The following table shows the different attributes and the mapping created from
NOTE: If you are using a custom date format, you need to use _uuuu_ for the year instead of _yyyy_.
This is due to a https://www.elastic.co/guide/en/elasticsearch/reference/current/migrate-to-java-time.html#java-time-migration-incompatible-date-formats[change in Elasticsearch 7].

Check the code of the `org.springframework.data.elasticsearch.annotations.DateFormat` enum for a complete list of
predefined values and their patterns.
Check the code of the `org.springframework.data.elasticsearch.annotations.DateFormat` enum for a complete list of predefined values and their patterns.

[[elasticsearch.mapping.meta-model.annotations.range]]
==== Range types
Expand Down Expand Up @@ -172,12 +165,13 @@ A `FieldNamingStrategy` applies to all entities; it can be overwritten by settin
[[elasticsearch.mapping.meta-model.annotations.non-field-backed-properties]]
==== Non-field-backed properties

Normally the properties used in an entity are fields of the entity class. There might be cases, when a property value
is calculated in the entity and should be stored in Elasticsearch. In this case, the getter method (`getProperty()`) can be
annotated
with the `@Field` annotation, in addition to that the method must be annotated with `@AccessType(AccessType.Type
.PROPERTY)`. The third annotation that is needed in such a case is `@WriteOnlyProperty`, as such a value is only
written to Elasticsearch. A full example:
Normally the properties used in an entity are fields of the entity class.
There might be cases, when a property value is calculated in the entity and should be stored in Elasticsearch.
In this case, the getter method (`getProperty()`) can be annotated with the `@Field` annotation, in addition to that the method must be annotated with `@AccessType(AccessType.Type
.PROPERTY)`.
The third annotation that is needed in such a case is `@WriteOnlyProperty`, as such a value is only written to Elasticsearch.
A full example:

====
[source,java]
----
Expand All @@ -190,6 +184,19 @@ public String getProperty() {
----
====

[[elasticsearch.mapping.meta-model.annotations.misc]]
==== Other property annotations

===== @IndexedIndexName

This annotation can be set on a String property of an entity.
This property will not be written to the mapping, it will not be stored in Elasticsearch and its value will not be read from an Elasticsearch document.
After an entity is persisted, for example with a call to `ElasticsearchOperations.save(T entity)`, the entity
returned from that call will contain the name of the index that an entity was saved to in that property.
This is useful when the index name is dynamically set by a bean, or when writing to a write alias.

Putting some value into such a property does not set the index into which an entity is stored!

[[elasticsearch.mapping.meta-model.rules]]
=== Mapping Rules

Expand Down Expand Up @@ -412,12 +419,15 @@ Looking at the `Configuration` from the <<elasticsearch.mapping.meta-model, prev
[source,java]
----
@Configuration
public class Config extends AbstractElasticsearchConfiguration {
public class Config extends ElasticsearchConfiguration {

@Override
public RestHighLevelClient elasticsearchClient() {
return RestClients.create(ClientConfiguration.create("localhost:9200")).rest();
}
@NonNull
@Override
public ClientConfiguration clientConfiguration() {
return ClientConfiguration.builder() //
.connectedTo("localhost:9200") //
.build();
}

@Bean
@Override
Expand All @@ -428,7 +438,7 @@ public class Config extends AbstractElasticsearchConfiguration {

@WritingConverter <2>
static class AddressToMap implements Converter<Address, Map<String, Object>> {

@Override
public Map<String, Object> convert(Address source) {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.annotations;

import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.data.annotation.Transient;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Annotation to mark a String property of an entity to be filled with the name of the index where the entity was
* stored after it is indexed into Elasticsearch. This can be used when the name of the index is dynamically created
* or when a document was indexed into a write alias.
*
* This can not be used to specify the index where an entity should be written to.
*
* @author Peter-Josef Meisch
* @since 5.1
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Documented
@Field(type = FieldType.Auto) // prevents the property being written to the index mapping
public @interface IndexedIndexName {
}
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,8 @@ public String doIndex(IndexQuery query, IndexCoordinates indexCoordinates) {
Object queryObject = query.getObject();

if (queryObject != null) {
query.setObject(updateIndexedObject(queryObject, IndexedObjectInformation.of(indexResponse.id(),
indexResponse.seqNo(), indexResponse.primaryTerm(), indexResponse.version())));
query.setObject(updateIndexedObject(queryObject, new IndexedObjectInformation(indexResponse.id(),
indexResponse.index(), indexResponse.seqNo(), indexResponse.primaryTerm(), indexResponse.version())));
}

return indexResponse.id();
Expand Down Expand Up @@ -629,7 +629,8 @@ protected List<IndexedObjectInformation> checkForBulkOperationFailure(BulkRespon
}

return bulkResponse.items().stream()
.map(item -> IndexedObjectInformation.of(item.id(), item.seqNo(), item.primaryTerm(), item.version()))
.map(item -> new IndexedObjectInformation(item.id(), item.index(), item.seqNo(), item.primaryTerm(),
item.version()))
.collect(Collectors.toList());

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ protected <T> Mono<Tuple2<T, IndexResponseMetaData>> doIndex(T entity, IndexCoor
return Mono.just(entity) //
.zipWith(//
Mono.from(execute((ClientCallback<Publisher<IndexResponse>>) client -> client.index(indexRequest))) //
.map(indexResponse -> new IndexResponseMetaData(indexResponse.id(), //
.map(indexResponse -> new IndexResponseMetaData(
indexResponse.id(), //
indexResponse.index(), //
indexResponse.seqNo(), //
indexResponse.primaryTerm(), //
indexResponse.version() //
Expand Down Expand Up @@ -139,8 +141,12 @@ public <T> Flux<T> saveAll(Mono<? extends Collection<? extends T>> entitiesPubli
.flatMap(indexAndResponse -> {
T savedEntity = entities.entityAt(indexAndResponse.getT1());
BulkResponseItem response = indexAndResponse.getT2();
updateIndexedObject(savedEntity, IndexedObjectInformation.of(response.id(), response.seqNo(),
response.primaryTerm(), response.version()));
updateIndexedObject(savedEntity, new IndexedObjectInformation( //
response.id(), //
response.index(), //
response.seqNo(), //
response.primaryTerm(), //
response.version()));
return maybeCallbackAfterSave(savedEntity, index);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,12 @@ public String doIndex(IndexQuery query, IndexCoordinates index) {
Object queryObject = query.getObject();

if (queryObject != null) {
query.setObject(updateIndexedObject(queryObject, IndexedObjectInformation.of(indexResponse.getId(),
indexResponse.getSeqNo(), indexResponse.getPrimaryTerm(), indexResponse.getVersion())));
query.setObject(updateIndexedObject(queryObject, new IndexedObjectInformation( //
indexResponse.getId(), //
indexResponse.getIndex(), //
indexResponse.getSeqNo(), //
indexResponse.getPrimaryTerm(), //
indexResponse.getVersion())));
}

return indexResponse.getId();
Expand Down Expand Up @@ -369,10 +373,15 @@ protected List<IndexedObjectInformation> checkForBulkOperationFailure(BulkRespon
return Stream.of(bulkResponse.getItems()).map(bulkItemResponse -> {
DocWriteResponse response = bulkItemResponse.getResponse();
if (response != null) {
return IndexedObjectInformation.of(response.getId(), response.getSeqNo(), response.getPrimaryTerm(),
return new IndexedObjectInformation( //
response.getId(), //
response.getIndex(), //
response.getSeqNo(), //
response.getPrimaryTerm(), //
response.getVersion());
} else {
return IndexedObjectInformation.of(bulkItemResponse.getId(), null, null, null);
return new IndexedObjectInformation(bulkItemResponse.getId(), bulkItemResponse.getIndex(), null, null,
null);
}

}).collect(Collectors.toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ public <T> Flux<T> saveAll(Mono<? extends Collection<? extends T>> entitiesPubli
BulkItemResponse bulkItemResponse = indexAndResponse.getT2();

DocWriteResponse response = bulkItemResponse.getResponse();
updateIndexedObject(savedEntity, IndexedObjectInformation.of(response.getId(), response.getSeqNo(),
response.getPrimaryTerm(), response.getVersion()));
updateIndexedObject(savedEntity, new IndexedObjectInformation(response.getId(), response.getIndex(),
response.getSeqNo(), response.getPrimaryTerm(), response.getVersion()));

return maybeCallbackAfterSave(savedEntity, index);
});
Expand Down Expand Up @@ -255,10 +255,11 @@ protected <T> Mono<Tuple2<T, IndexResponseMetaData>> doIndex(T entity, IndexCoor
return Mono.just(entity).zipWith(doIndex(request) //
.map(indexResponse -> new IndexResponseMetaData( //
indexResponse.getId(), //
indexResponse.getIndex(), //
indexResponse.getSeqNo(), //
indexResponse.getPrimaryTerm(), //
indexResponse.getVersion() //
))); //
)));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -408,23 +408,29 @@ protected <T> T updateIndexedObject(T entity, IndexedObjectInformation indexedOb
ElasticsearchPersistentProperty idProperty = persistentEntity.getIdProperty();

// Only deal with text because ES generated Ids are strings!
if (indexedObjectInformation.getId() != null && idProperty != null && idProperty.isReadable()
if (indexedObjectInformation.id() != null && idProperty != null && idProperty.isReadable()
&& idProperty.getType().isAssignableFrom(String.class)) {
propertyAccessor.setProperty(idProperty, indexedObjectInformation.getId());
propertyAccessor.setProperty(idProperty, indexedObjectInformation.id());
}

if (indexedObjectInformation.getSeqNo() != null && indexedObjectInformation.getPrimaryTerm() != null
if (indexedObjectInformation.seqNo() != null && indexedObjectInformation.primaryTerm() != null
&& persistentEntity.hasSeqNoPrimaryTermProperty()) {
ElasticsearchPersistentProperty seqNoPrimaryTermProperty = persistentEntity.getSeqNoPrimaryTermProperty();
// noinspection ConstantConditions
propertyAccessor.setProperty(seqNoPrimaryTermProperty,
new SeqNoPrimaryTerm(indexedObjectInformation.getSeqNo(), indexedObjectInformation.getPrimaryTerm()));
new SeqNoPrimaryTerm(indexedObjectInformation.seqNo(),
indexedObjectInformation.primaryTerm()));
}

if (indexedObjectInformation.getVersion() != null && persistentEntity.hasVersionProperty()) {
if (indexedObjectInformation.version() != null && persistentEntity.hasVersionProperty()) {
ElasticsearchPersistentProperty versionProperty = persistentEntity.getVersionProperty();
// noinspection ConstantConditions
propertyAccessor.setProperty(versionProperty, indexedObjectInformation.getVersion());
propertyAccessor.setProperty(versionProperty, indexedObjectInformation.version());
}

var indexedIndexNameProperty = persistentEntity.getIndexedIndexNameProperty();
if (indexedIndexNameProperty != null) {
propertyAccessor.setProperty(indexedIndexNameProperty, indexedObjectInformation.index());
}

// noinspection unchecked
Expand Down Expand Up @@ -791,8 +797,9 @@ public T doWith(@Nullable Document document) {

T entity = reader.read(type, documentAfterLoad);

IndexedObjectInformation indexedObjectInformation = IndexedObjectInformation.of( //
IndexedObjectInformation indexedObjectInformation = new IndexedObjectInformation( //
documentAfterLoad.hasId() ? documentAfterLoad.getId() : null, //
documentAfterLoad.getIndex(), //
documentAfterLoad.hasSeqNo() ? documentAfterLoad.getSeqNo() : null, //
documentAfterLoad.hasPrimaryTerm() ? documentAfterLoad.getPrimaryTerm() : null, //
documentAfterLoad.hasVersion() ? documentAfterLoad.getVersion() : null); //
Expand Down
Loading