ElasticSearcher\Managers\DocumentsManager::bulkIndex PHP Method

bulkIndex() public method

Index a set of documents.
public bulkIndex ( string $indexName, string $type, array $data )
$indexName string
$type string
$data array
    public function bulkIndex($indexName, $type, array $data)
    {
        $params = ['body' => []];
        foreach ($data as $item) {
            $header = ['_index' => $indexName, '_type' => $type];
            if (array_key_exists('id', $item)) {
                $header['_id'] = $item['id'];
            }
            // The bulk operation expects two JSON objects for each item
            // the first one should describe the operation, index, type
            // and ID. The later one is the document body.
            $params['body'][] = ['index' => $header];
            $params['body'][] = $item;
        }
        $this->elasticSearcher->getClient()->bulk($params);
    }

Usage Example

 public function testBulkIndex()
 {
     $documents = [['id' => 111112, 'name' => 'The Guardians of the Galaxy', 'year' => 2015], ['id' => 111113, 'name' => 'Spiderman 4D', 'year' => 2015], ['id' => 111114, 'name' => 'Tokyo Drift', 'year' => 2013]];
     $this->documentsManager->bulkIndex('movies', 'movies', $documents);
     foreach ($documents as $document) {
         $this->assertTrue($this->documentsManager->exists('movies', 'movies', $document['id']));
         $this->assertEquals($document, $this->documentsManager->get('movies', 'movies', $document['id'])['_source']);
     }
 }