⚡️ Models like Eloquent for Elasticsearch.

Overview

Elasticsearch Eloquent 2.x

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

This package allows you to interact with Elasticsearch as you interact with Eloquent models in Laravel.

Requirements

  • PHP >= 8.0
  • Elasticsearch >= 7.0

Install

Via Composer

$ composer require isswp101/elasticsearch-eloquent

Usage

Create a new model

You should override index and type properties to determine the document path.

use Isswp101\Persimmon\Models\BaseElasticsearchModel;
use Isswp101\Persimmon\Persistence\Persistence;
use Isswp101\Persimmon\Contracts\PersistenceContract;

class Product extends BaseElasticsearchModel
{
    protected string $index = 'index';
    protected string|null $type = 'type'; // optional

    // If you have a pre-configured Elasticsearch client you can pass it here (optional)
    public function createPersistence(): PersistenceContract
    {
        return new Persistence($client);
    }
}

Use the static create() method to create the document in Elasticsearch:

$product = Product::create([
    'id' => 1, 
    'name' => 'Product',
    'price' => 10
]);

Save the model

$product = new Product();
$product->id = 1;
$product->name = 'Product';
$product->price = 10;
$product->save();

Use save() method to store model data in Elasticsearch. Let's see how this looks in Elasticsearch:

{
   "_index": "index",
   "_type": "type",
   "_id": "1",
   "_version": 1,
   "_source": {
      "id": 1,
      "name": "Product",
      "price": 10,
      "created_at": "2021-03-27T11:24:15+00:00",
      "updated_at": "2021-03-27T11:24:15+00:00"
   }
}

Fields created_at and updated_at were created automatically.

Find existing model

$product = Product::find(1);

If you have big data in Elasticsearch you can specify certain fields to retrieve:

$product = Product::find(1, ['name']);

There are the following methods:

  • findOrFail() returns ModelNotFoundException exception if no result found.

Cache

There is a smart model cache when you use methods like find(), findOrFail() and so on.

$product = Product::find(1, ['name']);  // from elasticsearch
$product = Product::find(1, ['name']);  // from cache
$product = Product::find(1, ['price']); // from elasticsearch
$product = Product::find(1, ['price']); // from cache
$product = Product::find(1, ['name']);  // from cache
$product = Product::find(1);            // from elasticsearch
$product = Product::find(1);            // from cache
$product = Product::find(1, ['name']);  // from cache
$product = Product::find(1, ['price']); // from cache

Partial update

You can use the partial update to update specific fields quickly.

$product = Product::find(1, ['name']);
$product->name = 'Name';
$product->save(['name']);

Delete models

$product = Product::find(1);
$product->delete();

You can use the static method:

Product::destroy(1);

Model events

Out of the box you are provided with a simple implementation of events.
You can override the following methods to define events:

  • saving() is called before saving, updating, creating the model
  • saved() is called after saving, updating, creating the model
  • deleting() is called before deleting the model
  • deleted() is called after deleting the model
  • searching() is called after searching models
  • searched() is called after searching models

For example:

use Isswp101\Persimmon\Models\BaseElasticsearchModel;

class Product extends BaseElasticsearchModel
{
    protected function saving(): bool
    {
        // Disable update if it's free
        return $this->price <= 0;
    }

    protected function deleting(): bool
    {
        if ($this->user_id != 1) {
            throw new DomainException('No permissions to delete this model');
        }

        return true;
    }
}

Basic search

There are helpers to search documents:

The first($query) method returns the first document according to the query or null.

$product = Product::first($query);

The firstOrFail($query) method returns ModelNotFoundException exception if first($query) returns null.

$product = Product::firstOrFail($query);

The search($query) method returns documents according to the query.

$products = Product::search($query);

The all($query) method returns all documents (default 50 items per request) according to the query.

$products = Product::all($query);

If $query is not passed the query will be as match_all query.

Query Builder

Consider using these packages:

Testing

$ composer test

License

The MIT License (MIT).

You might also like...
Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.
Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.

Laravel Befriended Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked

Maps Laravel Eloquent models to Elasticsearch types

Elasticquent Elasticsearch for Eloquent Laravel Models Elasticquent makes working with Elasticsearch and Eloquent models easier by mapping them to Ela

Add Social Reactions to Laravel Eloquent Models. It lets people express how they feel about the content. Fully customizable Weighted Reaction System & Reaction Type System with Like, Dislike and any other custom emotion types. Do you react? #️⃣  Generate, Save, and Route Stripe-like Hash IDs for Laravel Eloquent Models
#️⃣ Generate, Save, and Route Stripe-like Hash IDs for Laravel Eloquent Models

Using this package you can generate, save and, route Stripe-like Hash Ids for your Eloquent Models. Hash Ids are short, unique, and non-sequential, an

A package to generate YouTube-like IDs for Eloquent models

Laravel Hashids This package provides a trait that will generate hashids when saving any Eloquent model. Hashids Hashids is a small package to generat

Search among multiple models with ElasticSearch and Laravel Scout
Search among multiple models with ElasticSearch and Laravel Scout

For PHP8 support use php8 branch For Laravel Framework 6.0.0 use 3.x branch The package provides the perfect starting point to integrate ElasticSear

Laravel 8.* Elasticsearch Eloquent
Laravel 8.* Elasticsearch Eloquent

Elasticsearch Installation composer require etsetra/elasticsearch Create config file $ php artisan vendor:publish --tag="etsetra-elasticsearch-config

An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Sortable behaviour for Eloquent models
Sortable behaviour for Eloquent models

Sortable behaviour for Eloquent models This package provides a trait that adds sortable behaviour to an Eloquent model. The value of the order column

This package gives Eloquent models the ability to manage their friendships.

