Code Monkey home page Code Monkey logo

meilisearch-laravel-scout's Introduction

MeiliSearch Laravel Scout

[DEPRECATED] MeiliSearch Laravel Scout

Latest Stable Version Actions Status License Bors enabled

⚡ The MeiliSearch driver for Laravel Scout


⚠️ This package is deprecated. We recommend you to use Laravel Scout that now supports MeiliSearch.


MeiliSearch Laravel Scout is a MeiliSearch driver for Laravel.

MeiliSearch is an open-source search engine. Discover what MeiliSearch is!

Table of Contents

📖 Documentation

See our Documentation or our API References.

Also, take a look at the Wiki of this repository!

🔧 Installation

Install the Plugin

composer require meilisearch/meilisearch-laravel-scout

Install the HTTP Client

You could use any PSR-18 compatible client to use with this SDK. No additional configurations are required.
A list of compatible HTTP clients and client adapters can be found at php-http.org.

If you use Laravel 8 you can skip this section as laravel pre-install Guzzle 7 by default.

Guzzle 7:

composer require guzzlehttp/guzzle

If you already have guzzle installed with a version < 7, don't forget to update the version inside your composer.json

"require": {
  "guzzlehttp/guzzle": "^7.0"
}

Guzzle 6:

composer require php-http/guzzle6-adapter

Symfony Http Client:

composer require symfony/http-client nyholm/psr7

Curl:

composer require php-http/curl-client nyholm/psr7

Export Configuration

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="Meilisearch\Scout\MeilisearchServiceProvider" --tag="config"

Update the .env file

SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=http://127.0.0.1:7700
MEILISEARCH_KEY=masterKey

Run MeiliSearch

There are many easy ways to download and run a MeiliSearch instance.

For example, if you use Docker:

docker run -it --rm -p 7700:7700 getmeili/meilisearch:latest ./meilisearch --master-key=masterKey

NB: you can also download MeiliSearch from Homebrew or APT.

🚀 Getting Started

Indexes

Create an Index

// Create an index
php artisan scout:index books
// Create an index and give the primary-key
php artisan scout:index books --key book_id

Add Documents

<?php

use Laravel\Scout\Searchable;

class Book extends Model
{
    use Searchable;
}
<?php

class BookController extends Controller
{
    public function store()
    {
        $book = new Book();
        $book->title = 'Pride and Prejudice';
        ...
        $book->save();
    }
}

You can also import all your table to meilisearch by using the artisan command:

php artisan scout:import "App\Book"

Search in an Index

class BookController extends Controller
{
    public function search()
    {
        // MeiliSearch is typo-tolerant:
        Book::search('harry pottre')->get();
        // Or if you want to get the result from meilisearch:
        Book::search('harry pottre')->raw();
    }
}

Delete Documents

class BookController extends Controller
{
    public function destroy($id)
    {
        // Delete one document
        Book::find($id)->delete();
        // Delete several documents
        Book::destroy([1, 42]);
        // Delete all documents /!\
        Book::query()->delete();
    }
}

or you can use the artisan command to delete all documents from an index:

php artisan scout:flush "App\Book"

Delete an Index

php artisan scout:index -d books

Search

Custom Search

All the supported options are described in the search parameters section of the documentation.

use MeiliSearch\Endpoints\Indexes;

class BookController extends Controller
{
    public function customSearch()
    {
        Book::search('prince', function (Indexes $meilisearch, $query, $options) {
            $options['filters'] = 'author="Antoine de Saint-Exupéry"';

            return $meilisearch->search($query, $options);
        })->take(3)->get();
    }
}

Pagination

class BookController extends Controller
{
    public function search()
    {
        Book::search('mustang')->paginate();
        // with a limit of items per page:
        Book::search('mustang')->paginate(5);
        // using meilisearch response:
        Book::search('mustang')->paginateRaw();
    }
}

🤖 Compatibility with MeiliSearch

This package only guarantees the compatibility with the version v0.20.0 of MeiliSearch.

💡 Learn More

If you're not familiar with MeiliSerach yet, the following sections may interest you:

💡 You can use more advance function by reading the documentation of MeiliSearch PHP Client.

👍 This package is a custom engine of Laravel Scout.

Development Workflow and Contributing

Any new contribution is more than welcome in this project!

If you want to know more about the development workflow or want to contribute, please visit our contributing guidelines for detailed instructions!


MeiliSearch provides and maintains many SDKs and Integration tools like this one. We want to provide everyone with an amazing search experience for any kind of project. If you want to contribute, make suggestions, or just know what's going on right now, visit us in the integration-guides repository.

