spring-data-elasticsearch searching over multiple indices

谁说胖子不能爱 提交于 2019-12-03 08:52:25

Sorry this is already supported

try below code, it should be working...

however below code is for where you have same structure in Entity and elasticsearch document

    @Test
    public void shouldTestResultsAcrossMultipleIndices() {
    // given
    String documentId1 = randomNumeric(5);
    SampleEntity sampleEntity1 = new SampleEntityBuilder(documentId1).message("some message")
            .version(System.currentTimeMillis()).build();

    IndexQuery indexQuery1 = new IndexQueryBuilder().withId(sampleEntity1.getId())
            .withIndexName("test-index-1")
            .withObject(sampleEntity1)
            .build();

    String documentId2 = randomNumeric(5);
    SampleEntity sampleEntity2 = new SampleEntityBuilder(documentId2).message("some test message")
            .version(System.currentTimeMillis()).build();

    IndexQuery indexQuery2 = new IndexQueryBuilder().withId(sampleEntity2.getId())
            .withIndexName("test-index-2")
            .withObject(sampleEntity2)
            .build();

    elasticsearchTemplate.bulkIndex(Arrays.asList(indexQuery1, indexQuery2));
    elasticsearchTemplate.refresh("test-index-1", true);
    elasticsearchTemplate.refresh("test-index-2", true);

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(matchAllQuery())
            .withIndices("test-index-1", "test-index-2")
            .build();
    // when
    List<SampleEntity> sampleEntities = elasticsearchTemplate.queryForList(searchQuery, SampleEntity.class);
    // then
    assertThat(sampleEntities.size(), is(equalTo(2)));
}

if you have different structure in the index then you can use below method of elasticsearchTemplate

  Page<T> queryForPage(SearchQuery query, Class<T> clazz, SearchResultMapper mapper);

still confused ? happy to help :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!