nqxcode/laravel-lucene-search

Laravel 5.5 包,用于在基于 ZendSearch Lucene 的 Eloquent 模型上执行全文搜索。


README

Latest Stable Version Latest Unstable Version License Build Status Coverage Status

Laravel 5.5 包,用于在基于 ZendSearch Lucene 的 Eloquent 模型上执行全文搜索。

安装

在您的 composer.json 中要求此包,并运行 composer update

{
	"require": {
        "nqxcode/laravel-lucene-search": "2.4.*"
	}
}

更新 composer 后,将 ServiceProvider 添加到 config/app.php 文件中的 providers 数组中

'providers' => [
	Nqxcode\LuceneSearch\ServiceProvider::class,
],

如果您想使用外观搜索,请将以下内容添加到您的 config/app.php 文件中的 facades 中

'aliases' => [
	'Search' => Nqxcode\LuceneSearch\Facade::class,
],

配置

通过运行以下命令将配置文件发布到项目中

php artisan vendor:publish --provider="Nqxcode\LuceneSearch\ServiceProvider"

基本

在发布的配置文件中为需要索引的模型添加描述,例如

'index' => [

	// ...

	namespace\FirstModel::class => [
		'fields' => [
			'name', 'full_description', // fields for indexing
		]
	],

	namespace\SecondModel::class => [
		'fields' => [
			'name', 'short_description', // fields for indexing
		]
	],

	namespace\ModelWithCustomPrimaryKey::class => [
		// You can also define your primary key (if you use something else than "id")
		'primary_key' => 'my_custom_field_name',
		'fields' => [
			'username', 'short_description', // fields for indexing
		]
	],

	// ...

],

动态字段的索引

您还可以索引 可选字段(动态字段)的值。要启用可选字段的索引,请在每个必要模型的配置中添加以下选项

  • 在每个必要模型的配置中添加以下选项
        'optional_attributes' => true

        // or

        'optional_attributes' => [
                'accessor' => 'custom_name' // with specifying of accessor name
        ]
  • 在模型中添加 特殊访问器,该访问器返回 field-name => field-value 列表。默认情况下,将使用 getOptionalAttributesAttribute 访问器。如果配置中指定了访问器名称,则将使用 getCustomNameAttribute 访问器。

示例

在配置文件中

        namespace\FirstModel::class => [
                'fields' => [
                    'name', 'full_description', // fixed fields for indexing
                ],

                'optional_attributes' => true //  enable indexing for dynamic fields
        ],

在模型中添加以下访问器

        public function getOptionalAttributesAttribute()
        {
                return [
                        'optional_attribute1' => 'value1',
                        'optional_attribute2' => 'value2',
                ];
        }

分数提升

有关 Apache Lucene - 分数的详细信息,请参阅 Apache Lucene - Scoring

模型级别提升

这是 Apache Lucene 术语中的 文档级别提升。默认情况下,所有模型的 提升 值均为 1。要更改此行为,请根据以下示例自定义必要模型的提升。

  • 在每个必要模型的配置中添加以下选项
        'boost' => true

        // or

        'boost' => [
                'accessor' => 'custom_name' // with specifying of accessor name
        ]

在模型中添加以下访问器

        public function getBoostAttribute()
        {
                return 0.5; // customize boost value for model
        }
  • 在模型中添加 特殊访问器,该访问器返回提升值。默认情况下,将使用 getBoostAttribute 访问器。如果配置中指定了访问器名称,则将使用 getCustomNameAttribute 访问器。

示例

在配置文件中

        namespace\FirstModel::class => [
                'fields' => [
                    'name', 'full_description',
                ],

                'boost' => true // enable boosting for model
        ],

在模型中添加以下访问器

        public function getBoostAttribute()
        {
                return 0.5; // customize boost value for model
        }

模型的字段级别提升

这是 Apache Lucene 术语中的 文档的字段级别提升。默认情况下,每个字段的 提升 设置为 1。要更改此行为,请根据以下示例设置必要字段的提升。

在配置文件中

        namespace\FirstModel::class => [
                'fields' => [
                    'name', // field with default boost
                    'full_description' => ['boost' => 0.2], // customize boost value
                ],
        ],

