PHP code example of huscakmak / elasticsearch

1. Go to this page and download the library: Download huscakmak/elasticsearch 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/ */

    

huscakmak / elasticsearch example snippets


    'providers' => [
        // ...

        Huslab\Elasticsearch\ElasticsearchServiceProvider::class,

        // ...
    ],

    // ...

    'aliases' => [
        // ...

        'ES' => Huslab\Elasticsearch\Facades\ES::class,

        // ...
    ],

$app->register(Huslab\Elasticsearch\ElasticsearchServiceProvider::class);

$app->withFacades();

app("es")->index("my_index")->type("my_type")->get();

# This is similar to:
ES::index("my_index")->type("my_type")->get();



use Huslab\Elasticsearch\ConnectionManager;
use Huslab\Elasticsearch\Factories\ClientFactory;

$connectionManager = new ConnectionManager([
 'servers' => [
        [
            "host" => '127.0.0.1',
            "port" => 9200,
            'user' => '',
            'pass' => '',
            'scheme' => 'http',
        ],
    ],

	// Custom handlers
	// 'handler' => new MyCustomHandler(),

    'index' => 'my_index',
], new ClientFactory());

$connection = $connectionManager->connection();

// Access the query builder using created connection
$documents = $connection->search("hello")->get();

# Here you can define the default connection name.
'default' => env('ELASTIC_CONNECTION', 'default'),

# Here you can define your connections.
'connections' => [
	'default' => [
	    'servers' => [
	        [
	            "host" => env("ELASTIC_HOST", "127.0.0.1"),
	            "port" => env("ELASTIC_PORT", 9200),
	            'user' => env('ELASTIC_USER', ''),
	            'pass' => env('ELASTIC_PASS', ''),
	            'scheme' => env('ELASTIC_SCHEME', 'http'),
	        ]
	    ],
	    
		// Custom handlers
		// 'handler' => new MyCustomHandler(),
		'index' => env('ELASTIC_INDEX', 'my_index')
	]
],
 
# Here you can define your indices.
'indices' => [
	'my_index_1' => [
	    "aliases" => [
	        "my_index"
	    ],
	    'settings' => [
	        "number_of_shards" => 1,
	        "number_of_replicas" => 0,
	    ],
	    'mappings' => [
	        'posts' => [
                'properties' => [
                    'title' => [
                        'type' => 'string'
                    ]
                ]
	        ]
	    ]
	]
]

   "aliases" => [
       "my_index_alias"
   ]       
   

# change the default driver to 'es'
'driver' => env('SCOUT_DRIVER', 'es'),

# link `es` driver with default elasticsearch connection in config/es.php
'es' => [
    'connection' => env('ELASTIC_CONNECTION', 'default'),
],

namespace App\Models;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    // ...
}

namespace App\Models;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    protected $index = 'posts';
}

namespace App\Models;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    protected $connection = 'blag';
}

namespace App;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    protected $type = 'posts';
}

namespace App\Models;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    protected $attributes = [
        'published' => false,
    ];
}

use App\Models\Post;

foreach (Post::all() as $post) {
    echo $post->title;
}

use App\Models\Post;

$posts = Post::where('status', 1)
             ->orderBy('created_at', 'desc')
             ->take(10)
             ->get();

use App\Models\Post;

$posts = Post::where('sponsored', true)->get();
$posts = $posts->reject($post => $post->in_review);

use App\Models\Post;

$posts = Post::all();
$total = $posts->getTotal();
$maxScore = $posts->getMaxScore();
$duration = $posts->getDuration();
$isTimedOut = $posts->isTimedOut();
$scrollId = $posts->getScrollId();
$shards = $posts->getShards();

foreach ($title as $title) {
    echo $post->title;
}

use App\Models\Post;

$posts = Post::take(500)->get();

use App\Models\Post;

// Retrieve a model by its ID...
$posts = Post::find('AVp_tCaAoV7YQD3Esfmp');

// Retrieve the first model matching the query constraints...
$post = Post::where('published', 1)->first();

