ElasticSerch同时查询多个索引
一、许多场景需要查询的结果不在一个索引里面,但是elasticseach不能像别的数据库一样进行联查,所以我们可以同时查询多个索引的字段来满足需求
1、查询DSL语句
GET /_search { "size": 20, "query": { "bool": { "minimum_should_match": 1, "should": [ { "bool": { "must": [ { "term": { "_index": { "value": "索引一" } } }, { "term": { "索引一字段": { "value": "少年歌行" } } } ] } }, { "bool": { "must": [ { "term": { "_index": { "value": "索引二" } } } ], "filter": { "term": { "索引而字段": "少年歌行" } } } } ] } }, "sort": [ { "_index": { "order": "desc" } }, { "_score": { "order": "desc" } } ] }
2、java
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); QueryBuilder queryBuilder1 = QueryBuilders.boolQuery(). .must(QueryBuilders.termQuery("_index", "索引一")); QueryBuilder queryBuilder2 = QueryBuilders.boolQuery(). .must(QueryBuilders.termQuery("_index", "索引二"); boolQueryBuilder.minimumShouldMatch(1) .should(bookQueryBuilder) .should(extensionQueryBuilder); Query query = new NativeSearchQueryBuilder() .withSourceFilter(new FetchSourceFilter(new String[] {}, excludes)) .withQuery(boolQueryBuilder) .withSort(SortBuilders.fieldSort("_index").order(SortOrder.DESC)) .withSort(SortBuilders.fieldSort("_score").order(SortOrder.DESC)) .withPageable(PageRequest.of(page - 1, size)) .build();
SearchHits<SearchResultDto> search = esRestTemplate.search(query, SearchResultDto.class, IndexCoordinates.of("索引一", "索引二"));