Elasticsearch原理解析--scroll原理

scroll是ES用來(lái)解決全量遍歷數(shù)據(jù)的功能壶运。具體使用文檔見(jiàn):

https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#scroll-search-results

本篇文章將為大家分享scroll的原理凑保。通過(guò)本篇文章樱蛤,大家將會(huì)明白,為什么scroll是怎么做到全量遍歷功能,為什么不推薦使用scroll用作深翻頁(yè)。

先從基本功能誓琼,看看scroll是如何使用的。

scroll是通過(guò)search接口觸發(fā)的肴捉,search接口默認(rèn)最多只能返回size=10000條記錄腹侣,通過(guò)scroll,可以繼續(xù)往后面遍歷數(shù)據(jù)齿穗。這個(gè)是如何做大的呢傲隶?

首先search接口帶上scroll參數(shù),本次search就會(huì)返回一個(gè)scrollId窃页,比如如下請(qǐng)求:

POST /my-index-000001/_search?scroll=1m
{
  "query": {
    "match": {
      "message": "foo"
    }
  }
}

返回結(jié)果如下:

{
  "_scroll_id" : "FGluY2x1ZGVfY29udGV4dF91dWlkDXF1ZXJ5QW5kRmV0Y2gBFjY0MlkyRFFLVFdDc3RJd0UwT0VKcUEAAAAAAAAblxZfWjZMamlqb1JXeXJlcWtlN0xfUHNR",
  "took" : 11,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 10372087,
      "relation" : "eq"
    },
    ......
  }
}

可以看到返回多了一個(gè)_scroll_id伦籍,然后使用scroll接口,傳遞scroll_id腮出,就能不斷遍歷之前search DSL命中的全部數(shù)據(jù)。

POST /_search/scroll                                                               
{
  "scroll" : "1m",                                                                
  "scroll_id" : "FGluY2x1ZGVfY29udGV4dF91dWlkDXF1ZXJ5QW5kRmV0Y2gBFjY0MlkyRFFLVFdDc3RJd0UwT0VKcUEAAAAAAAAblxZfWjZMamlqb1JXeXJlcWtlN0xfUHNR" 
}

這里scroll設(shè)置為1m芝薇,說(shuō)明scrollId只保存1分鐘胚嘲,一分鐘后,scrollid就消失了洛二,再使用就會(huì)報(bào)如下錯(cuò)誤:

{
  "error" : {
    "root_cause" : [
      {
        "type" : "search_context_missing_exception",
        "reason" : "No search context found for id [7063]"
      }
    ],
    "type" : "search_phase_execution_exception",
    "reason" : "all shards failed",
    "phase" : "query",
    "grouped" : true,
    "failed_shards" : [
      {
        "shard" : -1,
        "index" : null,
        "reason" : {
          "type" : "search_context_missing_exception",
          "reason" : "No search context found for id [7063]"
        }
      }
    ],
    "caused_by" : {
      "type" : "search_context_missing_exception",
      "reason" : "No search context found for id [7063]"
    }
  },
  "status" : 404
}

接下來(lái)看看scroll是如何實(shí)現(xiàn)的馋劈。

scroll是以shard為單位保存scrollId的,

在search query流程中晾嘶,如果search請(qǐng)求傳遞了scroll參數(shù)妓雾,在創(chuàng)建ReaderContext時(shí),就會(huì)創(chuàng)建的是LegacyReaderContext垒迂,LegacyReaderContext中會(huì)生成一個(gè)ScrollContext械姻。我們來(lái)看下ScrollContext的內(nèi)容:

public final class ScrollContext {
    public TotalHits totalHits = null;
    public float maxScore = Float.NaN;
    public ScoreDoc lastEmittedDoc;
    public Scroll scroll;
}

其中有個(gè)關(guān)鍵變量lastEmittedDoc,這個(gè)記錄了上次scroll遍歷到的docId位置机断。

