diff --git a/README.md b/README.md index 4bbf190..3cd83a2 100644 --- a/README.md +++ b/README.md @@ -92,9 +92,12 @@ Any additional settings you want to define per index can be included in the `sta ], ], ], + /* + Pass any of the options from https://typesense.org/docs/26.0/api/search.html#search-parameters + */ 'search_options' => [ /* - Specify a custom sort by order, see the Typesense documentation for more info: + eg Specify a custom sort by order, see the Typesense documentation for more info: https://typesense.org/docs/guide/ranking-and-relevance.html#ranking-based-on-relevance-and-popularity */ 'sort_by' => '_text_match(buckets: 10):desc,weighted_score:desc', diff --git a/src/Typesense/Index.php b/src/Typesense/Index.php index 6f278aa..66cc5a2 100644 --- a/src/Typesense/Index.php +++ b/src/Typesense/Index.php @@ -103,9 +103,9 @@ public function searchUsingApi($query, array $options = []): Collection ->join(',') ?: '*'; } - if (! isset($options['sort_by'])) { - if ($sort = Arr::get($this->config, 'settings.search_options.sort_by', false)) { - $options['sort_by'] = $sort; + foreach (Arr::get($this->config, 'settings.search_options', []) as $handle => $value) { + if (! isset($options[$handle])) { + $options[$handle] = $value; } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 9ca79d5..008e0d0 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -44,6 +44,17 @@ protected function resolveApplicationConfiguration($app) $app['config']->set('statamic.search.indexes.typesense_index', [ 'driver' => 'typesense', 'searchables' => ['collection:pages'], + 'settings' => [ + 'schema' => [ + 'fields' => [ + [ + 'type' => 'string', + 'name' => 'title', + 'sort' => true, + ], + ], + ], + ], ]); } } diff --git a/tests/Unit/IndexTest.php b/tests/Unit/IndexTest.php index 9c738e9..95d721f 100644 --- a/tests/Unit/IndexTest.php +++ b/tests/Unit/IndexTest.php @@ -108,4 +108,28 @@ public function it_removes_documents_from_the_index() $this->assertNotContains('entry::test-1', $export); $this->assertContains('entry::test-2', $export); } + + #[Test] + public function it_sorts_by_specified_order() + { + $entry1 = Facades\Entry::make() + ->id('test-2') + ->collection('pages') + ->data(['title' => 'Entry 1']) + ->save(); + + $entry2 = tap(Facades\Entry::make() + ->id('test-1') + ->collection('pages') + ->data(['title' => 'Entry 2'])) + ->save(); + + $results = Facades\Search::index('typesense_index')->searchUsingApi('*', ['sort_by' => 'title:asc']); + + $this->assertSame(['Entry 1', 'Entry 2'], collect($results)->pluck('title')->all()); + + $results = Facades\Search::index('typesense_index')->searchUsingApi('*', ['sort_by' => 'title:desc']); + + $this->assertSame(['Entry 2', 'Entry 1'], collect($results)->pluck('title')->all()); + } }