PHP code example of shisun / laravel-elasticsearch-query-builder

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

    

shisun / laravel-elasticsearch-query-builder example snippets


    'providers' => [
        ...
        Shisun\LaravelElasticsearchQueryBuilder\LaravelElasticsearchQueryBuilderServiceProvider::class,
    ]
    

        use Shisun\LaravelElasticsearchQueryBuilder\EsTrait;
        
        class User extends Model
        {
            use EsTrait;
        }
        

     use Shisun\LaravelElasticsearchQueryBuilder\EsTrait;
     class User extends Model
     {
        use EsTrait;
        public $mappingProperties;
        public function __construct($attributes = []) {
            parent::__construct($attributes);
        
            $this->mappingProperties = [
                'id' => [
                    'type' => 'integer',
                ],
                'name' => [
                    'type' => 'text',
                        'index' => true,
                ],
                'email' => [
                    'type' => 'keyword'
                ],
                'address' => [
                    'type' => 'text'
                ],
                'float_example' => [
                    'type' => 'float'
                ],
                'multi_fields_example' => [
                    'type' => 'text',
                    'fields' => [
                        'raw' => [
                            'type' => 'keyword'
                        ]
                    ]
                ],
                'created_at' => [
                    'type' => 'date',
                    'format' => 'yyyy-MM-dd HH:mm:ss',
                ],
                'some_relations' => [
                    'type' => 'nested',
                    'properties' => [
                        ....
                    ]
                ]
            ];
        }
     }   
     

     public function getIndexName() {
         return 'users';
     }
     // type name will be set to index name if this function is not defined.
     public function getTypeName() {
         return 'users';
     }
     

  use Shisun\LaravelElasticsearchQueryBuilder\LaravelElasticsearchQueryBuilder as Builder;
  $query = (new Builder())->setOptions([
      'index_name' => 'users',
      'type_name'  => 'users'
  ])->where('name', 'Leo')->get()->toArray();
  // or if you only want to generate the query without getting results
  $query = (new Builder())->where('name', 'Leo')->getBody()
  

      use Shisun\LaravelElasticsearchQueryBuilder\LaravelElasticsearchQueryBuilder as Builder;
      $builder = new Builder();
      

      use Shisun\LaravelElasticsearchQueryBuilder\LaravelElasticsearchQueryBuilder as Builder;
      $builder = (new Builder())->setOptions([
          'index_name' => 'users',
          'type_name'  => 'users',
          'validation' => false,
          'mapping_properties' => [check the example in the installation section]
      ]);
      

      User::es()->where('id', 1)->first()
      

         // Find the user whose name starts with 'Leo'
         User::es()->where('name', '*', 'Leo*')->first()
         

      User::es()->where(function($q) {
          $q->orWhere(...)->orWhere(...);
      })->get()->toArray()
      

      User::es()->whereNull('name')->get()
      

         User::es()->whereNull('Addresses')->get()
         

      User::es()->whereNotNull('name')->get()
      

         User::es()->whereNotNull('Addresses')->get()
         

      User::es()->orWhere('id', 1)->first()
      

      User::es()->orWhere(function($q) {
          $q->where(...)->where(...);
      })->limit(1)->get()->toArray()
      

      User::es()->whereMatch('email', 'shisun@')->first()
      

      User::es()->whereMatch('email', 'shisun@', [
             'query' => 'this will be overrided by $value',
             'operator' => 'and',
             'zero_terms_query' => 'all'
           ])->first()
      

      User::es()->whereDoesntMatch('email', 'shisun@')->first()
      

      User::es()->whereDoesntMatch('email', 'shisun@', [
             'query' => 'this will be overrided by $value',
             'operator' => 'and',
             'zero_terms_query' => 'all'
           ])->first()
      

      User::es()->orWhereMatch('email', 'shisun@')->first()
      

      User::es()->orWhereMatch('email', 'shisun@', [
             'query' => 'this will be overrided by $value',
             'operator' => 'and',
             'zero_terms_query' => 'all'
           ])->first()
      

      // find all users with active someRelations
      User::es()->whereHas('someRelations', function($q) {
          $q->where('status', 'active');
      })->first();
      

      // find all users with either active someRelations or red someOtherRelations
      // Note: the parent 'whereHas' is interchangable with 'where' clause
      User::es()->whereHas(function($q) {
          $q->orWhereHas('someRelations', function($k) {
               $k->where('status', 'active');
          })->orWhereHas('someOtherRelations', function($k) {
               $k->where('color', 'red');
          });
      })->first();
      

      // find all users with either active someRelations or red someOtherRelations
      // Note: the parent 'whereHas' is interchangable with 'where' clause
      User::es()->whereHas(function($q) {
          $q->orWhereHas('someRelations', function($k) {
               $k->where('status', 'active');
          })->orWhereHas('someOtherRelations', function($k) {
               $k->where('color', 'red');
          });
      })->first();
      

      // find all users with no someRelation
      User::es()->whereHasNull('someRelations')->first();
      

      // find all users with no someRelation with id = 1
      User::es()->whereHasNull('someRelations', function($q) {
          $q->where('id', 1);
      })->first();
      

      // find all users either with no someRelation or named as 'Leo'
      User::es()->where(function($q) {
          $q->orWhereHasNull('someRelations')->orWhere('name', 'Leo');
      })->first();
      

      // find all users with pending or active status
      User::es()->whereIn('status', ['active', 'pending'])->get();
      

      // find all users with either pending/active status or with name Leo
      User::es()->where(function($q) {
          $q->orWhereIn('status', ['active', 'pending'])->orWhere('name', 'Leo');
      })->get();
      

      // find all users that are not in pending or active status
      User::es()->whereNotIn('status', ['active', 'pending'])->get();
      

      // find all users with either not in pending/active status or with name Leo
      User::es()->where(function($q) {
          $q->orWhereNotIn('status', ['active', 'pending'])->orWhere('name', 'Leo');
      })->get();
      

      User::es()->whereBetween('id', 1, 5)->first()
      

      User::es()->orWhereBetween('id', 1, 5)->first()
      

      User::es()->orderBy('id', 'desc')->get()
      

      // If the category of the item is Laptop then use discount_price for ordering. Otherwise, use listing_price.
      Item::es()->orderBy('id', 'desc', 
                  ['lang' => 'painless', 'source' => "if(doc['category'].value == 'Laptops') {return doc['discount_price'].value;} else {return doc['listing_price'].value;}"])
            ->get()
      

      // get the first page. 25 users per page.
      User::es()->page(1, 25)->get()
      

      // get 25 users.
      User::es()->limit(25)->get()
      

      // skip first 25 users.
      User::es()->offset(25)->get()
      

      Item::es()->aggregate('group_items_by_categories', function($q) {
          $q->groupBy('category_id');
      })->get()->aggregations();
      

         // get all active and pending items. But only aggregate on the filtered items that are also red.
         // Note: aggregate clause is only applied on the filtered items.
         Item::es()->whereIn('status', ['active', 'pending'])->aggregate('categories', function($q) {
             $q->where('color', 'red')->aggregate('group_by', function($k) {
                 $k->groupBy('category_id');
             });
         })->get()->aggregations();
         // this returns
         // [
         //     'categories' => [
         //         'doc_count' => 50,
         //         'group_by'  => [
         //             'doc_count_error_upper_bound' => 0,
         //             'sum_other_doc_count'         => 8,
         //             'buckets' => [
         //                 [
         //                     'key' => 1,
         //                     'doc_count' => 15
         //                 ],
         //                 ...
         //             ]
         //         ]
         //     ]
         //  ]
         // the 'key' in buckets is one of the category_id
         

         // get all active and pending items. And aggregate on all red items.
         // Note: aggregateAll clause is applied on all items regardless other queries.
         Item::es()->whereIn('status', ['active', 'pending'])->aggregateAll('categories', function($q) {
             $q->where('color', 'red')->aggregate('group_by', function($k) {
                 $k->groupBy('category_id');
             });
         })->get()->aggregations();
         // this returns
         // [
         //     'categories' => [
         //         'doc_count' => 50,
         //         'group_by'  => [
         //             'doc_count_error_upper_bound' => 0,
         //             'sum_other_doc_count'         => 8,
         //             'buckets' => [
         //                 [
         //                     'key' => 1,
         //                     'doc_count' => 15
         //                 ],
         //                 ...
         //             ]
         //         ]
         //     ]
         //  ]
         // the 'key' in buckets is one of the category_id
         

      Item::es()->aggregateOn('someRelations', function($q) {
          $q->min('id');
      })->get()->aggregations();
      // this returns
      // [
      //     'some_relations' => [
      //         'doc_count' => 50,
      //         'min_id'  => [
      //             'value' => 1
      //         ]
      //     ]
      //  ]
      // 'some_relations' will be replaced if custom_name is provided
      

      Item::es()->min('id')->get()->aggregations();
      // or
      Item::es()->aggregate('test', function($q) {
          $q->min('id');
      })->get()->aggregations();
      // They both return. Note: the 'test' in the second example is ignored.
      // [
      //     'min_id' => [
      //         'value' => 1
      //     ]
      //  ]
      // 'min_id' will be replaced if custom_name is provided. The format of the name is 'min_' + column
      

      Item::es()->max('id')->get()->aggregations();
      // or
      Item::es()->aggregate('test', function($q) {
          $q->max('id');
      })->get()->aggregations();
      // They both return. Note: the 'test' in the second example is ignored.
      // [
      //     'max_id' => [
      //         'value' => 1
      //     ]
      //  ]
      // 'min_id' will be replaced if custom_name is provided. The format of the name is 'max_' + column
      

      Item::es()->avg('id')->get()->aggregations();
      // or
      Item::es()->aggregate('test', function($q) {
          $q->avg('id');
      })->get()->aggregations();
      // They both return. Note: the 'test' in the second example is ignored.
      // [
      //     'avg_id' => [
      //         'value' => 1
      //     ]
      //  ]
      // 'min_id' will be replaced if custom_name is provided. The format of the name is 'avg_' + column
      

      Item::es()->sum('id')->get()->aggregations();
      // or
      Item::es()->aggregate('test', function($q) {
          $q->sum('id');
      })->get()->aggregations();
      // They both return. Note: the 'test' in the second example is ignored.
      // [
      //     'sum_id' => [
      //         'value' => 1
      //     ]
      //  ]
      // 'min_id' will be replaced if custom_name is provided. The format of the name is 'sum_' + column
      

      User::es()->whereMatch('name', 'Leo', ['operator' => 'and'])->minScore(5)->get()
      

      User::es()->with('Addresses', 'Company')->get()
      

      User::es()->withOut('Addresses', 'Company')->get()
      

      User::es()->scroll()
      

      User::es()->count()
      

      User::es()->first()
      

      // get the user with id = 5
      // Note: the key_name can be set by setKeyName or setOptions. The key_name is 'id' by default
      User::es()->find(5)
      

      // delete the user with id = 5
      // Note: the key_name can be set by setKeyName or setOptions. The key_name is 'id' by default
      User::es()->delete(5)
      

      // if the aggregations are
      // this returns
      // [
      //     'categories' => [
      //         'doc_count' => 50,
      //         'group_by'  => [
      //             'doc_count_error_upper_bound' => 0,
      //             'sum_other_doc_count'         => 8,
      //             'buckets' => [
      //                 [
      //                     'key' => 1,
      //                     'doc_count' => 15
      //                 ],
      //                 ...
      //             ]
      //         ]
      //     ]
      //  ]
      // Then you can use getAggregationBuckets('categories') to get the buckets array
      

  [
     "pages" => [
       1,
       2,
       3,
       4,
       5,
     ],
     "rows" => 165,
     "active" => 1,
     "totalpages" => 7.0,
     "prev" => false,
     "next" => true,
     "per_page" => 25
  ]