Skip to content

Commit

Permalink
feat: added support for sortable fields
Browse files Browse the repository at this point in the history
  • Loading branch information
rasstislav committed Sep 11, 2023
1 parent e0943ff commit dbdc3e2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ public function rebuild(): void
$settings = [
'searchableAttributes' => Document::get_searchable_fields($sng::class),
'filterableAttributes' => Document::get_filterable_fields($sng::class),
'sortableAttributes' => Document::get_sortable_fields($sng::class),
];

static::get_client()->index($indexName)->updateSettings($settings);
Expand Down Expand Up @@ -393,11 +394,12 @@ public function remove(Document|array $documents): self
* @param $q
* @param array|null $filter
* @param int|null $limit
* @param array|null $sort
* @return SearchResults
* @throws NotFoundExceptionInterface
* @throws Throwable
*/
public function search($q, ?array $filter = null, ?int $limit = null): SearchResults
public function search($q, ?array $filter = null, ?int $limit = null, ?array $sort = null): SearchResults
{
if ($limit === null || $limit <= 0) {
$limit = 100;
Expand All @@ -412,6 +414,10 @@ public function search($q, ?array $filter = null, ?int $limit = null): SearchRes
$options['filter'] = $filter;
}

if ($sort !== null) {
$options['sort'] = $sort;
}

$meiliResults = static::get_client()->index($this->getIndexName())->search($q, $options);

$estimatedTotalHits = $meiliResults->getEstimatedTotalHits();
Expand Down
32 changes: 32 additions & 0 deletions src/Model/Document.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,38 @@ public static function get_filterable_fields(string $class, bool $fieldNames = t
return $filterable_fields[$class];
}

/**
* @param string $class
* @return array|null
*/
public static function get_sortable_fields(string $class): ?array
{
$sortable_fields = [];

$classes = [];
$fields = [];

foreach (ClassInfo::getValidSubClasses($class) as $subClass) {
$sortableFields = Config::inst()->get($subClass, 'meilisearch_sortable_fields') ?? [];

$fields = array_merge($fields, $sortableFields);

$classes[] = $subClass;
}

$fields = array_values(array_unique($fields));

if (empty($fields)) {
$fields = null;
}

foreach ($classes as $subClass) {
$sortable_fields[$subClass] = $fields;
}

return $sortable_fields[$class];
}

/**
* @return array
* @throws NotFoundExceptionInterface
Expand Down

0 comments on commit dbdc3e2

Please sign in to comment.