Reputation: 3
So i have intergrated elasticsearch to my laravel app and everyhting works fine when i search manually , it does the indexes and everything its just that whenever i use the engine search() methode it always returns null and i don't know why, take a look:
public function search(Builder $builder)
{
// Get the search query from the builder
$query = $builder->query;
// Define the Elasticsearch search parameters
$params = [
'index' => 'products_index', // Use the specified index or search in all indices
'body' => [
'query' => [
'match' => [
'title' => $query
],
],
],
];
// Perform the search using the Elasticsearch client
$response = $this->elasticsearch->search($params);
// Extract the hits from the response
$hits = $response['hits']['hits'];
// Check if the hits contain the expected _source field
if (empty($hits)) {
Log::warning('No hits found in the search response');
return [];
}
// Map the search results to Eloquent models
$models = [];
foreach ($hits as $hit) {
// Assuming each document in Elasticsearch corresponds to a single Eloquent model
if (isset($hit['_source'])) {
$models[] = $this->map($builder, $hit, $builder->model);
} else {
Log::error('Missing _source field in search result', ['hit' => $hit]);
}
}
dump($models);
return $models;
}
public function map(Builder $builder, $results, $model)
{
/*$modelInstance = null;*/
// Check if the '_source' key exists in the results
if ($results && isset($results['_source'])) {
Log::warning('every thing seem fine');
// Get the primary key name of the model
$keyName = $model->getKeyName();
// Create a new instance of the model
$modelInstance = $model->newInstance();
// Set the raw attributes of the model from the Elasticsearch source
$modelInstance->setRawAttributes($results['_source']);
// Set the primary key attribute of the model
$modelInstance->setAttribute($keyName, $results['_id']);
return $modelInstance;
}else Log::error('Missing _source field in search results', ['results' => $results]);
}
whenever i use Product::search($query)->get(); as you can see in my search() methode i have wrote a dump() above the return. the dump($model) works and shows the result but the return is null
I mean is there anything im missing?
p.s and for some reasone even when i empty the search methode, when i search, the engine runs the map() methode!!!!
i have searched alot and used logs and AIs but so far nothing.
Upvotes: 0
Views: 68