通过 Spring Data ElasticSearch 将 Spring Data JPA 条目批量索引到 Elastic

Batch indexing Spring Data JPA entries to Elastic through Spring Data ElasticSearch

我们当前的设置是通过 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);
}

逻辑非常简单,只是取决于可能需要一段时间的数据量,因此分解成批次并添加一些消息可能会有所帮助。