matchory / elasticsearch

Laravel 缺失的 Elasticsearch ORM!

安装数量: 45,595

依赖关系: 0

建议者: 0

安全性: 0

星标: 31

关注者: 4

分支: 130

公开问题: 14

类型:软件包

3.0.0-alpha.9 2024-06-11 10:26 UTC

README

Latest Stable Version Total Downloads Latest Unstable Version License

Laravel Elasticsearch 集成

这是由 @basemkhirat 开发的优秀库的一个分支,遗憾的是他似乎已经放弃了该项目。
由于我们非常依赖这个库,我们将努力保持其与较新版本的 Laravel 和 Elasticsearch 兼容并更新。

此分支的更改

  • 支持 Elasticsearch 7.10 及更高版本
  • 支持 PHP 7.3 及更高版本(包括 PHP 8)
  • 扩展了对 Laravel 库的支持,允许您使用几乎所有的 Laravel 版本
  • 在所有支持的位置添加类型提示,对所有参数都充满信心
  • 提供高级自动补全的 Docblock 注释,详细的内联文档
  • 将连接管理干净地分离到 ConnectionManager,同时保留向后兼容性
  • 支持 大多数 Eloquent 模型行为(见下文)
  • 移除了对 Laravel 内部依赖的依赖

如果您有兴趣贡献,请提交一个 PR 或打开一个问题!

特性

  • 具有优雅语法的流畅 Elasticsearch 查询构建器
  • 受 Laravel Eloquent 启发的 Elasticsearch 模型
  • 使用简单的 artisan 命令进行索引管理
  • 有限支持 Lumen 框架
  • 可以作为 Laravel Scout 驱动器使用
  • 并行使用多个 Elasticsearch 连接
  • 基于 Laravel Pagination 的内置分页
  • 使用基于 laravel cache 的缓存层进行查询缓存。

目录

要求

  • PHP >= 7.3
    请参阅Travis CI 构建日志
  • laravel/laravel >= 5.* 或 laravel/lumen >= 5.* 或任何使用 composer 的应用程序

安装

本节描述了所有支持的应用程序类型的安装过程。

使用 composer 安装软件包

无论您使用 Laravel、Lumen 还是其他框架,请首先使用 composer 安装该软件包

composer require matchory/elasticsearch

Laravel 安装

如果您已禁用包自动发现,请将服务提供者和外观添加到您的 config/app.php

    'providers' => [
        // ...

        Matchory\Elasticsearch\ElasticsearchServiceProvider::class,

        // ...
    ],

    // ...

    'aliases' => [
        // ...

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

        // ...
    ],

最后,将服务提供者发布到您的配置目录

php artisan vendor:publish --provider="Matchory\Elasticsearch\ElasticsearchServiceProvider"

Lumen 安装

从 composer 安装软件包后,将包服务提供者添加到 bootstrap/app.php

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

将软件包配置目录 vendor/matchory/elasticsearch/src/config/ 复制到您的项目根目录,与您的 app/ 目录并列

cp -r ./vendor/matchory/elasticsearch/src/config ./config

如果您尚未这样做,请通过在 bootstrap/app.php 中取消注释该行来使 Lumen 与外观协同工作

$app->withFacades();

如果您不希望在 Lumen 中启用外观,您可以使用 app("elasticsearch") 访问查询构建器

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

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

通用应用程序安装

您可以使用任何基于 composer 的应用程序安装该软件包。虽然我们无法提供通用说明,但以下示例应能为您提供一些思路

require "vendor/autoload.php";

use Matchory\Elasticsearch\ConnectionManager;
use Matchory\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();

配置(Laravel & Lumen)

发布服务提供者后,将在 config/es.php 中创建一个配置文件。在此,您可以添加一个或多个 Elasticsearch 连接,每个连接包含多个服务器。以下是一个示例

# 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'
                    ]
                ]
	        ]
	    ]
	]
]

如果您想使用 Elasticsearch 与 Laravel Scout,您可以在 config/scout.php 中找到 Scout 特定设置。

Artisan 命令(Laravel & Lumen)

此软件包包含的 artisan 命令可以创建或更新设置、映射和别名。请注意,所有命令默认使用默认连接。您可以通过传递 --connection <your_connection_name> 选项来更改此设置。

以下命令可用:

es:indices:list:列出服务器上的所有索引

$ php artisan es:indices:list
+----------------------+--------+--------+----------+------------------------+-----+-----+------------+--------------+------------+----------------+
| configured (es.php)  | health | status | index    | uuid                   | pri | rep | docs.count | docs.deleted | store.size | pri.store.size |
+----------------------+--------+--------+----------+------------------------+-----+-----+------------+--------------+------------+----------------+
| yes                  | green  | open   | my_index | 5URW60KJQNionAJgL6Q2TQ | 1   | 0   | 0          | 0            | 260b       | 260b           |
+----------------------+--------+--------+----------+------------------------+-----+-----+------------+--------------+------------+----------------+

es:indices:create:创建 config/es.php 中定义的索引

请注意,创建操作会跳过已存在的索引。

# Create all indices in config file.
php artisan es:indices:create

# Create only 'my_index' index in config file
php artisan es:indices:create my_index 

es:indices:update:更新 config/es.php 中定义的索引

请注意,更新操作更新索引设置、别名和映射,但不删除索引数据。

# Update all indices in config file.
php artisan es:indices:update

# Update only 'my_index' index in config file
php artisan es:indices:update my_index 

es:indices:drop:删除索引

使用此命令时要小心,因为这会导致您丢失索引数据!
使用 --force 选项运行 drop 命令会跳过所有确认信息。

# Drop all indices in config file.
php artisan es:indices:drop

