Permalink
Browse files

Clear search context after usage in scroll (#1399)

Because open search contexts have a cost they should be explicitly
cleared as soon as the scroll is not being used anymore.

The method `clear()` is exposed in `Scroll` to also be able to clear the
search context manually from outside.
  • Loading branch information...
mjanser authored and ruflin committed Nov 8, 2017
1 parent c070099 commit b2c37db61f26108df771dfce5175e492464c3033
Showing with 43 additions and 4 deletions.
  1. +4 −0 CHANGELOG.md
  2. +19 −3 lib/Elastica/Scroll.php
  3. +20 −1 test/Elastica/ScrollTest.php
@@ -11,8 +11,12 @@ All notable changes to this project will be documented in this file based on the
### Added
- Added clear() to `Scroll` for closing search context on ES manually
### Improvements
- Clear search context on ES after usage in `Scroll`
### Deprecated
@@ -83,9 +83,7 @@ public function next()
$this->_revertOptions();
} else {
// If there are no pages left, we do not need to query ES.
// Reset scroll ID so valid() returns false.
$this->_nextScrollId = null;
$this->_currentResultSet = null;
$this->clear();
}
}
@@ -134,6 +132,24 @@ public function rewind()
$this->_revertOptions();
}
/**
* Cleares the search context on ES and marks this Scroll instance as finished.
*/
public function clear()
{
if (null !== $this->_nextScrollId) {
$this->_search->getClient()->request(
'_search/scroll',
Request::DELETE,
[Search::OPTION_SCROLL_ID => [$this->_nextScrollId]]
);
// Reset scroll ID so valid() returns false.
$this->_nextScrollId = null;
$this->_currentResultSet = null;
}
}
/**
* Prepares Scroll for next request.
*
@@ -1,6 +1,7 @@
<?php
namespace Elastica\Test;
use Elastica\Client;
use Elastica\Document;
use Elastica\ResultSet;
use Elastica\Scroll;
@@ -15,12 +16,16 @@ class ScrollTest extends Base
*/
public function testForeach()
{
$scroll = new Scroll($this->_prepareSearch());
$search = $this->_prepareSearch();
$scroll = new Scroll($search);
$count = 1;
$this->_assertOpenSearchContexts($search->getClient(), 0);
/** @var ResultSet $resultSet */
foreach ($scroll as $scrollId => $resultSet) {
$this->assertNotEmpty($scrollId);
$this->_assertOpenSearchContexts($search->getClient(), 1);
$results = $resultSet->getResults();
switch (true) {
@@ -47,6 +52,8 @@ public function testForeach()
++$count;
}
$this->_assertOpenSearchContexts($search->getClient(), 0);
}
/**
@@ -118,4 +125,16 @@ private function _prepareSearch($indexSize = 11)
return $search;
}
/**
* Tests the number of open search contexts on ES.
*
* @param Client $client
* @param int $count
*/
private function _assertOpenSearchContexts(Client $client, $count)
{
$stats = $client->getStatus()->getData();
$this->assertSame($count, $stats['_all']['total']['search']['open_contexts'], 'Open search contexts should match');
}
}

0 comments on commit b2c37db

Please sign in to comment.