或/和在模型访问器中

        public function getOptionalAttributesAttribute()
        {
                return [
                        'optional_attribute1' => 'value1', // field with default boost
                        'optional_attribute2' => ['boost' => 0.5, 'value' => 'value2'], // customize boost value
                ];
        }

词干和停用词

默认情况下,以下过滤器用于搜索

  • 英语/俄语的词干过滤器(将单词还原为其基本形式),
  • 英语/俄语的停用词过滤器(从搜索索引中排除某些单词)。

这些过滤器可以被删除或替换为其他过滤器。

'analyzer' => [
    'filters' => [
    	// Default stemming filter.
    	Nqxcode\Stemming\TokenFilterEnRu::class,
    ],

    // List of paths to files with stopwords.
    'stopwords' => Nqxcode\LuceneSearch\Analyzer\Stopwords\Files::get(),
],

用法

Artisan 命令

初始化或重建搜索索引

要构建搜索索引,请运行

php artisan search:rebuild --verbose

清除搜索索引

要清除搜索索引,请运行

php artisan search:clear

搜索结果中的模型过滤

要过滤搜索结果中的模型,每个模型的类都可以实现 SearchableInterface。例如

use Illuminate\Database\Eloquent\Model;
use Nqxcode\LuceneSearch\Model\SearchableInterface;

class Dummy extends Model implements SearchableInterface
{
        // ...

        /**
         * Get id list for all searchable models.
         */
        public static function searchableIds()
        {
            return self::wherePublish(true)->pluck('id');
        }

        // ...
}

部分更新搜索索引

要注册必要事件(保存/更新/删除),请在目标模型中使用 use Nqxcode\LuceneSearch\Model\SearchTrait

    use Illuminate\Database\Eloquent\Model;
    use Nqxcode\LuceneSearch\Model\SearchableInterface;
    use Nqxcode\LuceneSearch\Model\SearchTrait;

    class Dummy extends Model implements SearchableInterface
    {
        use SearchTrait;

        // ...
    }

执行不进行索引的操作

如果您想避免触发索引,请将必要操作包装在模型上的 withoutSyncingToSearch() 方法中

Product::withoutSyncingToSearch(function () {
    // mass update position for product, e.g.
    foreach (Product::all() as $i => $product) {
        $product->update(['position' => $i)]);
    }    
});

查询构建

以多种方式构建查询

使用构造函数

默认情况下,将创建将执行完全短语搜索的查询。

简单查询
$query = Search::query('clock'); // search by all fields.
// or
$query = Search::where('name', 'clock'); // search by 'name' field.
// or
$query = Search::query('clock')              // search by all fields with
	->where('short_description', 'analog'); // filter by 'short_description' field.
// or
$query = Product::search('clock'); // search only in `Product` model by all fields in case when `Product` use `SearchableTrait`.
高级查询

对于 querywhere 方法,可以设置以下选项

  • phrase - 短语匹配(布尔值,默认为true)
  • proximity - 单词间的距离值(无符号整数)
  • fuzzy - 模糊匹配的值(浮点数,0 ... 1)
  • required - 应匹配(布尔值,默认为true)
  • prohibited - 不应匹配(布尔值,默认为false)
示例

查找所有包含类似“composite one two phrase”短语的模型

$query = Search::query('composite phrase', '*', ['proximity' => 2]);

通过查询中的每个单词进行搜索

$query = Search::query('composite phrase', '*', ['phrase' => false]);

使用Lucene原始查询

$query = Search::rawQuery('short_description:"analog"');
// or
$rawQuery = QueryParser::parse('short_description:"analog"');
$query = Search::rawQuery($rawQuery);

获取结果

对于构建的查询,有以下操作可用

获取所有找到的模型

$models = $query->get();

获取结果计数

$count = $query->count();

获取带有偏移量的限制结果

$models = $query->limit(5, 10)->get(); // Limit = 5 and offset = 10

分页显示找到的模型

$paginator = $query->paginate(50);

匹配项高亮显示

匹配项高亮显示适用于任何以 utf-8 编码的HTML片段,并且仅在最后执行请求时执行。

Search::find('nearly all words must be highlighted')->get();
$highlighted = Search::highlight('all words');

// highlighted html:
// '<span class="highlight">all</span> <span class="highlight">words</span>'

许可证

该软件包根据MIT许可证授权。