我需要将文档存储到Elasticsearch索引中,因此我定义了一个映射。从我的Java客户端,我需要为其提供类似于Compony类的pojo。它具有很多重复的值。我可以使用对象合成模式来解决这个问题,但是Elasticsearch无法处理这种结构,因此它期望一种扁平的结构。
class Company {
private String postalstreetName;
private String postalHouseNumer;
private String postalHouseLetter;
private String postalHouseNumberAddition;
private String postalZipCode;
private String postalCity;
private String postalCountry;
private String visitorstreetName;
private String visitorHouseNumer;
private String visitorHouseLetter;
private String visitorHouseNumberAddition;
private String visitorZipCode;
private String visitorCity;
private String visitorCountry;
private String establishmentstreetName;
private String establishmentHouseNumer;
private String establishmentHouseLetter;
private String establishmentHouseNumberAddition;
private String establishmentZipCode;
private String establishmentCity;
private String establishmentCountry;
}
我实际上希望像下面的pojo,并且以某种命名结构自动生成上面的pojo。
class Address {
private String streetName;
private String houseNumer;
private String houseLetter;
private String houseNumberAddition;
private String zipCode;
private String city;
private String country;
}
class Company {
private Address postalAddress;
private Address visitorAddress;
private Address establishmentAddress;
}
有人知道是否可以通过类似对象组成的pojo,自动为所有字段创建一个扁平化的pojo,这是否可行?
答案 0 :(得分:0)
我为我的问题找到了解决方案。 Elasticsearch期望具有第一个示例中的结构的json对象。因此,我要做的是将@JsonUnwrapped
添加到带有前缀值的字段中,所以我的Company类如下所示:
class Company {
@JsonUnwrapped(prefix = "postal")
private Address postalAddress;
@JsonUnwrapped(prefix = "visitor")
private Address visitorAddress;
@JsonUnwrapped(prefix = "Establishment")
private Address establishmentAddress;
}
结果将是:
{
"postalStreetName":"",
"postalHouseNumer":"",
"postalHouseLetter":"",
"postalHouseNumberAddition":"",
"postalCity":"",
"postalCountry":"",
"visitorStreetName":"",
"visitorHouseNumer":"",
"visitorHouseLetter":"",
"visitorHouseNumberAddition":"",
"visitorCity":"",
"visitorCountry":"",
"establishmentStreetName":"",
"establishmentHouseNumer":"",
"establishmentHouseLetter":"",
"establishmentHouseNumberAddition":"",
"establishmentCity":"",
"establishmentCountry":""
}
所以我不需要魔术般地创建那些pojo,因为杰克逊可以创建我需要的json文件。