awladdeleo/elasticquent

将Laravel Eloquent模型映射到Elasticsearch类型。

dev-main 2021-03-23 15:06 UTC

This package is auto-updated.

Last update: 2024-09-29 05:56:28 UTC


README

Elasticsearch for Eloquent Laravel Models

Elasticquent通过将Eloquent模型映射到Elasticsearch类型,使使用Elasticsearch和Eloquent模型变得更加容易。您可以使用默认设置或在模型中定义Elasticsearch如何索引和搜索您的Eloquent模型。

Elasticquent使用官方Elasticsearch PHP API。要开始,您应该具备Elasticsearch基本工作原理的知识(索引、类型、映射等)。

Elasticsearch需求

您必须运行至少Elasticsearch 1.0。Elasticsearch 0.9及以下版本将不会工作,也不受支持。

内容

报告问题

如果您发现任何问题,请随时通过GitHub的bug跟踪器报告此项目的问题。

或者,您可以分叉项目并创建一个拉取请求 :)

概述

Elasticquent允许您轻松地将Eloquent模型索引和搜索其内容在Elasticsearch中。

    $books = Book::where('id', '<', 200)->get();
    $books->addToIndex();

当您搜索时,您不会得到一个普通的搜索结果数组,而是得到一个具有一些特殊Elasticsearch功能的Eloquent集合。

    $books = Book::search('Moby Dick');
    echo $books->totalHits();

此外,您仍然可以使用所有Eloquent集合功能

    $books = $books->filter(function ($book) {
        return $book->hasISBN();
    });

查看其余的文档,了解如何开始使用Elasticsearch和Elasticquent!

Elasticquent的工作原理

在使用数据库时,Eloquent模型是从数据库表中读取的数据填充的。与Elasticquent一起,模型是通过在Elasticsearch中索引的数据填充的。使用Elasticsearch进行搜索的整体思想是它快速且轻量,因此您模型的功能将由已索引的文档数据决定。

设置

在开始使用Elasticquent之前,请确保您已安装Elasticsearch

要开始,将Elasticquent添加到您的composer.json文件中

"awladdeleo/elasticquent": "dev-master"

一旦运行了composer update,您需要注册Laravel服务提供程序,在config/app.php

'providers' => [
    ...
    Elasticquent\ElasticquentServiceProvider::class,
],

我们还为elasticsearch-php客户端提供了门面(已连接到我们的设置),如果您需要,请将其添加到您的config/app.php中。

'aliases' => [
    ...
    'Es' => Elasticquent\ElasticquentElasticsearchFacade::class,
],

然后,将Elasticquent特质添加到任何您希望能够索引到Elasticsearch中的Eloquent模型

use Elasticquent\ElasticquentTrait;

class Book extends Eloquent
{
    use ElasticquentTrait;
}

现在,您的Eloquent模型具有一些额外的方法,这些方法可以更容易地使用Elasticsearch索引模型数据。

Elasticsearch配置

默认情况下,Elasticquent将会连接到localhost:9200并使用default作为索引名称,你可以通过配置文件更改这些设置和其他设置。对于Laravel 4,你可以在/app/config/elasticquent.php中添加elasticquent.php配置文件,或者使用以下Artisan命令将配置文件发布到你的配置目录,用于Laravel 5:

$ php artisan vendor:publish --provider="Elasticquent\ElasticquentServiceProvider"
<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Custom Elasticsearch Client Configuration
    |--------------------------------------------------------------------------
    |
    | This array will be passed to the Elasticsearch client.
    | See configuration options here:
    |
    | http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_configuration.html
    */

    'config' => [
        'hosts'     => ['localhost:9200'],
        'retries'   => 1,
    ],

    /*
    |--------------------------------------------------------------------------
    | Default Index Name
    |--------------------------------------------------------------------------
    |
    | This is the index name that Elastiquent will use for all
    | Elastiquent models.
    */

    'default_index' => 'my_custom_index_name',

);

索引和映射

虽然你可以通过Elasticsearch API构建索引和映射,但你也可以使用一些辅助方法直接从模型中构建索引和类型。

如果你想简单地创建索引,Elasticquent模型有一个这样的功能。

Book::createIndex($shards = null, $replicas = null);

对于自定义分析器,你可以在模型中设置一个indexSettings属性并从那里定义分析器。

    /**
     * The elasticsearch settings.
     *
     * @var array
     */
    protected $indexSettings = [
        'analysis' => [
            'char_filter' => [
                'replace' => [
                    'type' => 'mapping',
                    'mappings' => [
                        '&=> and '
                    ],
                ],
            ],
            'filter' => [
                'word_delimiter' => [
                    'type' => 'word_delimiter',
                    'split_on_numerics' => false,
                    'split_on_case_change' => true,
                    'generate_word_parts' => true,
                    'generate_number_parts' => true,
                    'catenate_all' => true,
                    'preserve_original' => true,
                    'catenate_numbers' => true,
                ]
            ],
            'analyzer' => [
                'default' => [
                    'type' => 'custom',
                    'char_filter' => [
                        'html_strip',
                        'replace',
                    ],
                    'tokenizer' => 'whitespace',
                    'filter' => [
                        'lowercase',
                        'word_delimiter',
                    ],
                ],
            ],
        ],
    ];

对于映射,你可以在模型中设置一个mappingProperties属性并使用一些映射函数。

protected $mappingProperties = array(
   'title' => array(
        'type' => 'string',
        'analyzer' => 'standard'
    )
);

如果你想根据映射属性设置模型类型的映射,可以使用以下方法:

    Book::putMapping($ignoreConflicts = true);

