add of typesense container, searchEvents route and SearchController and method
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Typesense\Client;
|
||||
use Exception;
|
||||
use App\Models\Events;
|
||||
|
||||
class SearchController extends Controller
|
||||
{
|
||||
protected Client $client;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->client = new Client([
|
||||
'api_key' => 'xyz',
|
||||
'nodes' => [
|
||||
[
|
||||
'host' => env('TYPESENSE_CONNECTION'),
|
||||
'port' => '8108',
|
||||
'protocol' => 'http',
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
private function createEventsCollection()
|
||||
{
|
||||
try {
|
||||
$collections = $this->client->collections->retrieve();
|
||||
|
||||
if (!in_array('events', array_column($collections, 'name'))) {
|
||||
$this->client->collections->create([
|
||||
'name' => 'events',
|
||||
'fields' => [
|
||||
['name' => 'name', 'type' => 'string'],
|
||||
['name' => 'description', 'type' => 'string'],
|
||||
],
|
||||
]);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
throw new Exception("Error while creating the events collection : " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function indexEvents()
|
||||
{
|
||||
try {
|
||||
$events = Events::all();
|
||||
|
||||
foreach ($events as $event) {
|
||||
|
||||
$this->client->collections['events']->documents->upsert([
|
||||
'id' => (string) $event->id,
|
||||
'name' => $event->name,
|
||||
'description' => $event->description,
|
||||
]);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
throw new Exception("Error while indexing events : " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function searchEvents(Request $request)
|
||||
{
|
||||
try {
|
||||
$this->createEventsCollection();
|
||||
$this->indexEvents();
|
||||
$query = $request->input('query', '');
|
||||
|
||||
$searchResults = $this->client->collections['events']->documents->search([
|
||||
'q' => $query,
|
||||
'query_by' => 'name,description',
|
||||
]);
|
||||
|
||||
return response()->json($searchResults);
|
||||
} catch (Exception $e) {
|
||||
return response()->json(['error' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user