Easy-es框架,解决max_analyzed_offset问题
贴出原问题:
Caused by: org.dromara.easyes.common.exception.EasyEsException: search response failed ,failedShards: shard [[y5IlSlqJRd2hrlIN54BIFQ][article][2]], reason [ElasticsearchException[Elasticsearch exception [type=illegal_argument_exception, reason=The length [4710912] of field [content] in doc[3173515]/index[article] exceeds the [index.highlight.max_analyzed_offset] limit [1000000]. To avoid this error, set the query parameter [max_analyzed_offset] to a value less than index setting [1000000] and this will tolerate long field values by truncating them.]]], cause [ElasticsearchException[Elasticsearch exception [type=illegal_argument_exception, reason=The length [4710912] of field [content] in doc[3173515]/index[article] exceeds the [index.highlight.max_analyzed_offset] limit [1000000]. To avoid this error, set the query parameter [max_analyzed_offset] to a value less than index setting [1000000] and this will tolerate long field values by truncating them.]]
分析:
此问题是因为,es索引默认的单字段最大的可以进行高亮截取的长度为 index.highlight.max_analyzed_offset=1000000,但是字段存储的数据长度为4710912,长度超了很多,所以报错。
解决方案:
有两种解决方案
1、修改索引,put请求,设置 highlight.max_analyzed_offset=5000000,设置长一些,但是此方案会造成es内存消耗和开支更大,或许会影响查询,所以不建议,我也没有尝试。
2、代码中在请求查找的时候,添加参数 maxAnalyzedOffset(9999999)。
此方案可行,已测试。
具体做法如下,此处以和easy-es框架适配为例子。
//先正常封装查询,使用easy-es框架封装查询各类条件
LambdaEsQueryWrapper<ArticleSelect> leqw = queryWhere(dto);
//使用原生的高亮构造器 设置高亮条件maxAnalyzedOffset 及其他条件
HighlightBuilder highlightBuilder = new HighlightBuilder()
.fragmentSize(200) // 每个片段最多200字符
.numOfFragments(1) // 只返回1个片段
.maxAnalyzedOffset(999999) // 限制分析的最大字符数
.preTags("<font color='red'>") // 自定义高亮开始标签
.postTags("</font>") // 自定义高亮结束标签
.field("title") // 对 title 字段高亮
.field("content"); // 对 content 字段高亮
//注意,此处的SearchSourceBuilder不是new出来的,是selectMapper也就是easy-es的mapper get出来的
SearchSourceBuilder searchSourceBuilder = selectMapper.getSearchSourceBuilder(leqw);
//高亮构造器设置进入SearchSourceBuilder
searchSourceBuilder.highlighter(highlightBuilder);
//easy-es的框架混合插入SearchSourceBuilder
leqw.setSearchSourceBuilder(searchSourceBuilder);
//正常查询即可避免刚刚出现的错误 下面的查询是深分页查询,其他查询如queryList,pageQuery也是可以的,而且这个高亮设置和实体类字段上面的高亮注解@HighLight并不冲突,这个设置的优先级要高于注解。
SAPageInfo<ArticleSelect> data = selectMapper.searchAfterPage(leqw, dto.getNextSearchAfter(), dto.getPgSize());
更多推荐



所有评论(0)