PHPackages                             god-jay/scout-elasticsearch - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. god-jay/scout-elasticsearch

ActiveLibrary[Search &amp; Filtering](/categories/search)

god-jay/scout-elasticsearch
===========================

v1.0.1(4y ago)120MITPHPPHP &gt;=7.0

Since Oct 13Pushed 4y ago1 watchersCompare

[ Source](https://github.com/God-Jay/scout-elasticsearch)[ Packagist](https://packagist.org/packages/god-jay/scout-elasticsearch)[ RSS](/packages/god-jay-scout-elasticsearch/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (2)Versions (3)Used By (0)

god-jay scout-elasticsearch
===========================

[](#god-jay-scout-elasticsearch)

Use elasticsearch as easy as using Eloquent ORM in your laravel application.

English | [简体中文](README.zh-cn.md)

Contents
--------

[](#contents)

- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
    - [Create elasticsearch index](#create-elasticsearch-index)
    - [Import the given model into the search index](#import-the-given-model-into-the-search-index)
    - [Flush all of the model's records from the index](#flush-all-of-the-model's-records-from-the-index)
    - [Adding Records](#adding-records)
    - [Updating Records](#updating-records)
    - [Removing Records](#removing-records)
- [Searching](#searching)
- [Advanced Usage](#advanced-usage)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require god-jay/scout-elasticsearch
```

After installing the package, you should publish the Scout configuration using the vendor:publish Artisan command. This command will publish the scout.php configuration file to your config directory:

```
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
```

Then add

```
SCOUT_DRIVER=elastic
ELASTICSEARCH_HOST=your_es_host_ip:port

#Add if should auth es user
ELASTICSEARCH_USER=your_es_user
ELASTICSEARCH_PASS=your_es_pass

```

### Docker compose run es + kibana

[](#docker-compose-run-es--kibana)

If you don't have your own es service, you may install and run es + kibana with docker compose:

- You should install docker compose first: [install docker compose](https://docs.docker.com/compose/install/)
- Then run the command in the root of this directory:

    ```
    docker-compose up -d
    ```
- You can browse `http://localhost:5601` to visit kibana.
- To stop docker containers, run the command in the root of this directory:

    ```
    docker-compose down
    ```

in your .env file.

Configuration
-------------

[](#configuration)

Assuming there is a `posts` table and a Post Model, the simplified table may looks like:

idtitlecontentcreated\_at1标题文本内容2020-01-01 01:01:01Use GodJay\\ScoutElasticsearch\\Searchable in your model:

```
namespace App\Models;

use GodJay\ScoutElasticsearch\Searchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Searchable;
}
```

Add searchableAs function in the model:

```
public function searchableAs()
{
    //elasticsearch index name, you can set any name you like in the model
    return 'posts';
}
```

Usage
-----

[](#usage)

### Create elasticsearch index

[](#create-elasticsearch-index)

Add getElasticMapping function in the model,

then run `php artisan elastic:create-index "App\Models\Post"`

For more details, see [Create index API](https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-create-index.html)

```
public function getElasticMapping()
{
    return [
        'title' => [
            'type' => 'text',
            'analyzer' => 'ik_max_word',
            'search_analyzer' => 'ik_smart',
        ],
        'content' => [
            'type' => 'text',
            'analyzer' => 'ik_max_word',
            'search_analyzer' => 'ik_smart',
        ],
    ];
}
```

The elasticsearch index will be like:

```
{
  "mapping": {
    "_doc": {
      "properties": {
        "content": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_smart"
        },
        "title": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_smart"
        }
      }
    }
  }
}
```

### Import the given model into the search index

[](#import-the-given-model-into-the-search-index)

If there already exist many rows in your table, and you want to import the rows to elasticsearch,

Add toSearchableArray function in the model, then run `php artisan scout:import "App\Models\Post"`

```
public function toSearchableArray()
{
    return [
       'id' => $this->attributes['id'],
       'title' => $this->attributes['title'],
       'content' => strip_tags($this->attributes['content']),
       'created_at' => $this->attributes['created_at'],
   ];
}
```

After import the rows from table above, the elasticsearch index will be like:

```
{
  "mapping": {
    "_doc": {
      "properties": {
        "content": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_smart"
        },
        "created_at": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "id": {
          "type": "long"
        },
        "title": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_smart"
        }
      }
    }
  }
}
```

### Flush all of the model's records from the index

[](#flush-all-of-the-models-records-from-the-index)

Run `php artisan scout:flush "App\Models\Post"`

### Adding Records

[](#adding-records)

Once you have added the Searchable trait to a model, all you need to do is save a model instance and it will automatically be added to your search index.

```
$post = new Post();

// ...

$post->save();
```

### Updating Records

[](#updating-records)

To update a searchable model, you only need to update the model instance's properties and save the model to your database.

```
$post = Post::find(1);

// Update the order...

$post->save();
```

### Removing Records

[](#removing-records)

To remove a record from your index, delete the model from the database. This form of removal is even compatible with soft deleted models:

```
$post = Post::find(1);

$post->delete();
```

Searching
---------

[](#searching)

Base:

```
$posts = Post::search('内容')->get();
```

Paginate:

```
$posts = Post::search('内容')->paginate(10);
```

Highlight:

```
$post = Post::search('内容')->highlight(['title' => null, 'content' => null])->first();
```

The search result will be:

```
App\Models\Post Object
(
    [table:protected] => ppp
    ...
    [attributes:protected] => [
        [id] => 1
        [title] => 标题
        [content] => 文本内容
        [created_at] => 2020-01-01 01:01:01
    ]
    [relations:protected] => [
        [highlight] => GodJay\ScoutElasticsearch\Highlight Object
        (
            [attributes:protected] => [
                [content] => [
                    [0] => 文本内容
                ]
            ]
        )
    ]
)
```

Advanced Usage
--------------

[](#advanced-usage)

ES script sort:

```
use GodJay\ScoutElasticsearch\ElasticsearchEngine;

$posts = Post::search('', function (ElasticsearchEngine $engine, string $query, array $params) {
    $params['body']['sort'] = array_merge([[
        '_script' => [
            'type' => 'number',
            'script' => ['source' => "doc['field_a'].value * 0.7 + doc['field_b'].value * 0.3"],
            'order' => 'desc'
        ]
    ]], $params['body']['sort'] ?? []);
    $engine->setQueryParams($params);
    return $engine;
})->orderBy('id', 'desc')->where('field_c', 1)->get();
```

Debug:

```
use GodJay\ScoutElasticsearch\ElasticsearchEngine;

$debug = Post::search('', function (ElasticsearchEngine $engine, string $query, array $params) {
    $params['body']['sort'] = array_merge([[
        '_script' => [
            'type' => 'number',
            'script' => ['source' => "doc['field_a'].value * 0.7 + doc['field_b'].value * 0.3"],
            'order' => 'desc'
        ]
    ]], $params['body']['sort'] ?? []);
    $engine->setQueryParams($params);
    return $engine;
})->orderBy('id', 'desc')->where('field_c', 1)->where('field_d', ['x', 'y'])->debugSearch();
```

The result will be:

```
Array
(
    [result] => Illuminate\Database\Eloquent\Collection Object
    ...
    [query_params] => Array
    ...
    [exception] =>
    ...
)
```

The json string of `$debug['query_params']` will be:

```
{
  "index": "posts",
  "body": {
    "sort": [
      {
        "_script": {
          "type": "number",
          "script": {
            "source": "doc['field_a'].value * 0.7 + doc['field_b'].value * 0.3"
          },
          "order": "desc"
        }
      },
      {
        "id": "desc"
      }
    ],
    "query": {
      "bool": {
        "must": [
          {
            "match_phrase": {
              "field_c": 1
            }
          },
          {
            "terms": {
              "field_d": [
                "x",
                "y"
              ]
            }
          }
        ]
      }
    }
  }
}
```

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~68 days

Total

2

Last Release

1603d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7414a0304bd9cac87d8e81c08016774bae22baaae7facc647d3860333fd7825c?d=identicon)[God Jay](/maintainers/God%20Jay)

---

Top Contributors

[![God-Jay](https://avatars.githubusercontent.com/u/57613316?v=4)](https://github.com/God-Jay "God-Jay (6 commits)")

---

Tags

elasticsearchlaravellaravel-elasticsearchscoutsearchlaravelelasticsearchelasticscout

### Embed Badge

![Health badge](/badges/god-jay-scout-elasticsearch/health.svg)

```
[![Health](https://phpackages.com/badges/god-jay-scout-elasticsearch/health.svg)](https://phpackages.com/packages/god-jay-scout-elasticsearch)
```

###  Alternatives

[jeroen-g/explorer

Next-gen Elasticsearch driver for Laravel Scout.

397612.3k](/packages/jeroen-g-explorer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
