2.X/1. Getting Started

1-09-4. Scroll

drscg 2017. 9. 30. 17:38

scroll query is used to retrieve large numbers of documents from Elasticsearch efficiently, without paying the penalty of deep pagination.

scroll query는 Elasticsearch에서 매우 많은 수의 document를, deep 페이지 계산의 불이익 없이, 효과적으로 가져오기 위해 함께 사용된다.

Scrolling allows us to do an initial search and to keep pulling batches of results from Elasticsearch until there are no more results left. It’s a bit like a cursor in a traditional database.

Scrolling은 초기 검색을 하고, 더 이상 결과가 없을 때까지, Elasticsearch로부터 결과를 일괄적으로 가져오도록 유지할 수 있다. 전통적인 DB의 cursor 와 약간 유사하다.

A scrolled search takes a snapshot in time. It doesn’t see any changes that are made to the index after the initial search request has been made. It does this by keeping the old data files around, so that it can preserve its "view" on what the index looked like at the time it started.

scrolled 검색은 시간에 맞추어 snapshot을 찍는다. 초기 검색 request 후에, index의 어떤 변경 사항에 대해서도 알지 못한다. 이것은 index를 초기 검색이 시작된 시점처럼 보이게 하는 index의 "view" 를 유지하기 위해, 기존의 데이터 file을 유지함으로써 가능하다.

The costly part of deep pagination is the global sorting of results, but if we disable sorting, then we can return all documents quite cheaply. To do this, we sort by _doc. This instructs Elasticsearch just return the next batch of results from every shard that still has results to return.

deep 페이지 계산에서, 많은 비용이 소요되는 부분은 결과의 전체적인 정렬 부분이다. 만약 정렬을 비활성화하면, 모든 document를 훨씬 적은 비용으로 반환할 수 있다. 이렇게 하기 위해, _doc 을 기준으로 정렬한다. 이 명령어는 반환할 결과를 가지고 있는 모든 shard로부터 결과의 다음 부분만을 반환하도록 한다.

To scroll through results, we execute a search request and set the scroll value to the length of time we want to keep the scroll window open. The scroll expiry time is refreshed every time we run a scroll request, so it only needs to be long enough to process the current batch of results, not all of the documents that match the query. The timeout is important because keeping the scroll window open consumes resources and we want to free them as soon as they are no longer needed. Setting the timeout enables Elasticsearch to automatically free the resources after a small period of inactivity.

결과를 scroll하기 위하여, search request를 실행하고, scroll이 열린채로 유지하기를 원하는 시간을scroll 값에 설정한다. scroll 만료 시간은 scroll request를 실행시킬 때마다 refresh된다. 그래서, query에 일치하는 모든 document가 아닌, 현재의 결과 분량을 처리하기 위한 충분한 시간을 줘야한다. scroll이 열린채로 유지한다는 것은 resource를 소비한다는 것이고, 더 이상 필요하지 않으면 그것을 해지해야 하기 때문에 timeout은 중요하다. timeout을 설정하는 것은, 더 이상 사용하지 않는 순간 이후 조금 있다가, Elasticsearch가 자동으로 resource를 해지하도록 하는 것이다.

GET /old_index/_search?scroll=1m 
{
    "query": { "match_all": {}},
    "sort" : ["_doc"], 
    "size":  1000
}

1분 동안 scroll이 열린채로 유지한다.

_doc 은 가장 효율적인 정렬 순서이다.

The response to this request includes a _scroll_id, which is a long Base-64 encoded string. Now we can pass the _scroll_id to the _search/scroll endpoint to retrieve the next batch of results:

이 request에 대한 response는 base64로 인코딩된 긴 문자열인, _scroll_id 를 포함한다. 이제 결과의 다음 부분을 가져오기 위해, _search/scroll 의 마지막에 _scroll_id 를 넘길 수 있다.

GET /_search/scroll
{
    "scroll": "1m", 
    "scroll_id" : "cXVlcnlUaGVuRmV0Y2g7NTsxMDk5NDpkUmpiR2FjOFNhNnlCM1ZDMWpWYnRROzEwOTk1OmRSamJHYWM4U2E2eUIzVkMxalZidFE7MTA5OTM6ZFJqYkdhYzhTYTZ5QjNWQzFqVmJ0UTsxMTE5MDpBVUtwN2lxc1FLZV8yRGVjWlI2QUVBOzEwOTk2OmRSamJHYWM4U2E2eUIzVkMxalZidFE7MDs="
}

다시 scroll 만료 시간을 1분으로 설정했다는 것을 유심히 보자.

The response to this scroll request includes the next batch of results. Although we specified a sizeof 1,000, we get back many more documents. When scanning, the size is applied to each shard, so you will get back a maximum of size * number_of_primary_shards documents in each batch.

이 scroll request에 대한 response는 결과의 다음 분량이다. 비록 size 에 1,000을 지정했지만, 그 이상의 document를 돌려 받는다. scan 시에, size 는 각 shard별로 적용된다. 그래서, 각 부분에서 돌려 받는 document의 최대값은 size * number_of_primary_shards 이다.

Note

The scroll request also returns a new _scroll_id. Every time we make the next scroll request, we must pass the _scroll_id returned by the previous scroll request.

scroll request는 새로운 _scroll_id 도 반환한다. 다음 scroll request를 할 때마다, 직전scroll request에서 반환된 _scroll_id 를 넘겨야 한다.

When no more hits are returned, we have processed all matching documents.

더 이상 hit가 반환되지 않으면, 모든 일치하는 document를 처리한 것이다.

Tip

Some of the official Elasticsearch clients such as Python client and Perl client provide scroll helpers that provide easy-to-use wrappers around this funtionality.

Python client와 Perl client 같은 공식적인 Elasticsearch 클라이언트 중 일부는, 이 기능을 쉽게 사용할 수 있는 wrapper를 제공하는, scroll helper를 제공한다.


'2.X > 1. Getting Started' 카테고리의 다른 글

1-09-2. Fetch Phase  (0) 2017.09.30
1-09-3. Search Options  (0) 2017.09.30
1-10. Index Management  (0) 2017.09.30
1-10-01. Creating an Index  (0) 2017.09.30
1-10-02. Deleting an Index  (0) 2017.09.30