Skip to content

Commit

Permalink
Ensure that results are sorted by _id (could be breaking change) + us…
Browse files Browse the repository at this point in the history
…e logger instead of debugbar_log

By default we are sorting by `_id` after any HasSorting logic to ensure that pagination is correct.

You can turn this feature by using `$builder->setSortById(false);`

Updated config structure:

- `log_measurement` Logs every query to log (default false). You can use `ELASTICSEARCH_LOG_MEASUREMENT` env.
- `log_debug` Debug logs every query data to a log (true in local environment). You can use `ELASTICSEARCH_LOG_DEBUG` env.
- `service` Enables to change available indices (implement IndicesServiceContract or  extend IndicesService)
- `prefix` Used prefix for index names - uses APP_NAME and replace '-' to '_', converts name to slug variant.
- `hosts` A list of IPS for your elastic search - https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/configuration.html. Use `;` separator. Default localhost:9200.
  • Loading branch information
pionl committed Nov 11, 2021
1 parent 3ffc8ae commit ddc67e8
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 9 deletions.
3 changes: 2 additions & 1 deletion config/lelastico.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
),
'indices' => [],
'log_failure' => true,
'debugbar_log' => app()->isLocal() && function_exists('debugbar'),
'log_debug' => env('ELASTICSEARCH_LOG_DEBUG', 'local' === env('APP_ENV')),
'log_measurement' => env('ELASTICSEARCH_LOG_MEASUREMENT', false),
'service' => IndicesService::class,
];
16 changes: 16 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ Use `ELASTICSEARCH_HOSTS` environment for setting elastic search hosts. [Format]

```
$client = resolve(\Elasticsearch\Client::class);
```

```
$client = $container->make(\Elasticsearch\Client::class);
```

**Mapping types constants**
Expand Down Expand Up @@ -150,6 +154,10 @@ Property mappings types using constants like:

**Sorting**

**By default we are sorting by `_id` after any HasSorting logic to ensure that pagination is correct.**

You can turn this feature by using `$builder->setSortById(false);`

To enable sortable behavior add `HasSorting` trait to your instance of `AbstractBuilder` and implement method `allowedSortFields`.

```
Expand Down Expand Up @@ -180,6 +188,14 @@ Available directions for sorting are `asc` and `desc` and if not specified the d
`sort[]=goals:asc&sort[]=minutes:desc`
## Configuration
- `log_measurement` Logs every query to log (default false). You can use `ELASTICSEARCH_LOG_MEASUREMENT` env.
- `log_debug` Debug logs every query data to a log (true in local environment). You can use `ELASTICSEARCH_LOG_DEBUG` env.
- `service` Enables to change available indices (implement IndicesServiceContract or extend IndicesService)
- `prefix` Used prefix for index names - uses APP_NAME and replace '-' to '_', converts name to slug variant.
- `hosts` A list of IPS for your elastic search - https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/configuration.html. Use `;` separator. Default localhost:9200.
## TODO
- improve documentation
Expand Down
22 changes: 22 additions & 0 deletions src/Search/Query/AbstractBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Illuminate\Contracts\Config\Repository;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Lelastico\Constants\SortDirections;
use Lelastico\Indices\AbstractElasticIndex;
use Lelastico\Search\Query\Traits\AddQueries;
use Lelastico\Search\Query\Traits\HasPaginationSettings;
Expand All @@ -33,6 +34,8 @@ abstract class AbstractBuilder
*/
public ?Client $client = null;

protected bool $sortById = true;

public function __construct(Request $request, LoggerInterface $logger, Repository $config)
{
$this->request = $request;
Expand Down Expand Up @@ -80,6 +83,10 @@ public function paginate(): LengthAwarePaginator
$this->addSort($this->query, $this->request);
}

if (true === $this->sortById) {
$this->query->addSort('_id', SortDirections::ASC);
}

// Build the query and improve it
$query = $this->query->getQuery();

Expand Down Expand Up @@ -147,4 +154,19 @@ public function setSelect(array $select): self

return $this;
}

/**
* Ensure that entries are by default sorted by _id to ensure correct pagination.
*/
public function setSortById(bool $sortById): self
{
$this->sortById = $sortById;

return $this;
}

public function isSortingById(): bool
{
return $this->sortById;
}
}
37 changes: 32 additions & 5 deletions src/Search/Query/Traits/LogQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,46 @@ trait LogQuery
protected Repository $config;

/**
* Logs the query with debugbar (or any custom solution).
* Logs the query.
*
* @param array $result
* @param array $query
*/
protected function logQuery(array $result, array $query)
{
if (false === $this->config->get('lelastico.debugbar_log')) {
$time = $result['took'] / 1000; // ms

$isDebug = $this->config->get('lelastico.log_debug');

if (false === $isDebug) {
if (true == $this->config->get('lelastico.log_measurement')) {
$this->logMeasurement($time, $query['index'] ?? 'unknown');
}

return;
}

// TODO refactor
add_measure('Elastic search', 0, $result['took'] / 1000);
debugbar()->debug('Elastic search query '.json_encode($query, JSON_PRETTY_PRINT));
// Debug-bar add_measure function
$this->logDebug($time, $query);
}

protected function logMeasurement(float $time, string $index): void
{
$this->logger->info('Elastic search query time', [
'took' => $time,
'index' => $index,
]);
}

protected function logDebug(float $time, array $query): void
{
if (true === function_exists('add_measure')) {
add_measure('Elastic search', 0, $time);
}

$this->logger->debug('Elastic search query', [
'took' => $time,
'query' => $query,
]);
}
}
6 changes: 3 additions & 3 deletions src/Write/BulkWrite.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ class BulkWrite
* @var callable|null
*/
private $onSent;

/**
* Wait for refresh
*
* Wait for refresh.
*
* @var bool
*/
public $refresh = false;
Expand Down

0 comments on commit ddc67e8

Please sign in to comment.