以一次遍歷10000天記錄楷拳,遍歷索引全部數(shù)據(jù)為例绣夺,之前遍歷到了10000條doc,那么lastEmittedDoc就是10000欢揖,再執(zhí)行一次scroll陶耍,就能繼續(xù)往后遍歷10000條,lastEmittedDoc就設(shè)置為20000她混。所以scroll就能做到不斷往后遍歷烈钞,直到遍歷全量數(shù)據(jù)。

這里lastEmittedDoc還需要注意坤按,在多shard時(shí)毯欣,實(shí)際lastEmittedDoc的值,要以shard實(shí)際fetch到的數(shù)據(jù)為準(zhǔn)晋涣,所以lastEmittedDoc是在SearchService.executeFetchPhase方法中設(shè)置:

public void executeFetchPhase(ShardFetchRequest request, SearchShardTask task, ActionListener<FetchSearchResult> listener) {
        final ReaderContext readerContext = findReaderContext(request.contextId(), request);
        final ShardSearchRequest shardSearchRequest = readerContext.getShardSearchRequest(request.getShardSearchRequest());
        final Releasable markAsUsed = readerContext.markAsUsed(getKeepAlive(shardSearchRequest));
        runAsync(getExecutor(readerContext.indexShard()), () -> {
            try (SearchContext searchContext = createContext(readerContext, shardSearchRequest, task, false)) {
                if (request.lastEmittedDoc() != null) {
                    searchContext.scrollContext().lastEmittedDoc = request.lastEmittedDoc();
                }
                searchContext.assignRescoreDocIds(readerContext.getRescoreDocIds(request.getRescoreDocIds()));
                searchContext.searcher().setAggregatedDfs(readerContext.getAggregatedDfs(request.getAggregatedDfs()));
                searchContext.docIdsToLoad(request.docIds());
......
                return searchContext.fetchResult();
            } catch (Exception e) {
                assert TransportActions.isShardNotAvailableException(e) == false : new AssertionError(e);
                // we handle the failure in the failure listener below
                throw e;
            }
        }, wrapFailureListener(listener, readerContext, markAsUsed));
    }

然后scroll的是保存在SearchService的activeReaders對(duì)象中仪媒,activeReaders是一個(gè)Map對(duì)象,有個(gè)Reaper會(huì)定時(shí)檢查過(guò)期的ReaderContext谢鹊,將它從activeReaders清除:

//默認(rèn)一分鐘檢查一次
public static final Setting<TimeValue> KEEPALIVE_INTERVAL_SETTING = Setting.positiveTimeSetting(
        "search.keep_alive_interval",
        timeValueMinutes(1),
        Property.NodeScope
    );

// 啟動(dòng)清理定時(shí)任務(wù)
TimeValue keepAliveInterval = KEEPALIVE_INTERVAL_SETTING.get(settings);
this.keepAliveReaper = threadPool.scheduleWithFixedDelay(new Reaper(), keepAliveInterval, Names.SAME);

    //清理任務(wù)
    class Reaper implements Runnable {
        @Override
        public void run() {
            for (ReaderContext context : activeReaders.values()) {
                if (context.isExpired()) {
                    logger.debug("freeing search context [{}]", context.id());
                    freeReaderContext(context.id());
                }
            }
        }
    }

所以手動(dòng)刪除scrollId的接口算吩,實(shí)現(xiàn)方式也很簡(jiǎn)單,就是清理掉ReaderContext對(duì)應(yīng)的scrollId佃扼。

接下來(lái)再看下scrollId的編碼偎巢。scrollId在ReaderContext中是以Long類型的id保存的。

然后在協(xié)調(diào)節(jié)點(diǎn)兼耀,會(huì)將全部shard的scrollId進(jìn)行編碼成一個(gè)字符串返回給客戶端压昼。

在TransportSearchHelper內(nèi)中,有buildScrollId和parseScrollId兩個(gè)方法用來(lái)進(jìn)行編解碼:

