PHP code example of romangrinev / laravel-opensearch-engine

1. Go to this page and download the library: Download romangrinev/laravel-opensearch-engine 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/ */

    

romangrinev / laravel-opensearch-engine example snippets




namespace App\Providers;

// ...

use Grinev\LaravelOpenSearchEngine\OpenSearchEngine;
use Laravel\Scout\EngineManager;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // ...

        resolve(EngineManager::class)->extend(config('scout.driver'), function () {
            return new OpenSearchEngine;
        });

    }
}



return [

    //

    'driver' => env('SCOUT_DRIVER', 'opensearch'),

    'opensearch' => [
        'host' => env('OPENSEACH_HOST', 'http://localhost:9200'),
        'user' => env('OPENSEACH_USER', 'admin'),
        'pass' => env('OPENSEACH_PASS', 'admin'),
    ],

    //
];

$posts = Post::search('Key phrase')->get();

$posts = Post::search()->orderBy('posted_at', 'desc')->get();

$posts = Post::search()->where('category_id', '48')->get();

$posts = Post::search()->where('range', [
    'price' => [
        'gte' => 100,
        'lte' => 200
    ]
])->get();

$posts = Post::search()->->where('geo_bounding_box', [
    "location" => [
        "top_left" => [
            "lat" => 48.0,
            "lon" => -123.0
        ],
        "bottom_right" => [
            "lat" => 46.0,
            "lon" => -121.0
        ]
    ]
])->get();


return [
    //
    'opensearch' => [
        //
        'mappings' => [
            'posts_index' =>[
                "mappings" => [
                    "properties" => [
                        "location" => [
                            "type" => "geo_point"
                        ]
                    ]
                ]
            ]
        ]
    ],
];

    public function searchableAs(){
        return 'posts_index';
    }
	public function toSearchableArray(){
		$data = [
            //
			'location' => "{$this->lat},{$this->lng}",
		];

		return $data;
	}

$raw = Post::search('Key phrase')
    ->whereRaw([
        'aggs' => [
            'categories' => [
                'terms' => [
                    'field' => 'category_id'
                ]
            ]
        ]
    ])->raw();
$categories = collect(data_get($raw, 'aggregations.categories.buckets', []))->pluck('key')->map(fn($id) => Category::find($id));
bash
php artisan scout:flush App\\Models\\Post
php artisan scout:index App\\Models\\Post
php artisan scout:import App\\Models\\Post