简体   繁体   中英

Laravel Scout check if index exists

I can't find documentation on how to check with Laravel Scout if an index exists or not.

I'm using it with meilisearch. My models have the Searchable trait.

This is how I want to access the index and check for search results:

$tasks = Task::search(
  query: trim($query) ?? '',
)->take(self::NUMBER_OF_SEARCHRESULTS_PER_MODEL)->get();

What I get is 'MeiliSearch \ Exceptions \ ApiException Index tasks not found.'

Another weird behavior, even though I execute scout:import "App\Models\Task" before, and it tells me that all records have been imported, meilisearch is not creating the index, if there are no records in the DB.

Therefor the above code results in the exception.

What I'd like to do now to prevent that, is something like this:

$tasksScoutBuilder = Task::search(
  query: trim($query) ?? '',
);

$tasks = ($tasksScoutBuilder->indexExists()) ? $tasksScoutBuilder->take(self::NUMBER_OF_SEARCHRESULTS_PER_MODEL)->get() : collect(); 

How can I check if the index for the model exists or not?

Before anything you should configuration model .you can overriding the searchableAs method on the model,if the index does not exist,Laravel throw exception like index_not_found_exception , for ex

public function searchableAs()
    {
        return 'posts_index';
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM