From f67ae25b13714a3e80717d75bd02a200be37ff48 Mon Sep 17 00:00:00 2001 From: "Christopher C. Wells" Date: Mon, 5 Apr 2021 21:07:40 -0700 Subject: [PATCH] Add support for a fallback when `SCOUT_DRIVE` is NULL --- .../IngredientPickerController.php | 66 +++++++++++++------ 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/app/Http/Controllers/IngredientPickerController.php b/app/Http/Controllers/IngredientPickerController.php index 7bdbba7..83a5888 100644 --- a/app/Http/Controllers/IngredientPickerController.php +++ b/app/Http/Controllers/IngredientPickerController.php @@ -20,28 +20,54 @@ class IngredientPickerController extends Controller $results = new Collection(); $term = $request->query->get('term'); if (!empty($term)) { - $results = Food::boolSearch() - ->join(Recipe::class) + $results = match (env('SCOUT_DRIVER')) { + 'elastic' => $this->searchWithElasticSearch($term), + default => $this->searchWithDatabaseLike($term), + }; - // Attempt to match exact phrase first. - ->should('match_phrase', ['name' => $term]) - - // Attempt multi-match search on all relevant fields with search-as-you-type on name. - ->should((new MultiMatchQueryBuilder()) - ->fields(['name', 'name._2gram', 'name._3gram', 'detail', 'brand', 'source']) - ->query($term) - ->type('bool_prefix') - ->analyzer('simple') - ->fuzziness('AUTO')) - - // Attempt to match on any tags in the term. - ->should((new TermsQueryBuilder()) - ->terms('tags', explode(' ', $term))) - - // Get resulting models. - ->execute() - ->models(); } return response()->json($results->values()); } + + /** + * Search using an ElasticSearch service. + */ + private function searchWithElasticSearch(string $term): Collection { + return Food::boolSearch() + ->join(Recipe::class) + + // Attempt to match exact phrase first. + ->should('match_phrase', ['name' => $term]) + + // Attempt multi-match search on all relevant fields with search-as-you-type on name. + ->should((new MultiMatchQueryBuilder()) + ->fields(['name', 'name._2gram', 'name._3gram', 'detail', 'brand', 'source']) + ->query($term) + ->type('bool_prefix') + ->analyzer('simple') + ->fuzziness('AUTO')) + + // Attempt to match on any tags in the term. + ->should((new TermsQueryBuilder()) + ->terms('tags', explode(' ', $term))) + + // Get resulting models. + ->execute() + ->models(); + } + + /** + * Search using basic database WHERE ... LIKE queries. + */ + private function searchWithDatabaseLike(string $term): Collection { + $foods = Food::query()->where('foods.name', 'like', "%{$term}%") + ->orWhere('foods.detail', 'like', "%{$term}%") + ->orWhere('foods.brand', 'like', "%{$term}%") + ->get(); + $recipes = Recipe::query()->where('recipes.name', 'like', "%{$term}%") + ->orWhere('recipes.description', 'like', "%{$term}%") + ->orWhere('recipes.source', 'like', "%{$term}%") + ->get(); + return $foods->merge($recipes); + } }