From dbdc3e2c3edc4361c6c76939f8222f5550faedf4 Mon Sep 17 00:00:00 2001 From: Rastislav Brandobur Date: Mon, 11 Sep 2023 09:23:44 +0200 Subject: [PATCH] feat: added support for sortable fields --- src/Index.php | 8 +++++++- src/Model/Document.php | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Index.php b/src/Index.php index b354ccf..36421c4 100644 --- a/src/Index.php +++ b/src/Index.php @@ -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); @@ -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; @@ -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(); diff --git a/src/Model/Document.php b/src/Model/Document.php index bf0bddf..a4e6474 100644 --- a/src/Model/Document.php +++ b/src/Model/Document.php @@ -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