nordsoftware/lumen-elasticsearch

该包已被废弃,不再维护。没有建议的替代包。

为Lumen PHP框架简单封装了https://github.com/elastic/elasticsearch-php。

3.8.2 2020-01-15 09:01 UTC

README

Build Status Coverage Status Code Climate Scrutinizer Code Quality StyleCI Latest Stable Version Total Downloads License

Elasticsearch-PHP提供简单封装,适用于Lumen PHP框架

版本支持

Lumen Elasticsearch PHP
>= 6.0 5.x >= 7.1 3.8 - 3.x
>= 5.4, <= 6.0 5.x >= 7.1 3.0 - 3.7
5.4.x 5.x >= 5.6 2.x
5.4.x 2.x >= 5.6 1.x
5.2.x 2.x >= 5.6 0.7.x

要求

  • 3.x 需要 PHP 7.1 或更高版本
  • 2.x 需要 PHP 5.6 或更高版本

使用

安装

运行以下命令通过Composer安装包

composer require nordsoftware/lumen-elasticsearch

将配置模板config/elasticsearch.php复制到您的应用的config目录,并根据需要修改。

将以下行添加到bootstrap/app.php

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

现在,您可以使用app(ElasticsearchServiceContract::class)获取服务实例,或在需要的地方注入ElasticsearchServiceContract

配置您的索引

您可以使用提供的控制台命令创建和删除索引。首先将命令添加到您的控制台内核

protected $commands = [
	...
	CreateCommand::class,
	DeleteCommand::class,
];

要创建一个索引,您需要一个描述索引外观的配置文件。要创建名为my-index的索引,在config/elasticsearch目录中创建一个名为my-index.php的文件(如果不存在则创建该目录),内容如下

<?php

return [
    'index' => 'my-index',
    'body' => [
        'mappings' => [
            'my-model' => [
                'properties' => [
                    'id' => ['type' => 'string', 'index' => 'not_analyzed'],
                    'name' => ['type' => 'string'],
                ],
            ],
        ],
        'settings' => [
            'analysis' => [
                'filter' => [
                    'finnish_stop' => [
                        'type' => 'stop',
                        'stopwords' => '_finnish_',
                    ],
                    'finnish_stemmer' => [
                        'type' => 'stemmer',
                        'language' => 'finnish',
                    ],
                ],
                'analyzer' => [
                    'finnish' => [
                        'tokenizer' => 'standard',
                        'filter' => [
                            'lowercase',
                            'finnish_stop',
                            'finnish_stemmer',
                        ],
                    ],
                ],
            ],
        ],
    ],
];

请参阅Elasticsearch官方文档以获取有关如何定义索引的更多信息。

现在您已经有了索引的配置文件,可以通过运行php artisan elastic:index:create config/elasticsearch/my-index.php来创建它。

要删除索引,运行php artisan elastic:index:delete my-index

索引您的数据

要将数据索引到新创建的索引中,您需要创建一个新的控制台命令,该命令扩展了Nord\Lumen\Elasticsearch\Console\IndexCommand,然后将其注册到您的控制台内核。一个示例实现可能如下所示

<?php

use Nord\Lumen\Elasticsearch\Console\IndexCommand;

class IndexPersonsCommand extends IndexCommand
{

    protected $signature = 'app:index:persons';

    protected $description = 'Indexes all persons into the search index';

    public function getData()
    {
        return [
            new Person('Joe'),
            new Person('Jane'),
        ];
    }

    public function getIndex()
    {
        return 'persons';
    }

    public function getType()
    {
        return 'person';
    }

    public function getItemBody($item)
    {
        // Item is an instance of Person in this case
        return $item->getName();
    }

    public function getItemId($item)
    {
        // Item is an instance of Person in this case
        return $item->getId();
    }

    public function getItemParent($item)
    {
        // Return null if your objects don't have any parent/child relationship
        return $item->getParent();
    }

}

现在,运行php artisan app:index:persons来索引数据。您现在可以为需要索引的其他数据类型创建额外的命令。

除了IndexCommand之外,还有一个AbstractMultiIndexCommand,如果需要将相同的数据索引到多个索引中,可以使用它。这在将Elasticsearch 5.x索引迁移到不支持具有多个不同文档类型的Elasticsearch 6.x时非常有用。

索引单个项目

控制台命令在您需要索引特定类型的所有项目时非常有用,例如,您的数据库中的所有人。但是,如果您更新了单个人员,您可能只想重新索引那个人。

以下是一个示例

$service = app(ElasticsearchServiceContract::class);

