該賞金過期4天。這個問題的答案有資格獲得 50聲望獎勵。 亞歷克斯想引起對這個問題的更多關注。
給定的
private Map<String, ZonedDateTime> timePoints = new HashMap<>();
如何提示 spring-data 欄位的型別?
當直接放在字典上時,如果鍵和值是日期字串,轉換器會嘗試將它們一起決議。
@Field(FieldType.Date)
private Map<String, ZonedDateTime> timePoints = new HashMap<>();
未提供欄位型別時,會出現以下錯誤:
Type .. of property .. is a TemporalAccessor class but has neither a @Field annotation defining the date type nor a registered converter for writing! It will be mapped to a complex object in Elasticsearch!
uj5u.com熱心網友回復:
將注釋放在屬性上,例如
@Field(FieldType.Date)
private Map<String, ZonedDateTime> timePoints = new HashMap<>();
不能作業,因為 aMap不是時間型別,因此不能這樣轉換。
如果您離開注釋,Map<String, ZonedDateTime>則將被解釋為一個物件。例如,如果您有
Map<String, ZonedDateTime> map = new Map();
map.put("utc", ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("UTC")));
map.put("paris", ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Europe/Paris")));
然后在使用 Spring Data Elasticsearch 存盤此物件時,這將嘗試創建一個物件以發送到 Elasticsearch(JSON 表示),如下所示:
{
"utc": {
},
"paris": {
}
}
應該表示時間的內部物件存盤為嵌套物件,而不是某些轉換后的值,因為無法將欄位型別添加到地圖的值中 - 您會在日志中看到有關 的警告。
但是Map在 Elasticsearch 中使用 a作為屬性是有問題的。鍵被解釋為子物件的屬性。之前無法定義索引中型別的映射,因為不知道這些屬性可以具有哪些可能的名稱。在我的示例中,它是“utc”和“paris”,但它可以是任何字串。Elasticsearch 會將這些值中的每一個作為動態映射欄位添加到索引中。這可能會導致映射爆炸,因此 Elasticsearch 將索引中的欄位數限制為默認值 1000。您可以重新考慮在 Elasticsearch 中存盤資料的方式。
如果您想堅持使用 a Map,則需要撰寫一個自定義轉換器,該轉換器能夠將您的轉換Map<String, ZonedDateTime>為 aMap<String, String>并回傳。
uj5u.com熱心網友回復:
不知道我是否 100% 理解您的問題,但您應該嘗試實作 Persistable 并添加帶注釋的屬性,這些值將自動為存盤在 Elasticsearch 中的物體維護,如下例所示:
@Document(indexName = "person")
public class Person implements Persistable<Long> {
@Nullable @Id
private Long id;
@CreatedDate
@Nullable @Field(type = FieldType.Date, format = DateFormat.basic_date_time)
private Instant created;
@Nullable @CreatedBy
private String createdBy;
@LastModifiedDate
@Nullable @Field(type = FieldType.Date, format = DateFormat.basic_date_time)
private Instant lastModified;
@Nullable @LastModifiedBy
private String lastModifiedBy;
@Nullable
public Long getId() { return id; }
@Override
public boolean isNew() { return id == null || (createdBy == null && created == null); }
// other properties, getter, setter...
}
uj5u.com熱心網友回復:
從檔案看來,您可能需要創建自定義轉換器并將它們添加到自定義ElasticsearchCustomConversionsbean 中。以下轉換器似乎有效:
@Bean
public ElasticsearchCustomConversions elasticsearchCustomConversions() {
return new ElasticsearchCustomConversions(
Arrays.asList(new ZonedDateTimeWriteConverter(), new ZonedDateTimeReadConverter()));
}
@WritingConverter
static class ZonedDateTimeWriteConverter implements Converter<ZonedDateTime, String> {
@Override
public String convert(ZonedDateTime source) {
return DateTimeFormatter.ISO_ZONED_DATE_TIME.format(source);
}
}
@ReadingConverter
static class ZonedDateTimeReadConverter implements Converter<String, ZonedDateTime> {
@Override
public ZonedDateTime convert(String source) {
return ZonedDateTime.from(DateTimeFormatter.ISO_ZONED_DATE_TIME.parse(source));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/348852.html
