如何使用Spring Data为Elastic Search设置_id字段

Bha*_*ath 5 spring-data spring-data-elasticsearch

我使用@Id注释在我的实体中定义了一个字段.但是这个@Id没有映射到弹性搜索文档中的_id._id值由Elastic Search自动生成.

我正在使用"org.springframework.data.annotation.Id;".这是@Id支持spring-data-es吗?

我的实体:

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(
    indexName = "my_event_db", type = "my_event_type"
)
public class EventTransactionEntity {
   @Id
   private long event_pk;

   public EventTransactionEntity(long event_pk) {
      this.event_pk = event_pk;
   }

   private String getEventPk() {
      return event_pk;
   }
}
Run Code Online (Sandbox Code Playgroud)

我的存储库类:

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import com.softwareag.pg.pgmen.events.audit.myPackage.domain.EventTransactionEntity;
public interface EventTransactionRepository extends ElasticsearchRepository<EventTransactionEntity, Long> {
}
Run Code Online (Sandbox Code Playgroud)

我的申请代码:

public class Application {
   @Autowired
   EventTransactionRepository eventTransactionRepository;

   public void setEventTransactionRepository(EventTransactionRepository repo)  
   {
       this.eventTransactionRepository = repo;
   }

   public void saveRecord(EventTransactionEntity entity) {
       eventTransactionRepository.save(entity); 
   }

    public void testSave() {
       EventTransactionEntity entity = new EventTransactionEntity(12345);
       saveRecord(entity);
   }
}
Run Code Online (Sandbox Code Playgroud)

执行ES查询(保存后):

http://localhost:9200/my_event_db/my_event_type/_search
Run Code Online (Sandbox Code Playgroud)

预期结果:

{
"hits": {
  "total": 1,
  "max_score": 1,
  "hits": [
  {
    "_index": "my_event_db",
    "_type": "my_event_type",
    "_id": "12345",
    "_score": 1,
    "_source": {
      "eventPk": 12345,
    }
  }]
}}
Run Code Online (Sandbox Code Playgroud)

获得的结果:

{
"hits": {
  "total": 1,
  "max_score": 1,
  "hits": [
  {
    "_index": "my_event_db",
    "_type": "my_event_type",
    "_id": "AVL7WcnOXA6CTVbl_1Yl",
    "_score": 1,
    "_source": {
      "eventPk": 12345,
    }
  }]
}}
Run Code Online (Sandbox Code Playgroud)

你可以看到我在结果中得到的_id是"_id":"AVL7WcnOXA6CTVbl_1Yl".但我希望_id字段等于eventPk值.

请帮忙.谢谢.

Ore*_*est 2

问题出在你的 getter 中,它应该public与字段具有相同的类型@Id:

public long getEvent_pk() {
   return event_pk;
}
Run Code Online (Sandbox Code Playgroud)