// Alternative to retrieving the first model matching the query constraints...
$post = Post::firstWhere('published', 1);

use App\Models\Post;

$model = Post::where('tags', '>', 3)->firstOr(function () {
    // ...
});

$post = Post::findOrFail('AVp_tCaAoV7YQD3Esfmp');

$post = Post::where('published', true)->firstOrFail();

use App\Models\Post;

Route::get('/api/posts/{id}', function ($id) {
    return Post::findOrFail($id);
});

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    /**
     * Create a new post instance.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request): Response
    {
        // Validate the request...

        $post = new Post;
        $post->title = $request->title;

        $post->save();
    }
}

use App\Models\Post;

$post = Post::create([
'title' => 'Searching efficiently',
]);

use App\Models\Post;

$post = Post::find('AVp_tCaAoV7YQD3Esfmp');

$post->title = 'Modified Post Title';

$post->save();

use App\Models\Author;

$author = Author::create([
'first_name' => 'Moritz',
'last_name' => 'Friedrich',
'title' => 'Developer',
]);

$author->title = 'Painter';

$author->isDirty(); // true
$author->isDirty('title'); // true
$author->isDirty('first_name'); // false

$author->isClean(); // false
$author->isClean('title'); // false
$author->isClean('first_name'); // true

$author->save();

$author->isDirty(); // false
$author->isClean(); // true

use App\Models\Author;

$author = Author::create([
'first_name' => 'Taylor',
'last_name' => 'Otwell',
'title' => 'Developer',
]);

$author->title = 'Painter';

$author->save();

$author->wasChanged(); // true
$author->wasChanged('title'); // true
$author->wasChanged('first_name'); // false

use App\Models\Author;

$author = Author::find(1);

$author->name; // John
$author->email; // [email protected]

$author->name = "Jack";
$author->name; // Jack

$author->getOriginal('name'); // John
$author->getOriginal(); // Array of original attributes...

use App\Models\Post;

$post = Post::create([
    'title' => 'Searching effectively',
]);

namespace App\Models;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['title'];
}

$post = Post::create(['title' => 'Searching effectively']);

$post->fill(['title' => 'Searching more effectively']);

/**
 * The attributes that aren't mass assignable.
 *
 * @var array
 */
protected $guarded = [];

use App\Models\Post;

$post = Post::find('AVp_tCaAoV7YQD3Esfmp');

$post->delete();

use App\Models\Post;

Post::destroy(1);

Post::destroy(1, 2, 3);

Post::destroy([1, 2, 3]);

Post::destroy(collect([1, 2, 3]));

namespace App\Scopes;

use Huslab\Elasticsearch\Query;
use Huslab\Elasticsearch\Model;
use Huslab\Elasticsearch\Interfaces\ScopeInterface;

class AncientScope implements ScopeInterface
{
    /**
     * Apply the scope to a given Elasticsearch query builder.
     *
     * @param  \Huslab\Elasticsearch\Query  $query
     * @param  \Huslab\Elasticsearch\Model  $model
     * @return void
     */
    public function apply(Query $query, Model $model)
    {
        $query->where('created_at', '<', now()->subYears(2000));
    }
}

namespace App\Models;

use App\Scopes\AncientScope;
use Huslab\Elasticsearch\Model;

class Post extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope(new AncientScope);
    }
}

namespace App\Models;

use Huslab\Elasticsearch\Query;
use Huslab\Elasticsearch\Model;

class Post extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted(): void
    {
        static::addGlobalScope('ancient', function (Query $query) {
            $query->where('created_at', '<', now()->subYears(2000));
        });
    }
}

Post::withoutGlobalScope(AncientScope::class)->get();

Post::withoutGlobalScope('ancient')->get();

// Remove all of the global scopes...
Post::withoutGlobalScopes()->get();

// Remove some of the global scopes...
Post::withoutGlobalScopes([
    FirstScope::class,
    SecondScope::class
])->get();

