As you know, using where()
statement after the search method uses numericFilter
. I am trying to filter my search results with string filtering.
How can I use Facet Filter on search statement?
As you know, using where()
statement after the search method uses numericFilter
. I am trying to filter my search results with string filtering.
How can I use Facet Filter on search statement?
An answer here helped me. I want to share my code snippets, maybe it will help someone else. My model:
public function toSearchableArray()
{
// Define the attributes you want to make searchable in Algolia
return [
'title' => $this->title,
'description' => $this->description,
'status' => $this->status,
'address' => $this->address,
];
}
public function getScoutSettings()
{
return [
'attributesForFaceting' => [
'filterOnly(status)',
'filterOnly(address)',
// Add other attributes for faceting
],
];
}
My search query:
$query = request('query');
$address = request('address');
$posts = Post::search($query, function ($algolia, $query, $options) use($address){
$new_options = [
"facetFilters"=>
["status:1","address:".$address],
];
return $algolia->search($query, array_merge($options,$new_options));
})->paginate(12);
According to the algolia documentation you can modify the search parameters like this:
$results = Product::search($q)->with(
[
'facets' => ['*'],
'facetFilters' => [$facetFilters],
]
)->paginate(24);
https://www.algolia.com/doc/framework-integration/laravel/searching/server-side-search/
I am glad to answer my own problem. First of all, it's really hard to find any doc about the Laravel Scout already. If you want to filter your search results with string parameters. Even it's really hard to find an answer too. I checked the whole library line by line.Finally, the result made me proud.
If you want to filter your result with string parameters you need to design callback function to your
search()
method and inject your FacetFilters on there.Simply, Let's assume you havePosts
model that you are using Algolia and you have enum typedcategory
column on it. You can filter your blog post search results with the code below.