# Drop specific index on sever. Not matter for index to be exist in config file or not.
php artisan es:indices:drop my_index 

数据重新索引(零停机时间)

首先,为什么需要重新索引?
更改索引映射不会反映出来,除非进行数据重新索引,否则您的搜索结果将无法正确工作。
为了避免停机时间,您的应用程序应该使用索引 alias 而不是索引 name 进行工作。
索引 alias 是一个常量名称,应用程序应该使用它来避免更改索引名称。

假设我们想更改 my_index 的映射,以下是操作方法

  1. alias 添加为示例 my_index_aliasmy_index 配置中,并确保您的应用程序正在使用它。

    "aliases" => [
        "my_index_alias"
    ]       
  2. 使用命令更新索引

    php artisan es:indices:update my_index
  3. 创建一个新的索引作为示例 my_new_index,并在配置文件中包含您的新映射。

    $ php artisan es:indices:create my_new_index
  4. 使用命令将 my_index 中的数据重新索引到 my_new_index

    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
  5. 在配置文件中从 my_index 中删除 my_index_alias 别名,并将其添加到 my_new_index 中,然后使用命令更新

    php artisan es:indices:update

作为 Laravel Scout 驱动器使用

首先,按照Laravel Scout 安装说明进行操作。
您只需更新 config/scout.php 中的以下几行即可

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

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

也请参阅 Laravel Scout 文档

Elasticsearch 模型

每个索引类型都有一个对应的 "模型",用于与该类型交互。模型允许您在类型或索引中查询数据,以及将新文档插入到类型中。Elasticsearch 模型尽可能地模仿 Eloquent 模型:您可以使用模型事件、路由绑定、高级属性方法等。 如果您缺少任何 Eloquent 功能,请提出问题,我们将很高兴添加它!

支持的功能

  • 属性
  • 事件
  • 路由绑定
  • 全局和局部查询范围
  • 复制模型

一个最小化的模型可能看起来像这样

namespace App\Models;

use Matchory\Elasticsearch\Model;

class Post extends Model
{
    // ...
}

索引名称

此模型并未特定绑定到任何索引,它将简单地使用为给定Elasticsearch连接配置的索引。要针对特定索引,您可以在模型上定义一个index属性

namespace App\Models;

use Matchory\Elasticsearch\Model;

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

连接名称

默认情况下,所有Elasticsearch模型都将使用为您的应用程序配置的默认连接。如果您想指定在交互特定模型时应使用不同的连接,应在模型上定义一个$connection属性

namespace App\Models;

use Matchory\Elasticsearch\Model;

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

映射类型

如果您仍在使用映射类型,您可以在模型上添加一个type属性以指示用于查询的映射_type

映射类型已弃用
请注意,Elastic已弃用映射类型,将在下一个主要版本中移除它们。您不应依赖它们来继续工作。

namespace App;

use Matchory\Elasticsearch\Model;

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

默认属性值

默认情况下,新实例化的模型实例将不包含任何属性值。如果您想定义模型某些属性的默认值,您可以在模型上定义一个attributes属性

namespace App\Models;

use Matchory\Elasticsearch\Model;

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

检索模型

一旦您创建了一个模型及其关联的索引类型,您就可以开始从索引中检索数据了。您可以认为Elasticsearch模型是一个强大的查询构建器,允许您流畅地查询与模型关联的索引。模型上的all方法将检索模型关联的Elasticsearch索引中的所有文档

use App\Models\Post;

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

添加额外的约束

all方法将返回模型索引中的所有结果。然而,由于每个Elasticsearch模型都充当查询构建器,您可以在查询中添加额外的约束,然后调用get()方法来检索结果

use App\Models\Post;

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

集合

如我们所见,Elasticsearch方法如allget从索引中检索多个文档。然而,这些方法并不返回一个普通的PHP数组。相反,返回一个Matchory\Elasticsearch\Collection实例。

Elasticsearch的Collection类扩展了Laravel的基础Illuminate\Support\Collection类,它提供了一系列有助于与数据集合交互的方法。例如,可以使用reject方法根据调用的闭包的结果从集合中删除模型。

use App\Models\Post;

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

除了Laravel基础集合类提供的方法之外,Elasticsearch集合类还提供了一些旨在专门与Elasticsearch模型集合交互的额外方法。

结果元数据

Elasticsearch除了查询的命中之外,还提供了几个额外的字段,如总结果数量或查询执行时间。Elasticsearch集合提供了这些属性的getter方法。

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();

迭代

由于Laravel的所有集合都实现了PHP的iterable接口,因此您可以将集合作为数组进行循环。

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

分块结果

Elasticsearch索引可能非常大。如果您的应用程序尝试在没有上限的情况下通过allget方法加载成千上万的Elasticsearch文档,则可能会耗尽内存。因此,默认获取的文档数量设置为10。要更改此设置,请使用take方法。

use App\Models\Post;

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

检索单个模型