namespace App\Models;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    /**
     * Scope a query to only  function scopePopular(Query $query): Query
    {
        return $query->where('votes', '>', 100);
    }

    /**
     * Scope a query to only 

use App\Models\Post;

$posts = Post::popular()->published()->orderBy('created_at')->get();

namespace App\Models;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    /**
     * Scope a query to only rch\Query
     */
    public function scopeOfType(Query $query, $type): Query
    {
        return $query->where('type', $type);
    }
}

if ($post->is($anotherPost)) {
    //
}

namespace App\Models;

use Huslab\Elasticsearch\Model;
use App\Events\UserDeleted;
use App\Events\UserSaved;

class Post extends Model
{
    /**
     * The event map for the model.
     *
     * @var array
     */
    protected $dispatchesEvents = [
        'saved' => PostSaved::class,
        'deleted' => PostDeleted::class,
    ];
}

namespace App\Models;

use Huslab\Elasticsearch\Model;

class Post extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted(): void
    {
        static::created(function ($post) {
            //
        });
    }
}

use function Illuminate\Events\queueable;

static::created(queueable(function ($post): void {
    //
}));


namespace App;

use Huslab\Elasticsearch\Model;

class post extends Model
{
    /**
     * Get the post title.
     *
     * @param  string  $value
     * @return string
     */
    public function getTitleAttribute(string $value): string
    {
        return ucfirst($value);
    }
}

$post = App\Post::find(1);

$title = $post->title;

public function getIsPublishedAttribute(): bool
{
    return $this->attributes['status'] === 1;
}

protected $appends = ['is_published'];

namespace App;

use Huslab\Elasticsearch\Model;

class post extends Model
{
    /**
     * Set the post title.
     *
     * @param  string  $value
     * @return string
     */
    public function setTitleAttribute(string $value): string
    {
        return strtolower($value);
    }
}

$post = App\Post::find(1);

$post->title = 'Awesome post to read';

use App\Models\Post;

$post = Post::withoutEvents(function () use () {
Post::findOrFail(1)->delete();

    return Post::find(2);
});

$post = Post::findOrFail(1);

$post->title = 'Other search strategies';

$post->saveQuietly();

use App\Models\Address;

$shipping = Address::create([
    'type' => 'shipping',
    'line_1' => '123 Example Street',
    'city' => 'Victorville',
    'state' => 'CA',
    'postcode' => '90001',
]);

$billing = $shipping->replicate()->fill([
    'type' => 'billing'
]);

$billing->save();

namespace App\Models;

use Huslab\Elasticsearch\Model;

class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getFirstNameAttribute(string $value): string
    {
        return ucfirst($value);
    }
}

use App\Models\User;

$user = User::find(1);

$firstName = $user->first_name;

/**
 * Get the user's full name.
 *
 * @return string
 */
public function getFullNameAttribute(): string
{
    return "{$this->first_name} {$this->last_name}";
}

namespace App\Models;

use Huslab\Elasticsearch\Model;

class User extends Model
{
    /**
     * Set the user's first name.
     *
     * @param  string  $value
     * @return void
     */
    public function setFirstNameAttribute(string $value): void
    {
        $this->attributes['first_name'] = strtolower($value);
    }
}

use App\Models\User;

$user = User::find(1);

$user->first_name = 'Sally';

namespace App\Models;

use Huslab\Elasticsearch\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

$user = App\Models\User::find(1);

if ($user->is_admin) {
    //
}

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'created_at' => 'datetime:Y-m-d',
];

/**
 * Prepare a date for array / JSON serialization.
 *
 * @param  \DateTimeInterface  $date
 * @return string
 */
protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d');
}

/**
 * The storage format of the model's date fields.
 *
 * @var string
 */
protected $dateFormat = 'U';

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Json implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  \Illuminate\Database\Eloquent\Model|\Huslab\Elasticsearch\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return array
     */
    public function get($model, $key, $value, $attributes)
    {
        return json_decode($value, true);
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  \Illuminate\Database\Eloquent\Model|\Huslab\Elasticsearch\Model  $model
     * @param  string  $key
     * @param  array  $value
     * @param  array  $attributes
     * @return string
     */
    public function set($model, $key, $value, $attributes)
    {
        return json_encode($value);
    }
}

    namespace App\Models;

    use App\Casts\Json;
    use Huslab\Elasticsearch\Model;

    class User extends Model
    {
        /**
         * The attributes that should be cast.
         *
         * @var array
         */
        protected $casts = [
            'options' => Json::class,
        ];
    }

