更改前:

@ApiOperation("分页排序")
    @GetMapping("pageAndSort/{page}/{size}")
    public Page<Hero> pageAndSort(@PathVariable Integer page,@PathVariable Integer size){
        //构建本地查询对象
        NativeSearchQueryBuilder query = new NativeSearchQueryBuilder();
        //
        PageRequest pageRequest = PageRequest.of(page, size);

        query.withPageable(pageRequest);
        query.withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC));

        SearchHits<Hero> search = elasticTemplate.search(query.build(), Hero.class);
        List<Hero> blogs = new ArrayList<>();
        for (SearchHit<Hero> hero : search) {
            blogs.add(hero.getContent());
        }
        PageImpl<Hero> heroes = new PageImpl<>(blogs, pageRequest, search.getTotalHits());
        return heroes;
    }

错误提示信息:Elasticsearch exception [type=illegal_argument_exception, reason=Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [createTime] in order to load field data by uninverting the inverted index. Note that this can use significant memory.]

翻译过来就是:对于需要每个文档字段数据(如聚合和排序)的操作,文本字段没有进行优化,因此这些操作在默认情况下是禁用的。请使用关键字字段代替。或者,在[createTime]上设置fielddata=true,以便通过反求倒排索引来加载字段数据。注意,这可能会使用有效内存。]

es中,text类型的字段使用一种叫做fielddata的查询时内存数据结构。当字段被排序,聚合或者通过脚本访问时这种数据结构会被创建。它是通过从磁盘读取每个段的整个反向索引来构建的,然后存存储在java的堆内存中。

 这里fileddata默认是不开启的。Fielddata可能会消耗大量的堆空间

所以换一种方式解决:在需要的字段上添加关键字  keyword

更改后:

 @ApiOperation("分页排序")
    @GetMapping("pageAndSort/{page}/{size}")
    public Page<Hero> pageAndSort(@PathVariable Integer page,@PathVariable Integer size){
        //构建本地查询对象
        NativeSearchQueryBuilder query = new NativeSearchQueryBuilder();
        //
        PageRequest pageRequest = PageRequest.of(page, size);

        query.withPageable(pageRequest);
        query.withSort(SortBuilders.fieldSort("createTime.keyword").order(SortOrder.DESC));

        SearchHits<Hero> search = elasticTemplate.search(query.build(), Hero.class);
        List<Hero> blogs = new ArrayList<>();
        for (SearchHit<Hero> hero : search) {
            blogs.add(hero.getContent());
        }
        PageImpl<Hero> heroes = new PageImpl<>(blogs, pageRequest, search.getTotalHits());
        return heroes;
    }


        query.withSort(SortBuilders.fieldSort("createTime.keyword").order(SortOrder.DESC));

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