更改前:
@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
更改后:文章来源:https://www.toymoban.com/news/detail-506932.html
@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));文章来源地址https://www.toymoban.com/news/detail-506932.html
到了这里,关于ES排序报错:Elasticsearch exception [type=illegal_argument_exception, reason=Text的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!