1[[client-helpers]] 2== Client helpers 3 4The client comes with helpers to give you a more comfortable experience with 5some APIs. 6 7 8[discrete] 9[[iterators]] 10=== Iterators 11 12 13[discrete] 14[[search-response-iterator]] 15==== Search response iterator 16 17The `SearchResponseIterator` can be used to iterate page by page in a search 18result using 19https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#paginate-search-results[pagination]. 20 21An example as follows: 22 23[source,php] 24---- 25use Elasticsearch\Helper\Iterators\SearchResponseIterator; 26 27$search_params = [ 28 'scroll' => '5m', // period to retain the search context 29 'index' => '<name of index>', // here the index name 30 'size' => 100, // 100 results per page 31 'body' => [ 32 'query' => [ 33 'match_all' => new StdClass // {} in JSON 34 ] 35 ] 36]; 37// $client is Elasticsearch\Client instance 38$pages = new SearchResponseIterator($client, $search_params); 39 40// Sample usage of iterating over page results 41foreach($pages as $page) { 42 // do something with hit e.g. copy its data to another index 43 // e.g. prints the number of document per page (100) 44 echo count($page['hits']['hits']), PHP_EOL; 45} 46---- 47 48 49[discrete] 50[[search-hit-iterator]] 51==== Search hit iterator 52 53The `SearchHitIterator` can be used to iterate in a `SearchResponseIterator` 54without worrying about 55https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#paginate-search-results[pagination]. 56 57An example as follows: 58 59[source,php] 60---- 61use Elasticsearch\Helper\Iterators\SearchHitIterator; 62use Elasticsearch\Helper\Iterators\SearchResponseIterator; 63 64$search_params = [ 65 'scroll' => '5m', // period to retain the search context 66 'index' => '<name of index>', // here the index name 67 'size' => 100, // 100 results per page 68 'body' => [ 69 'query' => [ 70 'match_all' => new StdClass // {} in JSON 71 ] 72 ] 73]; 74// $client is Elasticsearch\Client instance 75$pages = new SearchResponseIterator($client, $search_params); 76$hits = new SearchHitIterator($pages); 77 78// Sample usage of iterating over hits 79foreach($hits as $hit) { 80 // do something with hit e.g. write to CSV, update a database, etc 81 // e.g. prints the document id 82 echo $hit['_id'], PHP_EOL; 83} 84----