$service->index([
	'index' => 'persons',
	'type'  => 'person',
	'id'    => $person->getId(),
	'body'  => $person->getName(),
]);

运行查询

通过创建一个查询,然后使用该查询创建一个搜索,最后使用提供的服务执行该查询来运行对搜索索引的查询。

以下是一个示例

// Get an instance of ElasticSearchService
$service = app(ElasticsearchServiceContract::class);

// Create the query
$query = (new BoolQuery())
    ->addMust(
        (new TermQuery())
            ->setField('user')
            ->setValue('kimchy'))
    ->addFilter(
        (new TermQuery())
            ->setField('tag')
            ->setValue('tech'))
    ->addMustNot(
        (new RangeQuery())
            ->setField('age')
            ->setGreaterThanOrEquals(18)
            ->setLessThanOrEquals(40))
    ->addShould(
        (new TermQuery())
            ->setField('tag')
            ->setValue('wow'))
    ->addShould(
        (new TermQuery())
            ->setField('tag')
            ->setValue('elasticsearch'));

// Create the search
$search = $service->createSearch()
    ->setIndex('index')
    ->setType('document')
    ->setQuery($query)
    ->setSize(50)
    ->setPage(1);

// Execute the search to retrieve the results
$result = $service->execute($search);

您还可以执行原始查询

$service = app(ElasticsearchServiceContract::class);

$result = $service->search([
    'index' => 'index',
    'type'  => 'document',
    'body'  => [
        'query' => [
            'bool' => [
                'must' => [
                    'term' => ['user' => 'kimchy']
                ],
                'filter' => [
                    'term' => ['tag' => 'tech']
                ],
                'must_not' => [
                    'range' => [
                        'age' => ['gte' => 10, 'lte' => 20]
                    ]
                ],
                'should' => [
                    [
                        'term' => ['tag' => 'wow']
                    ],
                    [
                        'term' => ['tag' => 'elasticsearch']
                    ]
                ],
            ]
        ],
        'size' => 50,
        'from' => 0
    ],
]);

创建和应用索引迁移

有时您需要更改索引映射,这需要重新索引数据。然而,大多数时候,您不需要再次将所有内容索引到Elasticsearch中,而是只需从原始索引内部复制到新索引即可。这个过程可以在不停机的情况下无缝执行。

要求

  • 您必须将CreateMigrationCommandApplyMigrationCommand命令添加到您的控制台内核
  • 您的Elasticsearch实例必须支持/_reindex API。这通常是情况,但是,如果您使用的是Elasticsearch 2.3或更早版本,Amazon Elasticsearch Service不支持它。

创建迁移

  • 根据您的需要更改索引定义(例如,config/search/your-index.php
  • 运行php artisan elastic:migrations:create config/search/your-index.php

这将创建一个名为versions的目录,以及索引定义文件的带时间戳的副本。

应用迁移

  • 运行php artisan elastic:migrations:migrate config/search/your-index.php

如果您之前未运行迁移,一旦创建新索引,索引将被替换为同名别名。下次应用迁移时,别名将简单地更新。

如果您的文档非常大,您可能想减少重新索引期间使用的批处理大小,以防止Elasticsearch耗尽内存。您可以通过将--batchSize=X传递给elastic:migrations:migrate命令来实现这一点。如果省略了该选项,则使用默认值1000。

更新动态索引设置

有一个控制台命令(elastic:index:settings:update),您可以使用它来更新某些动态索引设置,例如刷新间隔或副本数。只需将其注册到您的控制台内核即可开始使用。

使用索引前缀

该库支持指定索引名称的前缀,类似于许多框架支持缓存前缀,以便多个应用程序可以共享相同的缓存。这意味着您可以使用单个Elasticsearch集群用于多个项目(例如,“开发”和“预发布”环境的共享一个)。

使用的前缀由配置文件(config/elasticsearch.php)指定。默认行为是从ELASTICSEARCH_INDEX_PREFIX环境变量中读取前缀。

如果您有一个名为content的索引,并且您将foo指定为前缀,则索引将命名为foo_content。如果需要自定义逻辑,您可以在ElasticsearchService中覆盖getPrefixedIndexName()

索引迁移也支持前缀,在这种情况下,创建的索引和别名都将添加前缀。

Pagerfanta集成

包含一个用于方便分页的Pagerfanta适配器。然而,它是可选的,所以如果您打算使用它,您必须明确要求pagerfanta/pagerfanta包。

贡献

请阅读指南

运行测试

通过运行以下命令克隆项目并安装其依赖项

composer install

运行以下命令以运行测试套件

composer test

许可证

请参阅LICENSE