phplaravelalgoliaadvanced-search

Algolia: searching multiple indices in Laravel


I would like to set up algolia to search multiple indices in Laravel, using something simple like this.

Route::get('/search/{query}', function ($query) {
$queries = [
    [
        'indexName' => 'movies_index',
        'query' => $query,
        'hitsPerPage' => 3
    ],
    [
        'indexName' => 'directors',
        'query' => $query,
        'hitsPerPage' => 3,
    ],
    [
        'indexName' => 'screenwriters',
        'query' => $query,
        'hitsPerPage' => 10
    ]
];



var_dump($queries);});

But I'm a beginner in laravel and algolia as well so I'm not entirely sure how to go on about it.


Solution

  • As per the Algolia Docs states:

    // perform 3 queries in a single API call:
    //  - 1st query targets index `categories`
    //  - 2nd and 3rd queries target index `products`
    
    $queries = [
      [
        'indexName' => 'categories',
        'query' => $myQueryString,
        'hitsPerPage' => 3
      ],
      [
        'indexName' => 'products',
        'query' => $myQueryString,
        'hitsPerPage' => 3,
        'facetFilters' => 'promotion'
      ],
      [
        'indexName' => 'products',
        'query' => $myQueryString,
        'hitsPerPage' => 10
      ]
    ];
    
    $results = $client->multipleQueries($queries);
    
    var_dump($results['results']);
    

    Don't forget to initialize your $client first:

    $client = new \AlgoliaSearch\Client('APP_ID', 'APP_KEY');