5
votes

I have defined a field in my entity using @Id annotation. But this @Id is not mapping to the _id in Elastic Search Documents. The _id values are auto generated by Elastic Search.

I am using "org.springframework.data.annotation.Id;". Is this @Id supported by spring-data-es?

My entity:

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;
   }
}

My Repository Class:

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

My Application Code:

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);
   }
}

ES Query executed (After Save):

http://localhost:9200/my_event_db/my_event_type/_search

Expected Result:

{
"hits": {
  "total": 1,
  "max_score": 1,
  "hits": [
  {
    "_index": "my_event_db",
    "_type": "my_event_type",
    "_id": "12345",
    "_score": 1,
    "_source": {
      "eventPk": 12345,
    }
  }]
}}

Obtained Result:

{
"hits": {
  "total": 1,
  "max_score": 1,
  "hits": [
  {
    "_index": "my_event_db",
    "_type": "my_event_type",
    "_id": "AVL7WcnOXA6CTVbl_1Yl",
    "_score": 1,
    "_source": {
      "eventPk": 12345,
    }
  }]
}}

You could see the _id I got in my result was, "_id": "AVL7WcnOXA6CTVbl_1Yl". But I would expect the _id field to be equivalent to eventPk value.

Please help. Thanks.

2

2 Answers

2
votes

The problem is in your getter it should be public with same type as @Id field:

public long getEvent_pk() {
   return event_pk;
}
0
votes

You can map it if you use a String type id with field name id

private String id;

This worked. Looks like only string type id field accepted.