static String buildScrollId(AtomicArray<? extends SearchPhaseResult> searchPhaseResults) {
        try {
            BytesStreamOutput out = new BytesStreamOutput();
            out.writeString(INCLUDE_CONTEXT_UUID);
            out.writeString(searchPhaseResults.length() == 1 ? ParsedScrollId.QUERY_AND_FETCH_TYPE : ParsedScrollId.QUERY_THEN_FETCH_TYPE);
            out.writeCollection(searchPhaseResults.asList(), (o, searchPhaseResult) -> {
                o.writeString(searchPhaseResult.getContextId().getSessionId());
                o.writeLong(searchPhaseResult.getContextId().getId());
                SearchShardTarget searchShardTarget = searchPhaseResult.getSearchShardTarget();
                if (searchShardTarget.getClusterAlias() != null) {
                    o.writeString(
                        RemoteClusterAware.buildRemoteIndexName(searchShardTarget.getClusterAlias(), searchShardTarget.getNodeId())
                    );
                } else {
                    o.writeString(searchShardTarget.getNodeId());
                }
            });
            return Base64.getUrlEncoder().encodeToString(out.copyBytes().array());
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    static ParsedScrollId parseScrollId(String scrollId) {
        try {
            byte[] bytes = Base64.getUrlDecoder().decode(scrollId);
            ByteArrayStreamInput in = new ByteArrayStreamInput(bytes);
            final boolean includeContextUUID;
            final String type;
            final String firstChunk = in.readString();
            if (INCLUDE_CONTEXT_UUID.equals(firstChunk)) {
                includeContextUUID = true;
                type = in.readString();
            } else {
                includeContextUUID = false;
                type = firstChunk;
            }
            SearchContextIdForNode[] context = new SearchContextIdForNode[in.readVInt()];
            for (int i = 0; i < context.length; ++i) {
                final String contextUUID = includeContextUUID ? in.readString() : "";
                long id = in.readLong();
                String target = in.readString();
                String clusterAlias;
                final int index = target.indexOf(RemoteClusterAware.REMOTE_CLUSTER_INDEX_SEPARATOR);
                if (index == -1) {
                    clusterAlias = null;
                } else {
                    clusterAlias = target.substring(0, index);
                    target = target.substring(index + 1);
                }
                context[i] = new SearchContextIdForNode(clusterAlias, target, new ShardSearchContextId(contextUUID, id));
            }
            if (in.getPosition() != bytes.length) {
                throw new IllegalArgumentException("Not all bytes were read");
            }
            return new ParsedScrollId(scrollId, type, context);
        } catch (Exception e) {
            throw new IllegalArgumentException("Cannot parse scroll id", e);
        }
    }

Scroll在5.x版本還增加另一個(gè)Sliced scroll功能瘤运。這是可以支持對(duì)一個(gè)DSL進(jìn)行并發(fā)scroll窍霞,提高拉取數(shù)據(jù)的性能。

Sliced scroll的原理是在scroll基礎(chǔ)上增加了分片功能拯坟。建議分片是按照shard數(shù)量的倍數(shù)來(lái)絮短。在一個(gè)shard中的sliced還能進(jìn)一步切分绒怨。

實(shí)現(xiàn)原理如下:

在DSL傳遞slice參數(shù)后,生成的Query,會(huì)wrapper上slice的query改基,具體代碼在SliceBuilder.createSliceQuery中:

    private Query createSliceQuery(int id, int max, SearchExecutionContext context, boolean isScroll) {
        if (field == null) {
            return isScroll ? new TermsSliceQuery(IdFieldMapper.NAME, id, max) : new DocIdSliceQuery(id, max);
        } else if (IdFieldMapper.NAME.equals(field)) {
            if (isScroll == false) {
                throw new IllegalArgumentException("cannot slice on [_id] when using [point-in-time]");
            }
            return new TermsSliceQuery(IdFieldMapper.NAME, id, max);
        } else {
            MappedFieldType type = context.getFieldType(field);
            if (type == null) {
                throw new IllegalArgumentException("field " + field + " not found");
            }
            if (type.hasDocValues() == false) {
                throw new IllegalArgumentException("cannot load numeric doc values on " + field);
            } else {
                IndexFieldData<?> ifm = context.getForField(type, MappedFieldType.FielddataOperation.SEARCH);
                if (ifm instanceof IndexNumericFieldData == false) {
                    throw new IllegalArgumentException("cannot load numeric doc values on " + field);
                }
                return new DocValuesSliceQuery(field, id, max);
            }
        }
    }

wrapper的slice query根據(jù)field的類型包括TermsSliceQuery魂奥、DocIdSliceQuery童社、DocValuesSliceQuery溯警。

他們的功能都是根據(jù)傳遞的id、max值年柠,確定在命中的docid集合中只返回slice id對(duì)應(yīng)的docid凿歼。這樣原DSL就只能返回slice query對(duì)應(yīng)的docId列表。

以上就是scroll的原理實(shí)現(xiàn),所以可以看到scroll只能往后面遍歷毅往,而且設(shè)置了有效期牵咙,所以如果頻繁設(shè)置scroll用來(lái)進(jìn)行深翻頁(yè),會(huì)導(dǎo)致生成過(guò)多的scrollId攀唯,而且scroll也不能跳頁(yè)洁桌,所以從功能定位上scroll是用來(lái)遍歷全量數(shù)據(jù)使用的。如果要進(jìn)行翻頁(yè)侯嘀,ES推薦的使用Search After功能另凌。

使用scroll還需要注意一個(gè)問(wèn)題,如果訪問(wèn)出現(xiàn)了超時(shí)戒幔,由于不確定本次scroll是否已經(jīng)進(jìn)行吠谢,所以可能導(dǎo)致獲取的數(shù)據(jù)缺失,所以要進(jìn)行全部重試诗茎,這里也可以用一些技巧工坊,通過(guò)修改DSL,定位到最新獲取的數(shù)據(jù)敢订,再重新使用scroll查詢也是可以的王污。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市楚午,隨后出現(xiàn)的幾起案子昭齐,更是在濱河造成了極大的恐慌,老刑警劉巖矾柜,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件阱驾,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡怪蔑,警方通過(guò)查閱死者的電腦和手機(jī)里覆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)缆瓣,“玉大人喧枷,你說(shuō)我怎么就攤上這事±Τ睿” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵窟却,是天一觀的道長(zhǎng)昼丑。 經(jīng)常有香客問(wèn)我,道長(zhǎng)夸赫,這世上最難降的妖魔是什么菩帝? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上呼奢,老公的妹妹穿的比我還像新娘宜雀。我一直安慰自己,他們只是感情好握础,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布辐董。 她就那樣靜靜地躺著,像睡著了一般禀综。 火紅的嫁衣襯著肌膚如雪简烘。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,679評(píng)論 1 305
  • 那天定枷,我揣著相機(jī)與錄音孤澎,去河邊找鬼。 笑死欠窒,一個(gè)胖子當(dāng)著我的面吹牛覆旭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播岖妄,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼型将,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了衣吠?” 一聲冷哼從身側(cè)響起茶敏,我...
    開(kāi)封第一講書(shū)人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎缚俏,沒(méi)想到半個(gè)月后惊搏,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡忧换,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年恬惯,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片亚茬。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡酪耳,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出刹缝,到底是詐尸還是另有隱情碗暗,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布梢夯,位于F島的核電站言疗,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏颂砸。R本人自食惡果不足惜噪奄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一死姚、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧勤篮,春花似錦都毒、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至手负,卻和暖如春涤垫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背竟终。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工蝠猬, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人统捶。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓榆芦,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親喘鸟。 傳聞我的和親對(duì)象是個(gè)殘疾皇子匆绣,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容