Java elasticsearch spring-data设置不同的索引字段名称

时间:2016-01-05 17:00:24

标签: java spring elasticsearch spring-data spring-data-elasticsearch

我将elasticsearch java-api与spring-data结合使用,并且在索引文档时遇到了问题。 我想为索引字段使用不同的名称。这意味着与java代码不同:

domainObject的:

@Document(indexName = "testindex", type = "message")
public class MessageObject {

@Id
private String  unid;

@FieldNameInElasticIndex(value = "javaMessage")  // I want anything like that
private String message;

private String secondMessage;

private String thirdMessage;

...

getters & setters

...

}

接口:

public interface MessageObjectRepository extends ElasticsearchRepository<MessageObject, Long> {


}

服务:

@Component
public class MessageService {

    @Autowired
    private MessageObjectRepository repository;


    public void addRegistrationObject(MessageObject msg) {

        repository.save(msg);
    }
}

...所以

是否可以更改名称,使索引看起来像:

"hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "testindex",
        "_type": "message",
        "_id": "00113B325ED357B7C1257E2D001D5B4B",
        "_score": 1,
        "_source": {
          "unid": "00113B325ED357B7C1257E2D001D5B4B",
          "javaMessage": "Hello",  // <--- this is what I want (javaMessage)
          "secondMessage": null,
          "thirdMessage": "Third",

而不是

"hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "testindex",
        "_type": "message",
        "_id": "00113B325ED357B7C1257E2D001D5B4B",
        "_score": 1,
        "_source": {
          "unid": "00113B325ED357B7C1257E2D001D5B4B",
          "message": "Hello",  // <--- this is NOT what I want (java name: message)
          "secondMessage": null,
          "thirdMessage": "Third",

2 个答案:

答案 0 :(得分:2)

这个想法只是在字段上使用@JsonProperty注释,并在JSON序列化期间提供您要使用的名称:

@JsonProperty("javaMessage")
private String message;

答案 1 :(得分:0)

Val发布了正确的解决方案:

@JsonProperty("name")