meilisearch-laravel-scout's People

Contributors

alifjafar avatar bensherred avatar bors[bot] avatar cannonb4ll avatar cappuc avatar curquiza avatar dependabot-preview[bot] avatar dichotommy avatar josecanhelp avatar jwohlfert23 avatar lkmadushan avatar matboivin avatar meili-bot avatar mmachatschek avatar pet1330 avatar qdequele avatar shokme avatar willvincent avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

meilisearch-laravel-scout's Issues

I can't index my documents (they are ok at Algolia)

I'm using Laravel 7, MS 0.13
I'm trying to index my model using:
php artisan scout:import "App\Models\Product"
Then I do (local_product is my index):
curl -X GET 'http://localhost:7700/indexes/local_product/documents'
And I get []

If I index in Algolia, my documents are ok there.
Also if I index movies doing:
curl -X POST 'http://127.0.0.1:7700/indexes/movies/documents' --data @movies.json
The movies are also indexed.

Include facetsDistribution in paginate() response?

Loving Meilisearch so far, guys... Only think holding me back from integrating it into our app is a lack of clarity on how to access the extra metadata like facetsDistribution.

I can currently access facetsDistribution by using raw() when executing the query, so my temporary workaround is calling the raw search function, then the traditional paginate query right afterwards. Is there a way to integrate the facetsDistribution response into the paginate response so I don't have to do this hacky, resource-intensive workaround?

Thanks!

A primary key is already present. It's impossible to update it

New instalation of the latest version of Laravel 8, with one some users in the database.

When running this command:
php artisan scout:import "App\Models\User"

The response is:

MeiliSearch\Exceptions\HTTPRequestException 

  A primary key is already present. It's impossible to update it

  at [Project Path]\vendor\meilisearch\meilisearch-php\src\Http\Client.php:182
    178▕     private function parseResponse(ResponseInterface $response)
    179▕     {
    180▕         if ($response->getStatusCode() >= 300) {
    181▕             $body = json_decode($response->getBody()->getContents(), true) ?? $response->getReasonPhrase();
  ➜ 182▕             throw new HTTPRequestException($response->getStatusCode(), $body);
    183▕         }
    184▕
    185▕         return json_decode($response->getBody()->getContents(), true);
    186▕     }

  1   [Project Path]\vendor\meilisearch\meilisearch-php\src\Http\Client.php:165
      MeiliSearch\Http\Client::parseResponse(Object(GuzzleHttp\Psr7\Response))

  2   [Project Path]\vendor\meilisearch\meilisearch-php\src\Http\Client.php:101
      MeiliSearch\Http\Client::execute(Object(GuzzleHttp\Psr7\Request))

Seems like this scout driver is making the post request to 127.0.0.1:63076 "POST /indexes/users/documents?primaryKey=id HTTP/1.1" 400 232 "-" "GuzzleHttp/7" 0.000152 and because the post contains the query param primaryKey=id the import fails.

This seems to be an issue with the meilisearch documentation as it clearly states on this page

If you want to set the primary key of your index through this route, it only has to be done the first time you add documents to the index. After which it will be ignored if given.

However when I test the post with Insomnia/Postman the same error happens if I add ?primaryKey=id so the documentation is wrong or meilisearch doesn't handle properly the primaryKey properly (shouldn't raise an error if the primaryKey is the same with the one already defined on the index).
I'll probably open an issue on the meilisearch documentation repo too but this issue needs to be fixed in this scout driver too.

I've been trying to set up this scout driver in my project for the last 2 days and seems like there are a couple of more issues and I started to question myself, is meilisearch production ready? They seem to change a lot of things and leave documentation behind with the updates. Does anyone else use it in production for let's say 1M small documents?

Custom pagination with totalCount

Hi,

I want to use "cursor" pagination with offset and limit.

How can I get the total count of documents in the following example?

        $result = Book::search('', function (Indexes $meilisearch, $query, $options) {
            $options['offset'] = 5;
            $options['limit'] = 30;
            return $meilisearch->search($query, $options);
        });

        return [
            'data' => $result->get(),
            'totalCount' => 0 // I want to know how many documents are in the index.
        ];

[DX] Easy index configuration

Hi, thanks for your time!

Just noticed on wiki page some alternative to configure indexes. But i think it adds a extra boilerplate to the project.

Suggestions for simplicity about config meilisearch index:

  • Via Model, using a protected property as array representing the “index config”, with same options as described on wiki page.

  • Via config/meilisearch.php file, with the same options as described on wiki page.

Method Laravel\Scout\Builder::limit does not exist.

Hi,

It seems the limit() option is not available, if I read the documentation it seems it should be available.