要删除映射

    Book::deleteMapping();

要重建(删除并重新添加,当你在映射中做出重要更改时很有用)映射

    Book::rebuildMapping();

你还可以获取类型映射并检查它是否存在。

    Book::mappingExists();
    Book::getMapping();

设置自定义索引名称

默认情况下,Elasticquent将在你的配置文件(config/elasticquent.php)中查找default_index键。要设置要使用的索引的默认值,你可以编辑此文件并设置default_index键。

return array(

   // Other configuration keys ...
   
   /*
    |--------------------------------------------------------------------------
    | Default Index Name
    |--------------------------------------------------------------------------
    |
    | This is the index name that Elastiquent will use for all
    | Elastiquent models.
    */
    
   'default_index' => 'my_custom_index_name',
);

如果你想有一个更动态的索引,你还可以在你的Eloquent模型内部覆盖默认配置,使用getIndexName方法。

function getIndexName()
{
    return 'custom_index_name';
}

注意:如果没有指定索引,Elasticquent将使用一个硬编码的字符串,值为default

设置自定义类型名称

默认情况下,Elasticquent将使用你的模型表名作为索引的类型名称。如果你想覆盖它,可以使用getTypeName函数。

function getTypeName()
{
    return 'custom_type_name';
}

要检查Elasticquent模型的类型是否存在,请使用typeExists

    $typeExists = Book::typeExists();

索引文档

要索引Eloquent模型中的所有条目,请使用addAllToIndex

    Book::addAllToIndex();

你也可以索引模型集合。

    $books = Book::where('id', '<', 200)->get();
    $books->addToIndex();

你还可以索引单个条目。

    $book = Book::find($id);
    $book->addToIndex();

你还可以重新索引整个模型。

    Book::reindex();

搜索

Elasticquent中有三种搜索方式。所有三种方法都返回一个搜索集合。

简单术语搜索

第一种方法是一个简单的术语搜索,搜索所有字段。

    $books = Book::search('Moby Dick');

基于查询的搜索

第二种是基于查询的搜索,用于更复杂的搜索需求。

    public static function searchByQuery($query = null, $aggregations = null, $sourceFields = null, $limit = null, $offset = null, $sort = null)

示例

    $books = Book::searchByQuery(array('match' => array('title' => 'Moby Dick')));

以下是可用的参数列表

  • query - 你的ElasticSearch查询
  • aggregations - 你希望返回的聚合。 有关聚合的详细信息,请参阅聚合
  • sourceFields - 将返回的集合限制为所选字段
  • limit - 要返回的记录数
  • offset - 设置记录偏移量(用于分页结果)
  • sort - 你的排序查询

原始查询

最后一种方法是发送到Elasticsearch的原始查询。此方法在搜索Elasticsearch中的记录时提供了最大的灵活性。

    $books = Book::complexSearch(array(
        'body' => array(
            'query' => array(
                'match' => array(
                    'title' => 'Moby Dick'
                )
            )
        )
    ));

这相当于

    $books = Book::searchByQuery(array('match' => array('title' => 'Moby Dick')));

搜索集合

当你在一个Elasticquent模型上搜索时,你会得到一个具有一些特殊函数的搜索集合。

你可以获取总命中数

    $books->totalHits();

访问分片数组

    $books->shards();

访问最大分数

    $books->maxScore();

访问超时布尔属性

    $books->timedOut();

并访问took属性

    $books->took();

并访问搜索聚合 - 有关聚合的详细信息,请参阅聚合

    $books->getAggregations();

搜索集合文档

搜索结果集合中的项目将包含来自Elasticsearch的一些额外数据。你可以始终检查并使用isDocument函数查看一个模型是否是文档。

    $book->isDocument();

你可以使用以下方法检查Elasticsearch分配给此文档的文档分数:

    $book->documentScore();

从Elastiquent分块结果

类似于Illuminate\Support\Collectionchunk方法将Elasticquent集合分割成多个给定大小的更小的集合

    $all_books = Book::searchByQuery(array('match' => array('title' => 'Moby Dick')));
    $books = $all_books->chunk(10);

在Elasticquent外部使用搜索集合

如果您正在处理来自Elasticquent之外的原生搜索数据,可以使用Elasticquent搜索结果集合将此数据转换为集合。

$client = new \Elasticsearch\Client();

$params = array(
    'index' => 'default',
    'type'  => 'books'
);

$params['body']['query']['match']['title'] = 'Moby Dick';

$collection = Book::hydrateElasticsearchResult($client->search($params));

更多选项

文档ID

Elasticquent会将您Eloquent模型中设置的primaryKey作为Elasticsearch文档的ID。

文档数据

默认情况下,Elasticquent将使用您Elasticsearch文档的整个属性数组。但是,如果您想自定义搜索文档的结构,可以设置一个返回您自定义文档数组的getIndexDocumentData函数。

function getIndexDocumentData()
{
    return array(
        'id'      => $this->id,
        'title'   => $this->title,
        'custom'  => 'variable'
    );
}

请注意这一点,因为当Elasticquent创建搜索结果集合时,会将文档源读入Eloquent模型属性中,所以请确保您索引了足够的数据以供您要使用的模型功能。

使用自定义集合与Elasticquent一起使用

如果您正在使用自定义集合与Eloquent模型一起使用,只需将ElasticquentCollectionTrait添加到您的集合中,这样就可以使用addToIndex了。

class MyCollection extends \Illuminate\Database\Eloquent\Collection
{
    use ElasticquentCollectionTrait;
}

路线图

Elasticquent目前需要

  • 模拟ES API调用的测试。
  • 对路由的支持