Skip to content

Commit

Permalink
feat: throw BulkInsertQueryException when there are any insert errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jmosul committed May 25, 2021
1 parent c03e0ff commit e1c8997
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace DesignMyNight\Elasticsearch;

use Closure;
use DesignMyNight\Elasticsearch\Exceptions\BulkInsertQueryException;
use DesignMyNight\Elasticsearch\Exceptions\QueryException;
use Elasticsearch\ClientBuilder;
use Illuminate\Database\Connection as BaseConnection;
Expand Down Expand Up @@ -283,9 +284,10 @@ public function scroll(string $scrollId, string $scrollTimeout = '30s', int $lim
/**
* Run an insert statement against the database.
*
* @param array $params
* @param array $bindings
* @param array $params
* @param array $bindings
* @return bool
* @throws BulkInsertQueryException
*/
public function insert($params, $bindings = [])
{
Expand All @@ -295,7 +297,11 @@ public function insert($params, $bindings = [])
Closure::fromCallable([$this->connection, 'bulk'])
);

return empty($result['errors']);
if (empty($result['errors'])) {
throw new BulkInsertQueryException($result);
}

return true;
}

/**
Expand Down
57 changes: 57 additions & 0 deletions src/Exceptions/BulkInsertQueryException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace DesignMyNight\Elasticsearch\Exceptions;

use Exception;

class BulkInsertQueryException extends Exception
{
private $errorLimit = 10;

/**
* BulkInsertQueryException constructor.
*
* @param array $queryResult
*/
public function __construct(array $queryResult)
{
parent::__construct($this->formatMessage($queryResult), 400);
}

/**
* Format the error message.
*
* Takes the first {$this->errorLimit} bulk issues and concatenates them to a single string message
*
* @param array $result
* @return string
*/
private function formatMessage(array $result): string
{
$message = [];

$items = array_filter($result['items'] ?? [], function(array $item): bool {
return $item['index'] && !empty($item['index']['error']);
});

$items = array_values($items);

$totalErrors = count($items);

// reduce to max limit
array_splice($items, 0, $this->errorLimit);

$message[] = 'Bulk Insert Errors (' . 'Showing ' . count($items) . ' of ' . $totalErrors . '):';

foreach ($items as $item) {
$itemError = array_merge([
'_id' => $item['_id'],
'reason' => $item['error']['reason'],
], $item['error']['caused_by'] ?? []);

$message[] = implode(': ', $itemError);
}

return implode(PHP_EOL, $message);
}
}

0 comments on commit e1c8997

Please sign in to comment.