问题
Updated Spring boot to 2.2.X from 2.1.X and elastic search to 6.8.X from 6.3.X.
Got mapping exception, to resolve Mapping exception, renamed document variable to myDocument.
Now on elasticSearchRepo.SaveAll(objectTosave)
value is not persisted in document.
Other properties like id, category are present in the document.
Is there any way to have different fieldName and jsonProperty?
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
@NoArgsConstructor
@Data
@EqualsAndHashCode
@ToString
@Document(indexName="my_document_index", type="information", createIndex=false)
@JsonIgnoreProperties(ignoreUnKnown = true)
@JsonInclude(Include.NON_NULL)
public class MyInstance
{
@Field
private String id;
@Field
private String category;
@Field
@JsonProperty("document")
private MyObject mydocument;
/** JSON Creator **/
@JsonCreator
public MyInstance(@JsonProperty("id") id, @JsonProperty("category") category,
@JsonProperty("document") mydocument)
{
this.id = id;
this.category = category;
this.mydocument = mydocument;
}
}
回答1:
No need to annotate the id
property with @Field
, you should rather put @Id
there. Although this is not needed, as the name of the property is enough, it makes it clearer what it is.
As for the mydocument
property not being persisted: It is but in Elasticsearch with the name mydocument. The @JsonProperty("document")
defines the name of this property in JSON when mapped by Jackson, when you get this in over a REST endpoint for example. Renaming to mydocument
inhibits the error that the property is interpreted as id property.
But I think you want to have as document in Elasticsearch as well. You can define the name of a property in Elasticsearch by setting it in the @Field
annotation:
@Document(indexName="my_document_index", createIndex=false)
public class MyInstance
{
@Id
private String id;
@Field
private String category;
@Field(name = "document")
@JsonProperty("document")
private MyObject mydocument;
}
来源:https://stackoverflow.com/questions/62714962/spring-boot2-2-x-spring-elastic-search6-8-x-different-jsonproperty-and-f