背景
elasticsearch7.x 开始加上了软限制,max_open_scroll_context
默认为500个,这个参数可以理解为数据库可用活跃连接数
报错是因为虽然scroll id有一个存活时限,过期后会自动被清理,但在高并发情况下还是会有可能达到限制,从而报错
Trying to create too many scroll contexts. Must be less than or equal to 500
可以发送请求来查看es集群的open_context
使用情况
[GET] _nodes/stats/indices/search
参数解释
"search" : {
"open_contexts" : 0, //正在打开的查询上下文个数
"query_total" : 0, //查询出来的总数据条数
"query_time_in_millis" : 0, //查询阶段所耗费的时间
"query_current" : 0, //当前正在查询个数
"fetch_total" : 0, //Fetch操作的次数
"fetch_time_in_millis" : 0, //Fetch阶段总耗时时间
"fetch_current" : 0, //正在fetch的次数
"scroll_total" : 0, //通过scroll api查询数据总条数
"scroll_time_in_millis" : 0, //通过scroll api总耗时时间
"scroll_current" : 0, //当前滚动API调用次
"suggest_total" : 0, //通过suggest api获取的推荐总数量
"suggest_time_in_millis" : 0,//suggest总耗费时间
"suggest_current" : 0 //正在执行suggest api的个数
},
解决方法
百度到的方法是将这个参数调大
curl -X PUT http://ip:9200/_cluster/settings -H 'Content-Type: application/json' -d'{
"persistent" : {
"search.max_open_scroll_context": 5000
},
"transient": {
"search.max_open_scroll_context": 5000
}
}
'
但是这个方法治标不治本,正确的解决办法是在使用scorll id查询后,手动将scroll id清除
xpack sql
在使用xpack sql中,如果sql语句查询的结果大于fetch_size,就会生成cursor,其实也就是scroll id
这里将整个流程完整走一遍,cursor较长,这里为了方便观察,简化了长度
- 发送请求
curl -d "{\"query\":\"select * from sample where name = 'John Smith' limit 1 \",\"fetch_size\":2}" -X POST -H 'Content-Type: application/json' http://ip:9200/_xpack/sql?format=json
- 得到的结果如下
{"rows":[[33,1,"TestD",null,"John Smith","Test Street No. 1",1,"TestO","Developer"],[33,1,"TestD",null,"John Smith","Test Street No. 1",1,"TestO","Developer"]],"cursor":"04qtAwFz5"}
- 根据获取到的游标重新发送请求,查下一页
curl -d "{\"cursor\":\"04qtAwFz5\"}" -X POST -H 'Content-Type: application/json' http://ip:9200/_xpack/sql?format=json
- 当所有的结果都查完后,再发送请求会得到
{"rows":[]}
这时如果再继续发送请求,就会报错
- 判断数据已经全部查完后,发送请求,清除游标
curl -d "{\"cursor\":\"04qtAwFz5\"}" -X POST -H 'Content-Type: application/json' http://ip:9200/_xpack/sql/close?format=json
#注意这里的地址为/_xpack/sql/close
transportClient
具体查询的代码我就不贴了,这里只贴删除游标的
//清除游标
if (searchResponse.getScrollId()!=null && !searchResponse.getScrollId().equals("")){
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.addScrollId(searchResponse.getScrollId());
ActionFuture<ClearScrollResponse> actionFuture = transportClient.clearScroll(clearScrollRequest);
if (!actionFuture.actionGet().isSucceeded()){
logger.error(actionFuture.toString());
}
}
restHighLevelClient
if (searchResponse.getScrollId() != null && !searchResponse.getScrollId().equals("")){
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.addScrollId(searchResponse.getScrollId());
ClearScrollResponse clearScrollResponse = restHighLevelClient.clearScroll(clearScrollRequest,RequestOptions.DEFAULT);
if (!clearScrollResponse.isSucceeded()){
logger.info(clearScrollResponse.toString());
}
}
查询时,每次返回的游标都是一样的,所以只需要最后删除一次就可以