我们当前的设置是通过 Spring Data JPA 将 MySQL 作为主要数据源,并使用 Hibernate Search 来索引和搜索数据。我们现在决定使用 Elastic Search 进行搜索,以更好地与其他功能保持一致,此外我们还需要多个服务器共享索引和搜索。
我可以使用 Spring Data ElasticSearch 设置 Elastic,通过 ElasticsearchRepository
轻松进行数据索引和搜索。但现在的挑战是如何将所有现有的 MySQL 记录索引到 Elastic Search 中。 Hibernate Search 提供了一个我们一直使用的 API 来执行此操作 org.hibernate.search.jpa.FullTextEntityManager#createIndexer。但我在 Spring Data ElasticSearch 中找不到方便的解决方案。希望有人可以在这里帮助我或提供一些指示。
有一个similar question here ,但是那里提出的解决方案不太适合我的需求,因为我希望能够索引整个对象,其中字段映射到多个数据库表。
最佳答案
到目前为止,我还没有找到比编写自己的代码将应用程序内的所有 JPA 条目索引到 ES 更好的解决方案,而这个解决方案对我来说效果很好
Pageable page = new PageRequest(0, 100);
Page<Instance> curPage = instanceManager.listInstancesByPage(page); //Get data by page from JPA repo.
long count = curPage.getTotalElements();
while (!curPage.isLast()) {
List<Instance> allInstances = curPage.getContent();
for (Instance instance : allInstances) {
instanceElasticSearchRepository.index(instance); //Index one by one to ES repo.
}
page = curPage.nextPageable();
curPage = instanceManager.listInstancesByPage(page);
}
逻辑非常简单,仅取决于可能需要一段时间的数据量,因此分解为批处理并添加一些消息可能会有所帮助。
关于spring - 通过 Spring Data ElasticSearch 将 Spring Data JPA 条目批量索引到 Elastic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37312415/