除了检索与给定查询匹配的所有文档外,您还可以使用findfirstfirstWhere方法检索单个文档。与返回模型集合的方法不同,这些方法返回单个模型实例。

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);```

有时你可能希望在查询没有结果时检索第一个结果或执行某些其他操作。firstOr 方法将返回与查询匹配的第一个结果,如果没有找到结果,则执行给定的闭包。闭包返回的值将被视为 firstOr 方法的返回值

use App\Models\Post;

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

未找到异常

有时你可能希望在找不到模型时抛出一个异常。这在路由或控制器中特别有用。findOrFailfirstOrFail 方法将检索查询的第一个结果;然而,如果没有找到结果,则会抛出 Matchory\Elasticsearch\Exceptions\DocumentNotFoundException 异常

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

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

如果没有捕获到 DocumentNotFoundException,则会自动向客户端发送一个 404 HTTP 响应

use App\Models\Post;

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

插入和更新模型

插入

要将新文档插入索引中,你应该实例化一个新的模型实例并设置模型上的属性。然后,在模型实例上调用 save 方法

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();
    }
}

在本例中,我们将传入的 HTTP 请求中的 name 字段赋值给 App\Models\Post 模型实例的 name 属性。当我们调用 save 方法时,一个文档将被插入到索引中。

或者,你也可以使用 create 方法通过单个 PHP 语句“保存”一个新的模型。通过 create 方法插入的模型实例将被该方法返回给你

use App\Models\Post;

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

但是,在使用 create 方法之前,你需要在你的模型类上指定 fillableguarded 属性。这些属性是必需的,因为默认情况下,所有 Elasticsearch 模型都受到防批量赋值漏洞的保护。有关批量赋值的更多信息,请参阅批量赋值文档

更新

save 方法也可以用来更新已存在于索引中的模型。要更新模型,你应该检索它并设置你想要更新的任何属性。然后,你应该调用模型的 save 方法。

save() 方法也可以用来更新已存在于索引中的模型。要更新模型,你应该检索它,设置你想要更新的任何属性,然后调用保存方法。

use App\Models\Post;

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

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

$post->save();

检查属性更改

Elasticsearch 提供了 isDirtyisCleanwasChanged 方法来检查模型的内部状态并确定其属性与最初检索时的变化。

isDirty 方法确定自模型检索以来模型是否更改了任何属性。你可以向 isDirty 方法传递一个特定的属性名称,以确定是否更改了特定的属性。该方法也接受可选的属性参数

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

wasChanged 方法确定在当前请求周期内最后一次保存模型时是否更改了任何属性。如果需要,你可以传递一个属性名称以查看是否更改了特定的属性

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

getOriginal 方法返回一个数组,包含模型自检索以来的原始属性,无论模型是否发生变化。如果需要,你可以传递一个特定的属性名称以获取特定属性的原始值

use App\Models\Author;

$author = Author::find(1);

$author->name; // John
$author->email; // john@example.com

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

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

批量赋值

你可以使用 create 方法通过单个 PHP 语句“保存”一个新的模型。该插入的模型实例将通过该方法返回给你

use App\Models\Post;

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

然而,在使用 create 方法之前,您需要在您的模型类上指定 fillableguarded 属性之一。这些属性是必需的,因为默认情况下,所有 Elasticsearch 模型都受到防篡改漏洞的保护。

当用户传递一个意外的 HTTP 请求字段,并且该字段更改了您未预期的索引中的字段时,就会发生篡改漏洞。

因此,要开始使用,您应该定义要使哪些模型属性可篡改。您可以使用模型上的 fillable 属性来完成此操作。例如,让我们让 Post 模型的 title 属性可篡改

namespace App\Models;

use Matchory\Elasticsearch\Model;

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

一旦指定了哪些属性是可篡改的,您就可以使用 create 方法将新文档插入索引。create 方法返回新创建的模型实例

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

如果您已经有一个模型实例,您可以使用 fill 方法用属性数组填充它

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

允许批量赋值

如果您希望将所有属性设置为可篡改,可以将模型的 guarded 属性定义为空数组。如果您选择取消保护模型,应特别注意始终手动制作传递给 Elasticsearch 的 fillcreateupdate 方法的数组

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

更新或插入(upserts)

目前还没有方便的包装器用于更新文档(根据模型是否存在插入或更新)。如果您对此类功能感兴趣,请提交一个问题。

删除模型

要删除模型,请在模型实例上调用 delete 方法

use App\Models\Post;

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

$post->delete();

通过其 ID 删除现有模型

在上面的示例中,我们在调用 delete 方法之前从索引中检索了模型。但是,如果您知道模型的 ID,您可以通过调用 destroy 方法来删除模型而无需显式检索它。除了接受单个 ID 外,destroy 方法还接受多个 ID、ID 数组或 ID 集合

use App\Models\Post;

Post::destroy(1);

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

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

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

重要
destroy 方法会逐个加载每个模型并调用 delete 方法,以便为每个模型正确地分发 deletingdeleted 事件。

查询作用域

查询范围实现的方式与 Eloquent 中完全相同。

全局作用域

全局范围允许您向特定模型的查询添加约束。编写自己的全局范围可以提供一个方便、简单的方法,以确保对给定模型的每个查询都接收某些约束。

编写全局范围

编写全局范围很简单。首先,定义一个实现 Matchory\Elasticsearch\Interfaces\ScopeInterface 接口的自定义类。Laravel 没有传统的位置来放置范围类,因此您可以将此类放置在任何您希望的目录中。

ScopeInterface 要求您实现一个方法:apply。根据需要,apply 方法可以添加约束或其他类型的子句到查询中。

namespace App\Scopes;

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

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

要将全局范围分配给模型,您应覆盖模型的 booted 方法并调用模型的 addGlobalScope 方法。addGlobalScope 方法仅接受范围实例作为其唯一参数

namespace App\Models;

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

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

Elasticsearch 还允许您使用闭包定义全局范围,这对于不需要单独类的简单范围特别有用。当使用闭包定义全局范围时,您应将自定义范围名称作为第一个参数传递给 addGlobalScope 方法。

namespace App\Models;

use Matchory\Elasticsearch\Query;
use Matchory\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));
        });
    }
}
移除全局范围

如果您希望从给定查询中删除全局范围,可以使用 withoutGlobalScope 方法。此方法仅接受全局范围类的名称作为其唯一参数。

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

或者,如果您使用闭包定义了全局范围,应传递分配给全局范围的字符串名称。

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

如果您想移除查询的多个甚至全部全局作用域,可以使用withoutGlobalScopes方法

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

本地作用域

本地作用域允许您定义可以在整个应用程序中轻松重用的常见查询约束集合。例如,您可能需要经常检索所有被认为是“流行”的帖子。

编写本地作用域

要定义作用域,请将作用域前缀添加到Elasticsearch模型方法之前。作用域应始终返回一个查询构建器实例

namespace App\Models;

use Matchory\Elasticsearch\Model;

class Post extends Model
{
    /**
     * Scope a query to only include popular posts.
     *
     * @param  \Matchory\Elasticsearch\Query  $query
     * @return \Matchory\Elasticsearch\Query
     */
    public function scopePopular(Query $query): Query
    {
        return $query->where('votes', '>', 100);
    }

    /**
     * Scope a query to only include published posts.
     *
     * @param  \Matchory\Elasticsearch\Query  $query
     * @return \Matchory\Elasticsearch\Query
     */
    public function scopePublished(Query $query): Query
    {
        return $query->where('published', 1);
    }
}
利用本地作用域

一旦定义了作用域,您可以在查询模型时调用作用域方法。但是,在调用方法时不应包括作用域前缀。您甚至可以链式调用多个作用域

use App\Models\Post;

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

动态作用域

有时您可能希望定义一个接受参数的作用域。要开始,只需将您的额外参数添加到作用域方法签名中。作用域参数应在$query参数之后定义

namespace App\Models;

use Matchory\Elasticsearch\Model;

class Post extends Model
{
    /**
     * Scope a query to only include posts of a given type.
     *
     * @param  \Matchory\Elasticsearch\Query  $query
     * @param  mixed  $type
     * @return \Matchory\Elasticsearch\Query
     */
    public function scopeOfType(Query $query, $type): Query
    {
        return $query->where('type', $type);
    }
}

一旦将预期参数添加到作用域方法签名中,您可以在调用作用域时传递这些参数

$posts = Post::ofType('news')->get();

比较模型

有时您可能需要确定两个模型是否是“相同的”。可以使用is方法快速验证两个模型具有相同的ID、索引、类型和连接

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

事件

Elasticsearch模型派发了几个事件,允许您挂钩模型生命周期的以下时刻:retrievedcreatingcreatedupdatingupdatedsavedsaveddeletingdeletedrestoringrestoredreplicating

retrieved事件将在从索引检索现有模型时触发。当新模型首次保存时,将触发creatingcreated事件。当现有模型被修改且调用save方法时,将触发updating/updated事件。当模型被创建或更新(即使模型属性没有更改)时,将触发save/saved事件。

要开始监听模型事件,请在您的Elasticsearch模型上定义一个dispatchesEvents属性。此属性将Elasticsearch模型生命周期的不同点映射到您自己的事件类。每个模型事件类都应通过其构造函数接收受影响模型的实例

namespace App\Models;

use Matchory\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,
    ];
}

定义并映射事件后,您可以使用事件监听器来处理事件。

使用闭包

除了使用自定义事件类之外,您还可以注册在派发各种模型事件时执行的闭包。通常,您应该在模型的booted方法中注册这些闭包

namespace App\Models;

use Matchory\Elasticsearch\Model;

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

如果需要,您可以在注册模型事件时利用可排队匿名事件监听器。这将指示Laravel在后台使用您的应用程序的队列执行模型事件监听器

use function Illuminate\Events\queueable;

static::created(queueable(function ($post): void {
    //
}));
访问器和修改器
定义访问器

要定义访问器,请创建一个名为getFooAttribute的方法,其中Foo是要访问的字段的“骆驼命名法”名称。在此示例中,我们将定义一个对title属性的访问器。访问器将自动在尝试检索title属性值时由模型调用

namespace App;

use Matchory\Elasticsearch\Model;

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

如您所见,字段的原始值传递给访问器,允许您修改并返回值。要访问访问器的值,您只需在模型实例上访问title属性

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

$title = $post->title;

偶尔,您可能需要添加没有对应索引字段的数组属性。为此,只需为值定义一个访问器

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

一旦创建了访问器,只需将其添加到模型上的appends属性

protected $appends = ['is_published'];

一旦属性被添加到appends列表中,它将被包括在模型的数组中。

定义修改器

要定义一个修改器,在你的模型上定义一个 setFooAttribute 方法,其中 Foo 是你想访问的字段的“大写命名”名称。所以,再次,让我们定义一个针对 title 属性的修改器。当尝试在模型上设置 title 属性的值时,此修改器将被自动调用。

namespace App;

use Matchory\Elasticsearch\Model;

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

修改器将接收要设置在属性上的值,允许你操纵该值,并将操纵后的值设置在模型内部的 $attributes 属性上。例如,如果我们尝试将标题属性设置为 Awesome post to read

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

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

在这个例子中,setTitleAttribute 函数将使用值 Awesome post to read 被调用。修改器然后将应用 strtolower 函数到名称上,并将结果值设置在内部的 $attributes 数组中。

静默事件

有时你可能需要暂时“静默”模型触发的所有事件。你可以使用 withoutEvents 方法来实现这一点。该方法只接受一个闭包作为其唯一参数。在这个闭包中执行的任何代码都不会触发模型事件。例如,以下示例将在不触发任何模型事件的情况下获取并删除一个 App\Models\Post 实例。闭包返回的任何值都将由 withoutEvents 方法返回。

use App\Models\Post;

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

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

无事件保存单个模型

有时你可能希望“保存”一个给定的模型而不触发任何事件。你可以使用 saveQuietly 方法来达到这个目的。

$post = Post::findOrFail(1);

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

$post->saveQuietly();

复制模型

你可以使用 replicate 方法创建现有模型实例的一个未保存副本。此方法特别适用于具有许多相同属性的模式实例。

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();

修改器和类型转换

访问器、修改器和属性转换允许你在模型实例检索或设置属性值时转换 Elasticsearch 属性值。例如,你可能想使用 Laravel 加密器 在存储在索引时加密一个值,然后在访问 Elasticsearch 模型上的属性时自动解密该属性。或者,你可能想在访问你的 Elasticsearch 模型时将存储在索引中的 JSON 字符串转换为数组。

访问器和修改器

定义访问器

访问器在访问时转换 Elasticsearch 属性值。要定义一个访问器,在你的模型上创建一个 get{Attribute}Attribute 方法,其中 {Attribute} 是你想要访问的字段的“大写命名”名称。

在这个例子中,我们将为 first_name 属性定义一个访问器。Elasticsearch 将在尝试检索 first_name 属性值时自动调用该访问器。

namespace App\Models;

use Matchory\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);
    }
}

如你所见,字段的原始值被传递到访问器中,允许你操纵并返回该值。要访问访问器的值,你可以在模型实例上简单地访问 first_name 属性。

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}";
}
定义修改器

修改器在设置时转换 Elasticsearch 属性值。要定义一个修改器,在你的模型上定义一个 set{Attribute}Attribute 方法,其中 {Attribute} 是你想要访问的字段的“大写命名”名称。

让我们为 first_name 属性定义一个修改器。当尝试在模型上设置 first_name 属性的值时,此修改器将被自动调用。

namespace App\Models;

use Matchory\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);
    }
}

修改器将接收要设置在属性上的值,允许你操纵该值,并将操纵后的值设置在 Elasticsearch 模型的内部 $attributes 属性上。要使用我们的修改器,我们只需要设置 Elasticsearch 模型上的 first_name 属性。

use App\Models\User;

$user = User::find(1);

$user->first_name = 'Sally';

在这个例子中,将调用setFirstNameAttribute函数并传入值Sally。然后,修改器将应用strtolower函数处理名称,并将结果值设置在内部的$attributes数组中。

属性类型转换

属性类型转换提供了类似于访问器和修改器功能,而无需在模型上定义任何额外的方法。相反,你的模型的$casts属性提供了一种方便的方法来将属性转换为常见的数据类型。

$casts属性应该是一个数组,其中键是要转换的属性名称,值是希望转换的字段类型。支持的类型转换包括:

  • 数组
  • 布尔值
  • 集合
  • 日期
  • 日期时间
  • 十进制:
  • 双精度浮点数
  • 加密
  • 加密:数组
  • 加密:集合
  • 加密:对象
  • 浮点数
  • 整数
  • 对象
  • 实数
  • 字符串
  • 时间戳

为了演示属性类型转换,让我们将is_admin属性转换为布尔值,该属性在我们的索引中以整数形式存储(01

namespace App\Models;

use Matchory\Elasticsearch\Model;

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

定义类型转换后,当访问is_admin属性时,它总是会被转换成布尔值,即使底层的值在索引中以整数形式存储

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

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

注意:空值属性将不会进行类型转换。

日期类型转换

你可以在模型的$casts属性数组中定义日期属性进行类型转换。通常,日期应该使用datetime类型进行转换。

在定义datedatetime类型转换时,你也可以指定日期的格式。此格式将在模型序列化为数组或JSON时使用

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

当字段被转换为日期时,你可以将其值设置为UNIX时间戳、日期字符串(Y-m-d)、日期时间字符串或DateTime / Carbon实例。日期的值将被正确转换并存储在索引中

你可以通过在模型上定义一个serializeDate方法来自定义模型所有日期的默认序列化格式。此方法不会影响你的日期在索引中存储的格式

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

要指定在索引中实际存储模型日期时应使用的格式,你应在模型上定义一个$dateFormat属性

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

自定义类型转换

Laravel提供了多种内置的有用的类型转换类型;然而,有时你可能需要定义自己的类型转换。你可以通过定义一个实现CastsAttributes接口的类来实现这一点。

实现此接口的类必须定义一个getset方法。get方法负责将索引中的原始值转换为类型转换值,而set方法应将类型转换值转换为可以存储在索引中的原始值。作为一个例子,我们将重新实现内置的json类型转换为一个自定义类型转换

注意:由于类型不兼容,你需要为Eloquent和Elasticsearch模型使用不同的类型转换,或者省略参数类型。

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Json implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  \Illuminate\Database\Eloquent\Model|\Matchory\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|\Matchory\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 Matchory\Elasticsearch\Model;

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

你不仅可以将值转换为基本类型,还可以将值转换为对象。定义将值转换为对象的类型转换与将值转换为基本类型非常相似;然而,set方法应返回一个键/值对的数组,这些键/值对将用于在模型上设置原始的可存储值。

例如,我们将定义一个自定义转换类,该类将多个模型值转换为单个 Address 值对象。我们假设 Address 值有两个公共属性:lineOnelineTwo

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|\Matchory\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|\Matchory\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();

提示:如果您计划将包含值对象的 Elasticsearch 模型序列化为 JSON 或数组,您应该在值对象上实现 Illuminate\Contracts\Support\ArrayableJsonSerializable 接口。

数组/JSON 序列化

当使用 toArraytoJson 方法将 Elasticsearch 模型转换为数组或 JSON 时,只要自定义转换值对象实现了 Illuminate\Contracts\Support\ArrayableJsonSerializable 接口,它们通常也会被序列化。然而,当使用第三方库提供的值对象时,您可能无法将这接口添加到对象中。

因此,您可以指定自定义转换类负责序列化值对象。为此,您的自定义类转换应实现 Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes 接口。该接口表明,您的类应包含一个 serialize 方法,该方法应返回您的值对象的序列化形式

/**
 * Get the serialized representation of the value.
 *
 * @param  \Illuminate\Database\Eloquent\Model|\Matchory\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;
}
入站转换

有时,您可能需要编写一个自定义转换,该转换仅转换模型上设置的值,而不会在从模型检索属性时执行任何操作。一个仅入站的经典示例是“哈希”转换。仅入站的自定义转换应实现 CastsInboundAttributes 接口,该接口仅要求定义一个 set 方法。

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|\Matchory\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',
];
可转换对象

您可能希望允许应用程序的值对象定义它们自己的自定义转换类。您可以将值对象类附加到实现 Illuminate\Contracts\Database\Eloquent\Castable 接口的对象上,而不是将自定义转换类附加到模型上

use App\Models\Address;

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

实现 Castable 接口的对象必须定义一个 castUsing 方法,该方法返回负责将 Castable 类转换为和从转换的自定义转换器类的类名

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;
    }
}

当使用 Castable 类时,您仍然可以在 $casts 定义中提供参数。这些参数将传递给 castUsing 方法

use App\Models\Address;

protected $casts = [
    'address' => Address::class.':argument',
];
可转换对象与匿名转换类

通过结合“可转换对象”和 PHP 的 匿名类,您可以定义一个值对象及其转换逻辑作为单个可转换对象。为此,从值对象的 castUsing 方法返回一个匿名类。该匿名类应实现 CastsAttributes 接口

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,
                ];
            }
        };
    }
}

路由模型绑定

当将模型 ID 注入路由或控制器操作时,您通常会查询 Elasticsearch 索引以检索与该 ID 对应的模型。Laravel 路由模型绑定提供了一种方便的方法,可以自动将模型实例直接注入到路由中。例如,您可以使用整个匹配给定 ID 的 User 模型实例,而不是注入用户 ID。

隐式绑定

Laravel 会自动解析在路由或控制器操作中定义的 Elasticsearch 模型,其类型提示变量名与路由段名称匹配。例如

use App\Models\Post;

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

由于$post变量被类型提示为App\Models\Post Elasticsearch模型,并且变量名与{post} URI段匹配,Laravel将自动注入具有与请求URI中相应值匹配的ID的模型实例。如果在数据库中找不到匹配的模型实例,将自动生成一个404 HTTP响应。

当然,在使用控制器方法时,也可以使用隐式绑定。再次注意,{post} URI段与控制器中的$post变量匹配,该变量包含App\Models\Post类型提示。

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]);
}

自定义键

有时您可能希望使用除_id之外的字段来解析Elasticsearch模型。为此,您可以在路由参数定义中指定该字段。

use App\Models\Post;

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

如果您希望模型绑定始终在检索给定的模型类时使用除_id之外的索引字段,您可以在Elasticsearch模型上重写getRouteKeyName方法。

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

自定义缺失模型行为

通常,如果找不到隐式绑定的模型,将生成一个404 HTTP响应。但是,您可以通过在定义路由时调用丢失的方法来自定义此行为。丢失的方法接受一个闭包,当找不到隐式绑定的模型时,将调用此闭包。

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');

显式绑定

您不必使用Laravel的隐式、基于约定的模型解析来使用模型绑定。您还可以显式定义路由参数与模型之间的对应关系。要注册显式绑定,请使用路由器的model方法指定给定参数的类。您应该在RouteServiceProvider类的boot方法开始处定义您的显式模型绑定。

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);

    // ...
}

接下来,定义一个包含{post}参数的路由。

use App\Models\Post;

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

由于我们已经将所有{post}参数绑定到App\Models\Post模型,将向路由注入该类的实例。因此,例如,对posts/1的请求将注入具有ID为1的索引中的Post实例。

如果在索引中找不到匹配的模型实例,将自动生成一个404 HTTP响应。

自定义解析逻辑

如果您希望定义自己的模型绑定解析逻辑,可以使用Route::bind方法。您传递给bind方法的闭包将接收URI段值,并应返回应注入到路由中的类的实例。再次提醒,这种自定义应该在您的应用程序的RouteServiceProviderboot方法中执行。

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();
    });

    // ...
}

或者,您可以在Elasticsearch模型上重写resolveRouteBinding方法。此方法将接收URI段值,并应返回应注入到路由中的类的实例。

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

如果路由正在使用隐式绑定作用域,将使用resolveChildRouteBinding方法来解决父模型的子绑定。

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

作为查询构建器使用

您可以使用ES外观在任何地方直接访问查询构建器。

创建新索引

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

创建具有自定义选项的索引(可选)

use Matchory\Elasticsearch\Facades\ES;
use Matchory\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

在查询中显式设置连接或索引名称将覆盖config/es.php中的配置。

通过ID获取文档

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();

WHERE子句

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

# or

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

WHERE大于

ES::type("my_type")->where("views", ">", 150)->get();

WHERE大于等于

ES::type("my_type")->where("views", ">=", 150)->get();

WHERE小于

ES::type("my_type")->where("views", "<", 150)->get();

WHERE小于等于

ES::type("my_type")->where("views", "<=", 150)->get();

WHERE LIKE

ES::type("my_type")->where("title", "like", "foo")->get();

WHERE字段存在

ES::type("my_type")->where("hobbies", "exists", true)->get(); 

# or 

ES::type("my_type")->whereExists("hobbies", true)->get();

WHERE IN子句

ES::type("my_type")->whereIn("id", [100, 150])->get();

WHERE BETWEEN子句

ES::type("my_type")->whereBetween("id", 100, 150)->get();

# or 

ES::type("my_type")->whereBetween("id", [100, 150])->get();

WHERE NOT子句

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

# or

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

不大于

ES::type("my_type")->whereNot("views", ">", 150)->get();

不大于等于

ES::type("my_type")->whereNot("views", ">=", 150)->get();

不小于

ES::type("my_type")->whereNot("views", "<", 150)->get();

不小于等于

ES::type("my_type")->whereNot("views", "<=", 150)->get();

不匹配

ES::type("my_type")->whereNot("title", "like", "foo")->get();

字段不存在

ES::type("my_type")->whereNot("hobbies", "exists", true)->get(); 

# or

ES::type("my_type")->whereExists("hobbies", true)->get();

不在子句中

ES::type("my_type")->whereNotIn("id", [100, 150])->get();

不在子句之间

ES::type("my_type")->whereNotBetween("id", 100, 150)->get();

# or

ES::type("my_type")->whereNotBetween("id", [100, 150])->get();

基于地理点的距离搜索

ES::type("my_type")->distance("location", ["lat" => -33.8688197, "lon" => 151.20929550000005], "10km")->get();

# or

ES::type("my_type")->distance("location", "-33.8688197,151.20929550000005", "10km")->get();

# or

ES::type("my_type")->distance("location", [151.20929550000005, -33.8688197], "10km")->get();  

使用数组查询搜索

ES::type("my_type")->body([
    "query" => [
         "bool" => [
             "must" => [
                 [ "match" => [ "address" => "mill" ] ],
                 [ "match" => [ "address" => "lane" ] ]
             ]
         ]
     ]
])->get();

# Note that you can mix between query builder and array queries.
# The query builder will will be merged with the array query.

ES::type("my_type")->body([
	"_source" => ["content"]
	
	"query" => [
	     "bool" => [
	         "must" => [
	             [ "match" => [ "address" => "mill" ] ]
	         ]
	     ]
	],
	   
	"sort" => [
		"_score"
	]
     
])->select("name")->orderBy("created_at", "desc")->take(10)->skip(5)->get();

# The result query will be
/*
Array
(
    [index] => my_index
    [type] => my_type
    [body] => Array
        (
            [_source] => Array
                (
                    [0] => content
                    [1] => name
                )
            [query] => Array
                (
                    [bool] => Array
                        (
                            [must] => Array
                                (
                                    [0] => Array
                                        (
                                            [match] => Array
                                                (
                                                    [address] => mill
                                                )
                                        )
                                )
                        )
                )
            [sort] => Array
                (
                    [0] => _score
                    [1] => Array
                        (
                            [created_at] => desc
                        )
                )
        )
    [from] => 5
    [size] => 10
    [client] => Array
        (
            [ignore] => Array
                (
                )
        )
)
*/

搜索整个文档

ES::type("my_type")->search("hello")->get();
    
# search with Boost = 2
    
ES::type("my_type")->search("hello", 2)->get();

# search within specific fields with different weights

ES::type("my_type")->search("hello", function($search){
	$search->boost(2)->fields(["title" => 2, "content" => 1])
})->get();

高亮字段搜索

$doc = ES::type("my_type")->highlight("title")->search("hello")->first();

# Multiple fields Highlighting is allowed.

$doc = ES::type("my_type")->highlight("title", "content")->search("hello")->first();

# Return all highlights as array using $doc->getHighlights() method.

$doc->getHighlights();

# Also you can return only highlights of specific field.

$doc->getHighlights("title");

仅返回第一个文档

ES::type("my_type")->search("hello")->first();

仅返回计数

ES::type("my_type")->search("hello")->count();

扫描和滚动查询

# These queries are suitable for large amount of data. 
# A scrolled search allows you to do an initial search and to keep pulling batches of results
# from Elasticsearch until there are no more results left.
# It’s a bit like a cursor in a traditional database
    
$documents = ES::type("my_type")->search("hello")
                 ->scroll("2m")
                 ->take(1000)
                 ->get();

# Response will contain a hashed code `scroll_id` will be used to get the next result by running

$documents = ES::type("my_type")->search("hello")
                 ->scroll("2m")
                 ->scrollID("DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAAFMFlJQOEtTdnJIUklhcU1FX2VqS0EwZncAAAAAAAABSxZSUDhLU3ZySFJJYXFNRV9laktBMGZ3AAAAAAAAAU4WUlA4S1N2ckhSSWFxTUVfZWpLQTBmdwAAAAAAAAFPFlJQOEtTdnJIUklhcU1FX2VqS0EwZncAAAAAAAABTRZSUDhLU3ZySFJJYXFNRV9laktBMGZ3")
                 ->get();

# And so on ...
# Note that you don't need to write the query parameters in every scroll. All you need the `scroll_id` and query scroll time.
    
# To clear `scroll_id` 
  
ES::type("my_type")->scrollID("DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAAFMFlJQOEtTdnJIUklhcU1FX2VqS0EwZncAAAAAAAABSxZSUDhLU3ZySFJJYXFNRV9laktBMGZ3AAAAAAAAAU4WUlA4S1N2ckhSSWFxTUVfZWpLQTBmdwAAAAAAAAFPFlJQOEtTdnJIUklhcU1FX2VqS0EwZncAAAAAAAABTRZSUDhLU3ZySFJJYXFNRV9laktBMGZ3")
        ->clear();

每页5个文档分页显示

$documents = ES::type("my_type")->search("hello")->paginate(5);
    
# Getting pagination links
    
$documents->links();

# Bootstrap 4 pagination

$documents->links("bootstrap-4");

# Simple bootstrap 4 pagination

$documents->links("simple-bootstrap-4");

# Simple pagination

$documents->links("simple-default");

这些都是您可以使用的所有分页方法

$documents->count()
$documents->currentPage()
$documents->firstItem()
$documents->hasMorePages()
$documents->lastItem()
$documents->lastPage()
$documents->nextPageUrl()
$documents->perPage()
$documents->previousPageUrl()
$documents->total()
$documents->url($page)

获取查询数组而不执行

ES::type("my_type")->search("hello")->where("views", ">", 150)->toArray();

获取原始Elasticsearch响应

ES::type("my_type")->search("hello")->where("views", ">", 150)->response();

忽略错误的HTTP响应

ES::type("my_type")->ignore(404, 500)->id(5)->first();

查询缓存(Laravel & Lumen)

该包包含基于Laravel缓存的内置缓存层。

ES::type("my_type")->search("hello")->remember(10)->get();

# Specify a custom cache key
ES::type("my_type")->search("hello")->remember(10, "last_documents")->get();

# Caching using other available driver
ES::type("my_type")->search("hello")->cacheDriver("redis")->remember(10, "last_documents")->get();

# Caching with cache key prefix
ES::type("my_type")->search("hello")->cacheDriver("redis")->cachePrefix("docs")->remember(10, "last_documents")->get();

执行Elasticsearch原生查询

ES::raw()->search([
    "index" => "my_index",
    "type"  => "my_type",
    "body" => [
        "query" => [
            "bool" => [
                "must" => [
                    [ "match" => [ "address" => "mill" ] ],
                    [ "match" => [ "address" => "lane" ] ]
                ]
            ]
        ]
    ]
]);

插入新文档

ES::type("my_type")->id(3)->insert([
    "title" => "Test document",
    "content" => "Sample content"
]);
     
# A new document will be inserted with _id = 3.
# [id is optional] if not specified, a unique hash key will be generated.

一次批量插入多个文档。

# Main query
ES::index("my_index")->type("my_type")->bulk(function ($bulk){

    # Sub queries
	$bulk->index("my_index_1")->type("my_type_1")->id(10)->insert(["title" => "Test document 1","content" => "Sample content 1"]);
	$bulk->index("my_index_2")->id(11)->insert(["title" => "Test document 2","content" => "Sample content 2"]);
	$bulk->id(12)->insert(["title" => "Test document 3", "content" => "Sample content 3"]);
	
});

# Notes from the above query:

# As index and type names are required for insertion, Index and type names are extendable. This means that: 

# If index() is not specified in subquery:
# -- The builder will get index name from the main query.
# -- if index is not specified in main query, the builder will get index name from configuration file.

# And

# If type() is not specified in subquery:
# -- The builder will get type name from the main query.
# you can use old bulk code style using multidimensional array of [id => data] pairs
 
ES::type("my_type")->bulk([
 
	10 => [
		"title" => "Test document 1",
		"content" => "Sample content 1"
	],

	11 => [
		"title" => "Test document 2",
		"content" => "Sample content 2"
	]
 
]);
 
# The two given documents will be inserted with its associated ids

更新现有文档

ES::type("my_type")->id(3)->update([
   "title" => "Test document",
   "content" => "sample content"
]);
    
# Document has _id = 3 will be updated.
    
# [id is required]
# Bulk update

ES::type("my_type")->bulk(function ($bulk){
    $bulk->id(10)->update(["title" => "Test document 1","content" => "Sample content 1"]);
    $bulk->id(11)->update(["title" => "Test document 2","content" => "Sample content 2"]);
});

增加字段

ES::type("my_type")->id(3)->increment("views");
    
# Document has _id = 3 will be incremented by 1.

ES::type("my_type")->id(3)->increment("views", 3);

# Document has _id = 3 will be incremented by 3.

# [id is required]

减少字段

ES::type("my_type")->id(3)->decrement("views");
    
# Document has _id = 3 will be decremented by 1.
    
ES::type("my_type")->id(3)->decrement("views", 3);
    
# Document has _id = 3 will be decremented by 3.

# [id is required]

使用脚本更新

# increment field by script
ES::type("my_type")->id(3)->script(
    "ctx._source.$field += params.count",
    ["count" => 1]
);
    
# add php tag to tags array list
ES::type("my_type")->id(3)->script(
    "ctx._source.tags.add(params.tag)",
    ["tag" => "php"]
);
    
# delete the doc if the tags field contain mongodb, otherwise it does nothing (noop)
ES::type("my_type")->id(3)->script(
    "if (ctx._source.tags.contains(params.tag)) { ctx.op = 'delete' } else { ctx.op = 'none' }",
    ["tag" => "mongodb"]
);

删除文档

ES::type("my_type")->id(3)->delete();

# Document has _id = 3 will be deleted.
# [id is required]
# Bulk delete
ES::type("my_type")->bulk(function ($bulk){
    $bulk->id(10)->delete();
    $bulk->id(11)->delete();
});

版本

请查看发布页面

作者

Basem Khirat - basemkhirat@gmail.com - @basemkhirat
Moritz Friedrich - moritz@matchory.com

错误、建议和贡献

感谢所有为原始项目做出贡献的以及为这个分支做出贡献的所有人
请使用Github来报告错误、发表评论或建议。

如果您有兴趣提供帮助,最紧迫的问题是使查询构建器现代化,以提供对Elasticsearch功能的更好支持,以及完成测试套件!

许可

MIT

祝您搜索愉快。