namespace App\Casts;

use App\Models\Address as AddressModel;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use InvalidArgumentException;

class Address implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  \Illuminate\Database\Eloquent\Model|\Huslab\Elasticsearch\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return \App\Models\Address
     */
    public function get($model, $key, $value, $attributes)
    {
        return new AddressModel(
            $attributes['address_line_one'],
            $attributes['address_line_two']
        );
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  \Illuminate\Database\Eloquent\Model|\Huslab\Elasticsearch\Model  $model
     * @param  string  $key
     * @param  \App\Models\Address  $value
     * @param  array  $attributes
     * @return array
     */
    public function set($model, $key, $value, $attributes)
    {
        if (! $value instanceof AddressModel) {
            throw new InvalidArgumentException('The given value is not an Address instance.');
        }

        return [
            'address_line_one' => $value->lineOne,
            'address_line_two' => $value->lineTwo,
        ];
    }
}

use App\Models\User;

$user = User::find(1);

$user->address->lineOne = 'Updated Address Value';

$user->save();

/**
 * Get the serialized representation of the value.
 *
 * @param  \Illuminate\Database\Eloquent\Model|\Huslab\Elasticsearch\Model  $model
 * @param  string  $key
 * @param  mixed  $value
 * @param  array  $attributes
 * @return mixed
 */
public function serialize($model, string $key, $value, array $attributes)
{
    return (string) $value;
}

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;

class Hash implements CastsInboundAttributes
{
    /**
     * The hashing algorithm.
     *
     * @var string
     */
    protected $algorithm;

    /**
     * Create a new cast class instance.
     *
     * @param  string|null  $algorithm
     * @return void
     */
    public function __construct($algorithm = null)
    {
        $this->algorithm = $algorithm;
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  \Illuminate\Database\Eloquent\Model|\Huslab\Elasticsearch\Model  $model
     * @param  string  $key
     * @param  array  $value
     * @param  array  $attributes
     * @return string
     */
    public function set($model, $key, $value, $attributes)
    {
        return is_null($this->algorithm)
                    ? bcrypt($value)
                    : hash($this->algorithm, $value);
    }
}

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'secret' => Hash::class.':sha256',
];

use App\Models\Address;

protected $casts = [
    'address' => Address::class,
];

namespace App\Models;

use Illuminate\Contracts\Database\Eloquent\Castable;
use App\Casts\Address as AddressCast;

class Address implements Castable
{
    /**
     * Get the name of the caster class to use when casting from / to this cast target.
     *
     * @param  array  $arguments
     * @return string
     */
    public static function castUsing(array $arguments): string
    {
        return AddressCast::class;
    }
}

use App\Models\Address;

protected $casts = [
    'address' => Address::class.':argument',
];

namespace App\Models;

use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Address implements Castable
{
    // ...

    /**
     * Get the caster class to use when casting from / to this cast target.
     *
     * @param  array  $arguments
     * @return object|string
     */
    public static function castUsing(array $arguments)
    {
        return new class implements CastsAttributes
        {
            public function get($model, $key, $value, $attributes)
            {
                return new Address(
                    $attributes['address_line_one'],
                    $attributes['address_line_two']
                );
            }

            public function set($model, $key, $value, $attributes)
            {
                return [
                    'address_line_one' => $value->lineOne,
                    'address_line_two' => $value->lineTwo,
                ];
            }
        };
    }
}

use App\Models\Post;

Route::get('/posts/{post}', function (Post $post) {
    return $post->content;
});

use App\Http\Controllers\PostController;
use App\Models\Post;

// Route definition...
Route::get('/posts/{post}', [PostController::class, 'show']);

