Skip to content

Searching with Meilisearch Bundle

Tomas Norkūnas edited this page Mar 6, 2024 · 3 revisions

Once you've configurated all of your indexes and indexed some documents you should be good to search them!

A basic search in your Quote entity can be:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Quote;

use Meilisearch\Bundle\SearchService;

final class QuoteController extends AbstractController
{
    #[Route('/search')]
    public function search(EntityManagerInterface $entityManager, SearchService $searchService, Request $request): Response 
    {
        $searchQuery = $request->query->get('q') ?? '';

        $hits = $searchService->search($entityManager, Quote::class, $searchQuery); 

        return $this->render(
            'quote/index.html.twig',
            [
                'quotes' => $hits,
                'q' => $searchQuery,
            ]
        );
    }
}

⚠️ remember you must have indexed your data before doing searches (or at least create the indexes) to avoid index not found error!