Skip to content
11 changes: 11 additions & 0 deletions src/Typesense/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Statamic\Facades\Blink;
use Statamic\Search\Documents;
use Statamic\Search\Index as BaseIndex;
use Statamic\Search\Result;
use Statamic\Support\Arr;
use Typesense\Client;
use Typesense\Exceptions\ObjectNotFound;
Expand Down Expand Up @@ -184,4 +185,14 @@ public function client()
{
return $this->client;
}

public function extraAugmentedResultData(Result $result)
{

if (is_null($highlight = Arr::get($result->getRawResult(), 'search_highlight')) && ! empty($highlight)) {
return [];
}

return ['search_highlight' => Arr::get(Arr::first($highlight), 'snippet')];
}
}
31 changes: 31 additions & 0 deletions tests/Unit/IndexTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,35 @@ public function it_sorts_by_specified_order()

$this->assertSame(['Entry 2', 'Entry 1'], collect($results['results'])->pluck('title')->all());
}

#[Test]
public function it_adds_search_highlight()
{
$entry1 = Facades\Entry::make()
->id('test-2')
->collection('pages')
->data(['title' => 'Entry 1'])
->save();

$results = Facades\Search::index('typesense_index')->searchUsingApi('Entry 1');

$this->assertEquals('<mark>Entry</mark> <mark>1</mark>', $results['results'][0]['search_highlight']['title']['snippet']);
}

#[Test]
public function it_augments_with_search_highlight()
{
$entry1 = Facades\Entry::make()
->id('test-2')
->collection('pages')
->data(['title' => 'Entry 1'])
->save();

$index = Facades\Search::index('typesense_index');
$result = $index->search('Entry 1')->get()->first();

$augmentedData = $index->extraAugmentedResultData($result);

$this->assertSame(['search_highlight' => '<mark>Entry</mark> <mark>1</mark>'], $augmentedData);
}
}
Loading