laravel / scout

Laravel Scout provides a driver based solution to searching your Eloquent models.
https://laravel.com/docs/scout
MIT License
1.57k stars 336 forks source link

Support multiple indexes per model #727

Closed rrmesquita closed 1 year ago

rrmesquita commented 1 year ago

Right now, Scout already allows you to choose on which index the user wants to perform a given search query (via the within() method), but I don't get the point of that since each model only supports one index.

What if the searchableAs() method could return an array of index names for each model, and Scout worked with some default index name that would be the first item in that array, and make it customizable via some defaultSearchableAs() method, that then should only return one string.

Say you have the following piece of data:

{
  "furniture": [
    {
      "id": 1,
      "name": "Eldorado Chair",
      "seller": "John Doe",
      "price": 100
    },
    {
      "id": 2,
      "name": "Monica Table",
      "seller": "John Doe",
      "price": 100
    },
    {
      "id": 3,
      "name": "Davenport Couch",
      "seller": "A. H. Davenport",
      "price": 100
    },
    {
      "id": 4,
      "name": "Celestial Globe",
      "seller": "Cicero",
      "price": 100
    }
  ]
}

What I want is to be able to search on both the name and seller fields, using different search terms. If this feature were implemented, I could do something like:

class Product extends Model
{
  public function searchableAs(): array
  {
    // model observer would work on both indexes
    return ['products_name', 'products_seller'];
  }
}

And in the controller I could have something like:

$search = [
  'name' => 'chair',
  'seller' => 'john doe'
];

$name_results = Product::search($search['name'])->within('products_name')->get();
$seller_results = Product::search($search['seller'])->within('products_seller')->get();

// some logic to merge the results

I understand that allowing such a configuration would mean creating multiple indexes based on the same group of data, and if poorly configured, it could significantly escalate resource consumption. Also, it can bring some unwanted complexity to the Scout library. Despite these drawbacks, I believe that this feature could unlock much more robust search capabilities, and the scenario I just described is prevalent based on the online discussions I have come across.

FYI: this conversation in meilisearch/product discusses how a similar result could be achieved on the search engine side.

driesvints commented 1 year ago

Thank you for your suggestion. If you could send in a PR for us to have a look at that'd be great. Thanks!