// Controller method definition...
public function show(Post $post): View
{
    return view('post.full', ['post' => $post]);
}

use App\Models\Post;

Route::get('/posts/{post:slug}', fn(Post $post): Post => $post);

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName(): string
{
    return 'slug';
}

use App\Http\Controllers\LocationsController;
use Illuminate\Http\Request;

Route::get('/locations/{location:slug}', [LocationsController::class, 'show'])
    ->missing(fn(Request $request) => Redirect::route('locations.index')
    ->name('locations.view');

use App\Models\Post;
use Illuminate\Support\Facades\Route;

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot():void
{
    Route::model('post', Post::class);

    // ...
}

use App\Models\Post;

Route::get('/posts/{post}', function (Post $post) {
    // ...
});

use App\Models\Post;
use Illuminate\Support\Facades\Route;

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot(): void
{
    Route::bind('post', function (string $value): Post {
        return Post::where('title', $value)->firstOrFail();
    });

    // ...
}

/**
 * Retrieve the model for a bound value.
 *
 * @param  mixed  $value
 * @param  string|null  $field
 * @return \Huslab\Elasticsearch\Model|null
 */
public function resolveRouteBinding($value, ?string $field = null): ?self
{
    return $this->where('name', $value)->firstOrFail();
}

/**
 * Retrieve the child model for a bound value.
 *
 * @param  string  $childType
 * @param  mixed  $value
 * @param  string|null  $field
 * @return \Huslab\Elasticsearch\Model|null
 */
public function resolveChildRouteBinding(string $childType, $value, ?string $field): ?self
{
    return parent::resolveChildRouteBinding($childType, $value, $field);
}

ES::create('my_index');
    
# or 
    
ES::index('my_index')->create();

use Huslab\Elasticsearch\Facades\ES;
use Huslab\Elasticsearch\Index;

ES::index('my_index')->create(function(Index $index) {
    $index->shards(5)->replicas(1)->mapping([
        'my_type' => [
            'properties' => [
                'first_name' => [
                    'type' => 'string',
                ],
                'age' => [
                    'type' => 'integer'
                ]
            ]
        ]
    ])
});
    
# or
    
ES::create('my_index', function(Index $index){
  
      $index->shards(5)->replicas(1)->mapping([
          'my_type' => [
              'properties' => [
                  'first_name' => [
                      'type' => 'string',
                  ],
                  'age' => [
                      'type' => 'integer'
                  ]
              ]
          ]
      ])
});

ES::drop("my_index");
    
# or

ES::index("my_index")->drop();

$documents = ES::connection("default")
                ->index("my_index")
                ->type("my_type")
                ->get();    # return a collection of results

$documents = ES::type("my_type")->get();    # return a collection of results

ES::type("my_type")->id(3)->first();
    
# or
    
ES::type("my_type")->_id(3)->first();

ES::type("my_type")->orderBy("created_at", "desc")->get();
    
# Sorting with text search score
    
ES::type("my_type")->orderBy("_score")->get();

ES::type("my_type")->take(10)->skip(5)->get();

ES::type("my_type")->select("title", "content")->take(10)->skip(5)->get();

ES::type("my_type")->where("status", "published")->get();

# or

ES::type("my_type")->where("status", "=", "published")->get();
bash
php artisan vendor:publish --provider="Huslab\Elasticsearch\ElasticsearchServiceProvider"
bash
   php artisan es:indices:reindex my_index my_new_index
   
   # Control bulk size. Adjust it with your server.
   php artisan es:indices:reindex my_index my_new_index --bulk-size=2000
   
   # Control query scroll value.
   php artisan es:indices:reindex my_index my_new_index --bulk-size=2000 --scroll=2m
   
   # Skip reindexing errors such as mapper parsing exceptions.
   php artisan es:indices:reindex my_index my_new_index --bulk-size=2000 --skip-errors 
   
   # Hide all reindexing errors and show the progres bar only.
   php artisan es:indices:reindex my_index my_new_index --bulk-size=2000 --skip-errors --hide-errors
   
bash
   php artisan es:indices:update