Laravel 5 Friendships This package gives Eloquent models the ability to manage their friendships. You can easily design a Facebook like Friend System.

Automatically validating Eloquent models for Laravel

Validating, a validation trait for Laravel Validating is a trait for Laravel Eloquent models which ensures that models meet their validation criteria

Laravel Ban simplify blocking and banning Eloquent models.
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

Laravel Scout provides a driver based solution to searching your Eloquent models.

Introduction Laravel Scout provides a simple, driver-based solution for adding full-text search to your Eloquent models. Once Scout is installed and c

Making Eloquent models translatable
Making Eloquent models translatable

A trait to make Eloquent models translatable This package contains a trait to make Eloquent models translatable. Translations are stored as json. Ther

Create presenters for Eloquent Models
Create presenters for Eloquent Models

Laravel Presentable This package allows the information to be presented in a different way by means of methods that can be defined in the model's pres

🍞🧑‍🍳 An on-the-fly GraphQL Schema generator from Eloquent models for Laravel.

An on-the-fly GraphQL Schema generator from Eloquent models for Laravel. Installation Quickstart Model schemas Installation This package requires PHP

A small package for adding UUIDs to Eloquent models.

A small package for adding UUIDs to Eloquent models. Installation You can install the package via composer: composer require ryangjchandler/laravel-uu

Use auto generated UUID slugs to identify and retrieve your Eloquent models.

Laravel Eloquent UUID slug Summary About Features Requirements Installation Examples Compatibility table Alternatives Tests About By default, when get

Comments
  • Problem with default User Model

    Problem with default User Model

    I rewrote default User Model extends ElasticsearchModel: `<?php

    namespace App;

    use Illuminate\Notifications\Notifiable; //use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; use App\ElasticsearchModel as Model; //use Laravel\Scout\Searchable;

    class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword, Notifiable;

    protected static $_index = 'laravel';
    protected static $_type = 'user';
    
    // public $name;
    // public $email;
    // public $password;
    // public $remember_token;
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];
    
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    

    } ` When I ran App\User::search($query)->get();, I got this error: Illuminate\Contracts\Container\BindingResolutionException with message 'Unresolvable dependency resolving [Parameter #0 [ $retries ]] in class Elasticsearch\Transport'

    opened by hieunv95 2
  • QueryBuilder (DSL)

    QueryBuilder (DSL)

    I suggest using development https://github.com/ongr-io/ElasticsearchDSL or make your like this https://github.com/sleimanx2/plastic#searching-model-content

    enhancement 
    opened by intech 1
  • Support elasticsearch client 5.x

    Support elasticsearch client 5.x

    • Use the official elasticsearch client "elasticsearch/elasticsearch": "~5.0"
    • Remove "shift31/laravel-elasticsearch": "^2.0"
    • Fix tests on elasticsearch 5.2.2
    opened by devemio 0
  • Add tests for basic features

    Add tests for basic features

    Need to write tests for basic features like:

    • [x] Model::find($id)
    • [x] Model::findOrFail($id)
    • [x] Model::search($query)
    • [x] Model::first($query)
    • [x] Model::destroy($id)

    and so on...

    enhancement 
    opened by devemio 0
Releases(2.0.0)
Owner
Sergey Sorokin
🏝 Backend Developer
Sergey Sorokin
ORM layer that creates models, config and database on the fly

RedBeanPHP 5 RedBeanPHP is an easy to use ORM tool for PHP. Automatically creates tables and columns as you go No configuration, just fire and forget

Gabor de Mooij 2.2k Jan 9, 2023
Low code , Zero Configuration ORM that creates models, config, database and tables on the fly.

?? ARCA ORM ?? Low code , Zero Configuration ORM that creates models, config, database and tables on the fly. ?? ???? Made in India ???? Complete docu

Scrawler Labs 28 Dec 18, 2022
Baum is an implementation of the Nested Set pattern for Laravel's Eloquent ORM.

Baum Baum is an implementation of the Nested Set pattern for Laravel 5's Eloquent ORM. For Laravel 4.2.x compatibility, check the 1.0.x branch branch

Estanislau Trepat 2.2k Jan 3, 2023
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

Jens Segers 6.3k Jan 5, 2023
Extensions for the Eloquent ORM

Sofa/Eloquence Easy and flexible extensions for the Eloquent ORM. Currently available extensions: Searchable query - crazy-simple fulltext search thro

Jarek Tkaczyk 1.1k Dec 20, 2022
Easily exclude model entities from eloquent queries

Laravel Excludable Easily exclude model entities from eloquent queries. This package allows you to define a subset of model entities who should be exc

H-FARM 49 Jan 4, 2023
Simple Enum cast for Eloquent ORM using myclabs/php-enum.

Enum cast for Eloquent Simple Enum cast for Eloquent ORM using myclabs/php-enum. Requirements PHP 7.3 or higher Laravel 8.0 or higher Installation You

Orkhan Ahmadov 5 Apr 21, 2022
Eloquent Repository implementation

Eloquent Repository Eloquent Repository using nilportugues/repository as foundation. Installation Use Composer to install the package: $ composer requ

Nil Portugués Calderó 17 Feb 12, 2022
Eloquent MongoDB Repository Implementation

Eloquent MongoDB Repository Eloquent MongoDB Repository using nilportugues/repository as foundation, using jenssegers/mongodb. Installation Use Compos

Nil Portugués Calderó 18 Feb 12, 2022
⚡️ Models like Eloquent for Elasticsearch.

Elasticsearch Eloquent 2.x This package allows you to interact with Elasticsearch as you interact with Eloquent models in Laravel. Requirements PHP >=

Sergey Sorokin 111 Dec 19, 2022