$items = FaqItem::search(request('query'))->limit(5)->get();

Returns me with an error:

exception: "BadMethodCallException"
file: "/Users/***/Workspace/***/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php"
line: 103
message: "Method Laravel\Scout\Builder::limit does not exist."

Is there something I am missing, or is this method missing from the package?

heed error; No space left on device: MeiliSearch\Exceptions\HTTPRequestException

We have a job that updates our product database. While running this job, we keep running into os error 32: heed error; No space left on device.

Have checked diskspace and inode utilization however plenty are available for use. Have updated to the newest version of the meilisearch-laravel-scout client yet the issue still persists.

This issue occurs when updating a database record that uses the searchable trait.

"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^7.0",
"laravel/scout": "^8.3",
"meilisearch/meilisearch-laravel-scout": "^0.12.0",

Stacktrace:

[2020-11-24 12:05:08] production.ERROR: heed error; No space left on device (os error 28) {"exception":"[object] (MeiliSearch\\Exceptions\\HTTPRequestException(code: 500): heed error; No space left on device (os error 28) at /home/backend/app/vendor/meilisearch/meilisearch-php/src/Http/Client.php:182)
[stacktrace]
#0 /home/backend/app/vendor/meilisearch/meilisearch-php/src/Http/Client.php(165): MeiliSearch\\Http\\Client->parseResponse()
#1 /home/backend/app/vendor/meilisearch/meilisearch-php/src/Http/Client.php(101): MeiliSearch\\Http\\Client->execute()
#2 /home/backend/app/vendor/meilisearch/meilisearch-php/src/Endpoints/Delegates/HandlesDocuments.php(29): MeiliSearch\\Http\\Client->post()
#3 /home/backend/app/vendor/meilisearch/meilisearch-laravel-scout/src/Engines/MeilisearchEngine.php(59): MeiliSearch\\Endpoints\\Indexes->addDocuments()
#4 /home/backend/app/vendor/laravel/scout/src/Searchable.php(63): Meilisearch\\Scout\\Engines\\MeilisearchEngine->update()
#5 /home/backend/app/vendor/laravel/scout/src/Searchable.php(42): App\\Models\\Product->queueMakeSearchable()
#6 /home/backend/app/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php(114): Illuminate\\Database\\Eloquent\\Collection->Laravel\\Scout\\{closure}()
#7 /home/backend/app/vendor/laravel/scout/src/Searchable.php(154): Illuminate\\Support\\Collection->__call()
#8 /home/backend/app/vendor/laravel/scout/src/ModelObserver.php(69): App\\Models\\Product->searchable()
#9 /home/backend/app/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(401): Laravel\\Scout\\ModelObserver->saved()
#10 /home/backend/app/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(226): Illuminate\\Events\\Dispatcher->Illuminate\\Events\\{closure}()
#11 /home/backend/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php(189): Illuminate\\Events\\Dispatcher->dispatch()
#12 /home/backend/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(771): Illuminate\\Database\\Eloquent\\Model->fireModelEvent()
#13 /home/backend/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(742): Illuminate\\Database\\Eloquent\\Model->finishSave()
#14 /home/backend/app/app/Jobs/BatchUpdateProducts.php(71): Illuminate\\Database\\Eloquent\\Model->save()
#15 /home/backend/app/vendor/laravel/framework/src/Illuminate/Redis/Limiters/DurationLimiter.php(90): App\\Jobs\\BatchUpdateProducts->App\\Jobs\\{closure}()
#16 /home/backend/app/vendor/laravel/framework/src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php(113): Illuminate\\Redis\\Limiters\\DurationLimiter->block()
#17 /home/backend/app/app/Jobs/BatchUpdateProducts.php(77): Illuminate\\Redis\\Limiters\\DurationLimiterBuilder->then()
#18 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): App\\Jobs\\BatchUpdateProducts->handle()
#19 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/Util.php(37): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#20 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\Util::unwrapIfClosure()
#21 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::callBoundMethod()
#22 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/Container.php(596): Illuminate\\Container\\BoundMethod::call()
#23 /home/backend/app/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\\Container\\Container->call()
#24 /home/backend/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\Bus\\Dispatcher->Illuminate\\Bus\\{closure}()
#25 /home/backend/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#26 /home/backend/app/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\\Pipeline\\Pipeline->then()
#27 /home/backend/app/vendor/laravel/framework/src/Illuminate/Foundation/Bus/Dispatchable.php(53): Illuminate\\Bus\\Dispatcher->dispatchNow()
#28 /home/backend/app/app/Console/Commands/ProductsUpdate.php(62): App\\Jobs\\BatchUpdateProducts::dispatchNow()
#29 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): App\\Console\\Commands\\ProductsUpdate->handle()
#30 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/Util.php(37): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#31 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\Util::unwrapIfClosure()
#32 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::callBoundMethod()
#33 /home/backend/app/vendor/laravel/framework/src/Illuminate/Container/Container.php(596): Illuminate\\Container\\BoundMethod::call()
#34 /home/backend/app/vendor/laravel/framework/src/Illuminate/Console/Command.php(134): Illuminate\\Container\\Container->call()
#35 /home/backend/app/vendor/symfony/console/Command/Command.php(258): Illuminate\\Console\\Command->execute()
#36 /home/backend/app/vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Symfony\\Component\\Console\\Command\\Command->run()
#37 /home/backend/app/vendor/symfony/console/Application.php(920): Illuminate\\Console\\Command->run()
#38 /home/backend/app/vendor/symfony/console/Application.php(266): Symfony\\Component\\Console\\Application->doRunCommand()
#39 /home/backend/app/vendor/symfony/console/Application.php(142): Symfony\\Component\\Console\\Application->doRun()
#40 /home/backend/app/vendor/laravel/framework/src/Illuminate/Console/Application.php(93): Symfony\\Component\\Console\\Application->run()
#41 /home/backend/app/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\\Console\\Application->run()
#42 /home/backend/app/artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle()

Double forward slashes - route generation.

Just curious if anyone is experiencing routes being generate with a double forward slash on requests (ending up within incoming requests to the Meilisearch server like POST //indexes//documents?primaryKey=id (taken from the console), it's resulting in 404's not found with the server, when built with the binary.
I'm not really sure where to go from here. When I generate a HTTP request via a rest client it all works fine. Anyone else have any issues?
Current version used is 0.10.0

Remove the usage of nbHits from the code base

The value nbHits returned by MeiliSearch is not a trustable value since it's not an exhaustive value. nbHits is indeed not reliable for pagination because can be exhaustive or not, depending on the value of exhaustiveNbHits that MeiliSearch returns which is always false

We should implement the pagination as described here: meilisearch/documentation#561


FYI: The Meili team is aware of the confusion with nbHis. Here are the different issues and comments about it to explain why it's confusing, and why we should not use it:

We are sorry for this. We all hope this confusion will be fixed asap in MeiliSearch.


Related to #95

Create Wiki pages or any accessible docs

The purpose of this issue is to provide a Wiki documentation that cannot be written down in the README.
We could add a How to section to explain how to handles indexes, synonyms, and other settings even if it's not the first purpose of this package.

(Following this discussion on #45)

Change master branch to main

Let's be allies and make this change that means a lot.

Here is a blog post that explain a little more why it's important, and how to easily do it. It will be a bit more complicated with automation, but we still should do it!

Wrong parameters for MeiliSearch\Exceptions\HTTPRequestException

Started getting this exception after upgrading to the latest version yesterday of this package.

Stacktrace:

[2020-08-10 15:22:11] production.ERROR: Wrong parameters for MeiliSearch\Exceptions\HTTPRequestException([string $message [, long $code [, Throwable $previous = NULL]]]) {"exception":"[object] (Error(code: 0): Wrong parameters for MeiliSearch\\Exceptions\\HTTPRequestException([string $message [, long $code [, Throwable $previous = NULL]]]) at /home/redacted/vendor/meilisearch/meilisearch-php/src/Exceptions/HTTPRequestException.php:20)
[stacktrace]
#0 /home/redacted/vendor/meilisearch/meilisearch-php/src/Exceptions/HTTPRequestException.php(20): Exception->__construct()
#1 /home/redacted/vendor/meilisearch/meilisearch-php/src/Http/Client.php(182): MeiliSearch\\Exceptions\\HTTPRequestException->__construct()
#2 /home/redacted/vendor/meilisearch/meilisearch-php/src/Http/Client.php(165): MeiliSearch\\Http\\Client->parseResponse()
#3 /home/redacted/vendor/meilisearch/meilisearch-php/src/Http/Client.php(101): MeiliSearch\\Http\\Client->execute()
#4 /home/redacted/vendor/meilisearch/meilisearch-php/src/Endpoints/Delegates/HandlesDocuments.php(29): MeiliSearch\\Http\\Client->post()
#5 /home/redacted/vendor/meilisearch/meilisearch-laravel-scout/src/Engines/MeilisearchEngine.php(59): MeiliSearch\\Endpoints\\Indexes->addDocuments()
#6 /home/redacted/vendor/laravel/scout/src/Jobs/MakeSearchable.php(42): Meilisearch\\Scout\\Engines\\MeilisearchEngine->update()
#7 [internal function]: Laravel\\Scout\\Jobs\\MakeSearchable->handle()

install error with laravel 7

when i try to install meilisearch-laravel-scout with laravel 7
it shows error:


composer require meilisearch/meilisearch-laravel-scout

Problem 1
    - Installation request for meilisearch/meilisearch-laravel-scout ^0.11.0 -> satisfiable by meilisearch/meilisearch-laravel-scout[v0.11.0].
    - Can only install one of: guzzlehttp/guzzle[6.5.x-dev, 7.0.1].
    - Can only install one of: guzzlehttp/guzzle[7.0.1, 6.5.x-dev].
    - Can only install one of: guzzlehttp/guzzle[6.5.x-dev, 7.0.1].
    - Conclusion: install guzzlehttp/guzzle 6.5.x-dev
    - Installation request for guzzlehttp/guzzle (locked at 7.0.1, required as ^7.0) -> satisfiable by guzzlehttp/guzzle[7.0.1].

Master Key

Hi all, thx

I need someone to explain to me how I generate the master key and the others, I don't quite understand that part, I'm sorry.

thx

Bug with symfony/http-client

As you know symfony/http-client is required in plenty of packages but it was giving me the error so I removed them to test meilisearch than installed http/guzzle6-adapter and everything seems to work ok than I installed the packages that I have removed they installed symfony/http-client and as I guess laravel gives priority to it and I am getting this error again. I have also tried to install symfony/http-client nyholm/psr7 as you suggested in readme but still getting the error. What do you think what will be solution for it.

Have also tried to update guzzle to 7.0 but still not working as expected, I think there is something with php version what will be your solution?

Using:
Laravel: 6.18.40
PHP: 7.4.5

Any request to mailisearch using symfony/http-client returns the error:

   ErrorException  : Trying to access array offset on value of type null

  at /var/www/vendor/symfony/http-client/HttpClientTrait.php:417
    413|                     $url['query'] = '?'.self::mergeQueryString(substr($url['query'] ?? '', 1), $queryDefaults, false);
    414|                 }
    415|             }
    416| 
  > 417|             $url['scheme'] = $base['scheme'];
    418|         }
    419| 
    420|         if ('' === ($url['path'] ?? '')) {
    421|             $url['path'] = '/';

  Exception trace:

  1   Illuminate\Foundation\Bootstrap\HandleExceptions::handleError()
      /var/www/vendor/symfony/http-client/HttpClientTrait.php:417

  2   Symfony\Component\HttpClient\CurlHttpClient::resolveUrl()
      /var/www/vendor/symfony/http-client/HttpClientTrait.php:141

Missing results

I have tried with the movies.json example to test with the searches and if I look for the Ready Player One movie it does not find it. I have looked at the movies.json file and I found it, when importing it has been imported without problems.

I've been looking at the documentation but I can't see if the configuration needs to be adjusted, I was just with a project where I have a database with 486610 films with Laravel Scout and all of them are imported well and the same thing happened with the Ready Player film One so I have tried with the example.

Error when setup attributesToHighlight

I did:

 Product::search($this->search, ['attributesToHighlight' => 'name'])->take(10)->get();

and I got this error:

call_user_func() expects parameter 1 to be a valid callback, array must have exactly two members

Screenshot

Creating index using php artisan not working

Hi Guys,

Great package so far. I have a small issue: I cannot create an index using artisan command.

I get this error for: php artisan scout:index myindexname
Argument 1 passed to MeiliSearch\Client::__construct() must be of the type string, null given....

I'm using:
Laravel 8
PHP 7.4

Any help would be appreciated!
Thanks,
Mihai

cant find any good example tutorial ,correct me if iam doing wrong

With formal knowledge in creating custom search engine for one of my project i managed to make it work
idk this is the right way to use it if not please advise
i have multiple models with one common field row_no in each .
first installed meilisearch using curl and run on 127.0.0.1:7700 then i added this module using composer and published and
created indexes and imported all data
from given code samples search is from individual model since i have multiple models and want to use single search function
i found meilisearch /meilisearch-php as useful and added a dropdown to select facet during search and i change index dynamically on selected facet

$client = new Client('http://127.0.0.1:7700', 'key');
        $index = $client->index($index);

this is working as expected but is there any simple way without using meilisearch /meilisearch-php
api and cdn are not fit for me and i don't like to include node modules in this simple project
any alternatives ?

[Question] Custom search with where()

Hi,

I am trying to combine custom search with where().

But the ->where('type_id', 3) does not take effect

 $result = Page::search('War', function (Indexes $meilisearch, $query, $options) {
            $options = ['attributesToHighlight' => ['description']];
            return $meilisearch->search($query, $options);
        })->where('type_id', 3)->raw();

If i do a simple search it works as expected. But, for sure, i dont get hililght anymore.

 $result = Page::search('War')->where('type_id', 3)->raw();

Guzzle 6

Hello. How can i use it with guzzle 6 without updating? Can't update right now, project has a lot of dependencies with require guzzle ^6.0.

Cannot use object of type MeiliSearch\Search\SearchResult as array

I'm trying to add a custom search as seen in the example:

return Book::search('prince', function (Indexes $meilisearch, $query, $options) {
            $options['limit'] = 10000;

            return $meilisearch->search($query, $options);
        })->get();

This always returns the following error:

[2021-01-29 13:53:27] local.ERROR: Cannot use object of type MeiliSearch\Search\SearchResult as array {"userId":1,"exception":"[object] (Error(code: 0): Cannot use object of type MeiliSearch\\Search\\SearchResult as array at /srv/http/project/api/vendor/meilisearch/meilisearch-laravel-scout/src/Engines/MeilisearchEngine.php:175)

I must be doing something wrong, does it expect to have filters set?

Thanks!

meilisearch requests fail in docker after upgrade

Hello!

I use meilisearch in docker
Laravel 7
meilisearch/meilisearch-laravel-scout: 0.10.7
guzzlehttp/guzzle: 6.3

my config

# Dockerfile
# ...
  meilisearch:
    image: getmeili/meilisearch:latest
    ports:
      - 7700:7700
    environment:
      MEILI_MASTER_KEY: masterKey
# .env
SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=meilisearch:7700
MEILISEARCH_KEY=masterKey

Works like a charm. Many thanks!

Now I'm upgrading to Laravel 8, after I update packages to
guzzlehttp/guzzle: ^7.0.1
meilisearch/meilisearch-laravel-scout: ^0.12
all requests to meilisearch fail with the message

$ php artisan scout:index some_index

   Symfony\Component\HttpClient\Psr18RequestException

  Invalid URL: scheme is missing in "//meilisearch:7700/indexes". Did you forget to add "http(s)://"?

  at vendor/symfony/http-client/Psr18Client.php:117
      113▕
      114▕             return $psrResponse->withBody($body);
      115▕         } catch (TransportExceptionInterface $e) {
      116▕             if ($e instanceof \InvalidArgumentException) {
  ➜ 117▕                 throw new Psr18RequestException($e, $request);
      118▕             }
      119▕
      120▕             throw new Psr18NetworkException($e, $request);
      121▕         }

      +22 vendor frames
  23  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

Will appreciate any help/ideas/workaround
Is there a possibility to configure HTTP Client to continue use guzzle instead of symfony/http-client (hope that may help)?

Paginated search results only return 1 page

Since updating to 1.2.3 (the issue is also present in 1.2.2. ), all searches using the following code only return 1 page.

Downgrading to 1.2.1 is necessary for the code to work correctly.

$courses = Course::_search_($this->searchString, function (Indexes $meilisearch, $query, $options) {  
        $options\['filters'\] = 'active=true';  
        return $meilisearch->search($query, $options);  
    })->paginate(12);

Meilisearch can't import products (Request Entity Too Large)

I have been trying to import products to the meilisearch and I get this error MeiliSearch\Exceptions\HTTPRequestException : Request Entity Too Large is this because of the latest version of meilisearch and how do I fix this?

private function parseResponse(ResponseInterface $response)
179| {
180| if ($response->getStatusCode() >= 300) {
181| $body = json_decode($response->getBody()->getContents(), true) ?? $response->getReasonPhrase();
> 182| throw new HTTPRequestException($response->getStatusCode(), $body);
183| }

cant use toSearchableArray method

I can't use toSearhableArray for eager loading. When I use eager loading features index not getting values. Any idea ?

    public function toSearchableArray(): array
    {
        return [
            $this->stock_code,
            $this->category->name,
            $this->name,
            $this->description,
            $this->status,
            $this->is_online,
            $this->is_active,
            optional($this->brand)->name,
            $this->mainProduct,
        ];
    }

The future of this repo

Hello everyone,

With @shokme (the main author of this package) we decided for the plan of this repository to build an integration for Laravel Scout by staying completely compliant/conformed with the original laravel/scout package.

The goal? To integrate this repository into the official laravel/scout package (as Algolia already is) by showing that people use it. We are working on this. We’ll keep you informed.

What does it mean? We did not integrate any contributions that would make the usage differ from the scout usage. Like this PR. The settings have to be handled in your models like we described in our wiki.

However, we would understand some of you would like a laravel-scout-extended integration, I mean with more friendly methods to handle settings in this repository, as this PR suggests.

The question: what do you think about making this repo an extended package and not only a strict integration with laravel-scout as we have right now?
For example, Algolia also did it with their scout-extended package.

I’m not saying it would be a priority task or an immediate and drastic change, we are not even sure this is the right choice to do, but we deeply believe it’s a good thing to have the community's opinion in mind when making decisions for the future of our repositories.
The PHP community is one of our most involved communities around MeiliSearch and all the Meili team would like to thank you for this! ❤️ Hope we will have your opinion here!

[question] how to search in related models as well ?

first many thanx for this tool, its a breeze in compare to others.

i was wondering if there is a way to search in related models as well ? i know its already an issue with scout but maybe meili could have a custom search where we can also search in other indexes and merge the results.

Skip searching by ID

Hello,

When creating toSearchableArray for a specific model, if there isn't ID included in final array, I can't import the data using php artisan scout:import "App\Book". But if I include ID, then it becomes available to search by ID also, which is behaviour I would like to escape. What is the right way to disable searching by ID?

Example code:

    public function toSearchableArray()
    {
        $array = $this->toArray();

        foreach(array_keys($array) as $key) {
            //if I unset ID also, I won't be able to import table data
            if(in_array($key, ['id', 'title', 'name'])) continue;
            unset($array[$key]);
        }

        return $array;
    }

Return all results when no term is provided

Is there currently some way to perform a search with an empty string to simply get all results? Meaning that instead of doing a search we would simply call getDocuments and apply all options to that.

Add not mocked tests

Hello everyone!

The current mock of the MeiliSearch server makes me a little worried about our tests. I would rather have tests running against a real MeiliSearch server. The goal is to be sure this package works in production against the latest version of MeiliSearch.
Indeed, MeiliSearch and meilisearch-php are not stable yet, and each modification in the MeiliSearch server enforces us to update the mock. Otherwise, our tests are not up to date with the last modifications of MeiliSearch and our package could contain errors without noticing them.

I don't say we should remove the mocked part, but we should at least have the integration test part against a real MeiliSearch server, so why not keep both? Except if you think this is too much maintenance, let's remove the mock part then.

We've done the same in the Symfony bundler package: https://github.com/meilisearch/meilisearch-symfony/blob/c764bcdb45f83941bc10d3b461ded5cf8d7f86b7/.github/workflows/tests.yml#L29-L32
And in the meilisearch-php SDK repo: https://github.com/meilisearch/meilisearch-php/blob/master/.github/workflows/tests.yml

What do you think @shokme? (just your opinion, I'm not asking you if you have time to do it of course 😁)
And also everyone, what is your opinion on it?

Metadata for search

Hey guys,

nice package / search engine. Everything seems to work so far but the meta data. How can I access e.g. which fields on the model has been hit by the search to highlight them?

Ty & Greets

PHP 7.2

A user asked us to support PHP 7.2:

Capture d’écran 2020-04-19 à 22 50 49

What do you think @shokme? 🙂 Is it a huge work?

Ranking rules and synonim

Hi! I'm just starting with meilisearch and I was wondering if is possible to change the ranking rules of an index with this package or if I need to make the petition myself to the meilisearch endpoint.

if my dataset is in another language, for example spanish, meilisearch I read that for stopword use some kind of tokenization of latin word, but not sure if the synonim work for Spanish?

I hope that someone can clarify and thank you for this amazing tool.

Downgrading Meilisearch to version compatible with database

Runing meilisearchreturns an error Cannot open database, expected MeiliSearch engine version: <0.12.0, current engine version: 0.20.0. Following instructions, I tried downgrading Meilisearch to 0.12.0 (I used brew to install meilisearch):

brew install [email protected]
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
Error: No available formula or cask with the name "[email protected]".
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Error: No formulae found in taps.

I am not able to install specific version of meilisearch, only the most recent one.

In docs it is also said To fix this error, simply delete your database folder (data.ms by default) and re-index your documents with the current-version engine. Where is data.ms stored?

getTotalCount returns nbHits which doesn't match total count if results have been filtered. This breaks pagination.

Right now using the documented method to get results and paginate, I always end up with alot of extra "pages" in my pagination links because when the LengthAwarePaginator is built, it uses nbHits for the total count of results. This only works if you are not filtering at all. Is there any way to work around this other than building my own paginator? Or finding a way to override the getTotalCount in MeilisearchEngine.php ?

The current code is like this:

    public function getTotalCount($results)
    {
        return $results['nbHits'];
    }

If I change the getTotalCount method of MeilisearchEngine.php to something like

    public function getTotalCount($results)
    {
        return count($results);
    }

Then everything works as expected.

Any thoughts?
for a little further information I'm doing queries like this:

        return Set::search($this->search, function(Index $meilisearch, $query, $options) {
           $options['filters'] = 'user_id = ' . \Auth::user()->id;
           return $meilisearch->search($query, $options);
        })->paginate($perPage);
        // or like this: 
        return Set::search($this->search)->where('user_id', \Auth::id())->paginate($perPage);

And even though that user only gets 5 results, the paginator shows 20 pages of blank results (since nbHits doesn't account for filtering, and the paginator uses getTotalCount method which simply returns nbHits)

I'm fairly certain this is uninteded behavior and is therefor a BUG. would a PR to fix this be accepted?

EDIT: I realized this might be a bug in the Meilisearch library itself rather then this scout plugin. I ran a test going back to the algolia driver (I'm trying to move away from algolia), and the code for that also return simply "nbHits". However in the case of using Algolia, the nbHits number has been properly affected by the filter. In other words. nbHits for Meilisearch is not returning the correct number, and nbHits for algolia is. Let me know if you think I should open an issue on that repo.

Thanks,
Isaac

Delay for index new records

I think I'm facing this problem meilisearch/meilisearch#1098

With artisan command, everything works fast, but for new records saved on database it's taking maybe more than an hour to appears on MeiliSearch web UI.

[edit]

I have two models with Searchable trait: User model and Order model. All new models of User are indexed at same time they are created, but all new models of Order are taking this long time 🤔

This is my User searchable array:
Screen Shot 2021-03-12 at 17 42 54

This is my Order searchable array:
Screen Shot 2021-03-12 at 17 44 07

Is the where method available?

Hi,

First of all, great work! 🤩

I wanted to ask if the basic where() method the original scout driver offers, is supported in this package as well?

If you read the original docs, it supports a basic where method:

Scout allows you to add simple "where" clauses to your search queries. Currently, these clauses only support basic numeric equality checks, and are primarily useful for scoping search queries by a tenant ID. Since a search index is not a relational database, more advanced "where" clauses are not currently supported

Docs:
https://laravel.com/docs/7.x/scout#where-clauses

Original method:
https://github.com/laravel/scout/blob/8.x/src/Engines/AlgoliaEngine.php#L156

Thanks!

Linter

We should have a linter so that everyone can easily contribute without messing the code 🙂

Steps:

  • Add and configure the linter
  • Add the command in README in the Development Workflow part
  • Add it in GitHub Action to be triggered on each PR

Laravel sail with Meilisearch: write a Wiki page

Not sure if right place to put this, but since laravel valet is going to be removed in the future.

I was wondering if this laravel driver supports the usage of laravel sail (dockerized container) https://laravel.com/docs/8.x/sail.

Or if there could be documentation to show how to implement, I have been unable to get this working.

The instance it creates does not get read by this driver is the impression I am getting, though I could easily be wrong.

Screenshot 2020-12-18 at 00 46 38

Screenshot 2020-12-18 at 00 47 06

Screenshot 2020-12-18 at 00 50 12

Update of existing records

I have meilisearch working via Laravel Forge on its own dedicated ec2 instance.

Everything works great.

Apart from when a record is updated via ->save() eloquent method.

The record on the meilisearch server doesn't change.

I'm updating via amazon sqs queues.

I've been checking this via Postman by doing a direct get request to the server and the records just don't update.

I've hit a dead end in my debugging and wondering if anyone else has a similar issue or there is just a big delay when updating records.

Update

It seems to be the tasks taking up to 5 hours to process a document update.
Not sure why this is taking so long or if there is a way I can assign more processes to this process?

{
    "status": "processed",
    "updateId": 11022,
    "type": {
        "name": "DocumentsAddition",
        "number": 1
    },
    "duration": 47.64718841,
    "enqueuedAt": "2021-04-17T11:10:20.522991788Z",
    "processedAt": "2021-04-18T17:43:41.904437172Z"
}

search()->get() returns a maximum of 20 items

  1. seed many rows to User table
  2. import User to scout meilsearch index
  3. search for 'a' in meilisearch web UI and note the number of documents
  4. search for 'a' in tinker using User::search('a')->get()->count()

Expected:
meilisearch web UI and laravel scout search should return the same number of documents

Problem:
meilisearch returns 23428 results
scout returns 20 results

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.