PHP code example of codeartmk / opensearch-laravel
1. Go to this page and download the library: Download codeartmk/opensearch-laravel library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
codeartmk / opensearch-laravel example snippets
use Codeart\OpensearchLaravel\OpenSearchable;
use Codeart\OpensearchLaravel\Traits\HasOpenSearchDocuments;
class User extends Authenticatable implements OpenSearchable
{
use HasApiTokens, HasFactory, Notifiable, HasOpenSearchDocuments;
//rest of the model
}
use Codeart\OpensearchLaravel\OpenSearchable;
use Codeart\OpensearchLaravel\Traits\HasOpenSearchDocuments;
class User extends Authenticatable implements OpenSearchable
{
use HasApiTokens, HasFactory, Notifiable, HasOpenSearchDocuments;
public function openSearchMapping(): array
{
return [
"mapping" => [
"properties" => [
"id" => [ "type" => "integer" ],
"first_name" => [ "type" => "text" ],
"last_name" => [ "type" => "text" ],
"name" => [ "type" => "text" ],
"email" => [ "type" => "keyword" ],
//...
]
]
];
}
public function openSearchArray(): array
{
return [
"id" => $this->id,
"first_name" => $this->first_name,
"last_name" => $this->last_name,
"name" => $this->first_name + " " + $this->last_name,
"email" => $this->email,
//...
];
}
public function openSearchIndexName(): string
{
return "users";
}
//rest of the model
}
use App\Models\User;
User::opensearch()
->documents()
->create($ids, fn($query) => $query->with('relationship'));
use Codeart\OpensearchLaravel\Interfaces\OpenSearchQuery;
use Codeart\OpensearchLaravel\Search\SearchQueries\Types\SearchQueryType;
class MyCustomQuery implements OpenSearchQuery, SearchQueryType
{
public function __construct(
private readonly string $query
) {}
public static function make(string $query) {
return self($query);
}
public function toOpenSearchQuery() : array{
return [
'query_string' => [
'query' => $query
]
];
}
}
use App\Models\User;
use MyNamespace\MyCustomQuery;
User::opensearch()
->builder()
->search([
Query::make([
MyCustomQuery::make('the wind AND (rises OR rising)')
]),
])
->get();
use Codeart\OpensearchLaravel\Interfaces\OpenSearchQuery;
use Codeart\OpensearchLaravel\Aggregations\Types\AggregationType;
class MyCustomAggregation implements OpenSearchQuery, AggregationType
{
//aggregation logic
}