2016-02-19 49 views
5

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

我正在使用“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; 
    } 
} 

我的仓库类:

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

我的应用程序代码:

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执行查询(保存后):

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

预期结果:

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

得到的结果:

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

你可以看到我在结果得到了_id是, “_id”: “AVL7WcnOXA6CTVbl_1Yl”。但我希望_id字段等同于eventPk值。

请帮忙。谢谢。

回答

2

的问题是在你的getter应该public与同一类型@Id领域:

public long getEvent_pk() { 
    return event_pk; 
} 
0

如果使用String类型的ID与字段名ID可以映射它

private String id; 

这工作。看起来像只接受字符串类型ID字段。

相关问题