弹性数据弹性搜索搜索多个索引 [英] spring-data-elasticsearch searching over multiple indices

查看:533
本文介绍了弹性数据弹性搜索搜索多个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网页上有一个搜索字段,这个搜索字段应该搜索多个指数。
我可以搜索一个indice没有问题,如在spring-data-elasticsearch的文档中所述。

i have a searchfield on my page and this searchfield should search over more than one indice. I can search for one indice without a problem, like described in the documentation of spring-data-elasticsearch.

但是,如果我搜索,例如 Foo,我想按照相关性排列以下列表:

But if i search, as example for "Foo", i want to have the following list as result ordered by relevance:

{ title: "Foo" } -> Entity: Sample
{ name: "FooTest" } -> Entity: Test
{ title: "FooSample2" } -> Entity: Sample
// ...and so on
// The entities are not part of the same parent. So, they are complete different.

为此,我无法找到有助于我的文档中的任何内容。

For this i couldn't find anything in documentation that would help me.

可以帮助吗?

编辑:

final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchAllQuery())
                .withIndices("game-index", "lets-play-index", "video-index", "genre-index", "platform-index", "user-index")
                .withPageable(new PageRequest(0, 10))
                .build();

            // when
            final Page<SearchResult> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SearchResult.class, new SearchResultMapper() {

                @Override
                public <T> FacetedPage<T> mapResults(
                                                        final SearchResponse response,
                                                        final Class<T> clazz,
                                                        final Pageable pageable) {
                    LoggerUtil.get(this.getClass())
                        .debug(response.toString());
                    LoggerUtil.get(this.getClass())
                        .debug(response.getHits()
                            .toString());
                    LoggerUtil.get(this.getClass())
                        .debug("TotalHits: " + response.getHits()
                            .totalHits());

                    final long totalHits = response.getHits()
                        .totalHits();
                    final List<T> results = new ArrayList<T>();
                    for (final SearchHit hit : response.getHits()) {
                        LoggerUtil.get(this.getClass())
                            .debug(hit.sourceAsString());
                        if (hit != null) {
                            final T result = null;
                            /*
                             * if (!Strings.isNullOrEmpty(hit.sourceAsString()))
                             * { result = mapEntity(hit.sourceAsString(),
                             * clazz); } else { result =
                             * mapEntity(hit.getFields() .values(), clazz); }
                             */
                            // setPersistentEntityId(result, hit.getId(),
                            // clazz);
                            results.add(result);
                        }
                    }
                    final List<FacetResult> facets = new ArrayList<FacetResult>();
                    if (response.getFacets() != null) {
                        for (final Facet facet : response.getFacets()) {
                            final FacetResult facetResult = DefaultFacetMapper.parse(facet);
                            if (facetResult != null) {
                                facets.add(facetResult);
                            }
                        }
                    }

                    return new FacetedPageImpl<T>(results, pageable, totalHits, facets);
                }

            });

SearchResultMapper内部的响应如下:

the response inside of SearchResultMapper is the follwing:

{
  "took" : 5,
  "timed_out" : false,
  "_shards" : {
    "total" : 30,
    "successful" : 30,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

如果我用简单的搜索:

final Class<?> clazz = Class.forName(className);

            final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(getQueryBuilderForQuery(query))
                .build();
            final List<?> results = elasticsearchTemplate.queryForList(searchQuery, clazz);

它的工作原理,我得到很多结果。这意味着我的索引正在工作。

it works and i get many results. that means my index is working.

我绝对不知道我能做什么。非常感谢。

i have definitly no idea what i can do. thanks a lot.

推荐答案

对不起,这是已经支持

下面的代码,它应该是工作...

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

如果索引中有不同的结构,那么可以使用以下的elasticsearchTemplate方法

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 :-)

这篇关于弹性数据弹性搜索搜索多个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