algolia/algoliasearch-laravel-4

此包已被弃用且不再维护。没有推荐替代包。

Laravel 4 Algolia 扩展

1.1.1 2016-06-30 13:28 UTC

This package is not auto-updated.

Last update: 2020-01-22 01:53:15 UTC


README

此包不再维护且已弃用,我们建议使用Laravel Scout,它需要Laravel 5.4及以上版本。

此PHP包将Algolia搜索API集成到Laravel Eloquent ORM中。它基于algoliasearch-client-php包。支持PHP 5.4及以上。

Build Status Latest Version License

目录

  1. 安装
  2. 配置
  3. 快速入门
  4. 排名 & 相关性
  5. 选项
  6. 索引
  7. 主/从
  8. 针对多个索引

安装

algolia/algoliasearch-laravel添加到您的composer.json文件中

composer require algolia/algoliasearch-laravel-4

将服务提供者添加到config/app.php文件中的providers数组。

AlgoliaSearch\Laravel\AlgoliaServiceProvider::class

配置

Laravel Algolia需要配置。要开始,您需要创建一个包含以下内容的algolia.php配置文件

<?php

return array(
    'id' => 'APP_ID',
    'key' => 'SECRET_KEY'
);

您需要修改它以包含您的凭据。

快速入门

以下代码向您的Contact模型添加搜索功能,创建一个Contact索引

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;
}

默认情况下,所有可见属性都会发送。如果您想发送特定的属性,您可以这样做:

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public function getAlgoliaRecord()
    {
        return array_merge($this->toArray(), [
            'custom_name' => 'Custom Name'
        ]);
    }
}

排名 & 相关性

我们提供了多种方法来配置索引设置以调整整体相关性,但最重要的设置是可搜索属性和反映记录流行度的属性。您可以使用以下代码配置它们

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public $algoliaSettings = [
    	'attributesToIndex' => [
    		'id',
    		'name',
    	],
    	'customRanking' => [
    		'desc(popularity)',
    		'asc(name)',
    	],
    ];
}

同义词

同义词用于告诉引擎哪些单词或表达式应该被视为具有文本相关性的等价词。

我们的同义词API已被设计成可以尽可能轻松地管理索引及其从属索引的大量同义词。

您可以通过在$algoliaSettings类属性中添加一个synonyms来使用同义词API,如下所示

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public $algoliaSettings = [
        'synonyms' => [
            [
                'objectID' => 'red-color',
                'type'     => 'synonym',
                'synonyms' => ['red', 'another red', 'yet another red']
            ]
        ]
    ];
}

您可以使用setSetting方法将设置传播(保存)到Algolia

Contact::setSettings();

前端搜索(实时体验)

传统的搜索实现通常将搜索逻辑和功能放在后端。当搜索体验仅包括用户输入搜索查询、执行该搜索然后被重定向到搜索结果页面时,这是有意义的。

在后台实现搜索不再是必要的。实际上,在大多数情况下,由于额外的网络和处理延迟,它会损害性能。我们强烈建议使用我们的JavaScript API客户端,它直接从最终用户的浏览器、移动设备或客户端发出所有搜索请求。这将减少整体搜索延迟,同时减轻服务器的负担。

在您的JavaScript代码中,您可以执行以下操作

var client = algoliasearch('ApplicationID', 'Search-Only-API-Key');
var index = client.initIndex('YourIndexName');
index.search('something', function(success, hits) {
  console.log(success, hits)
}, { hitsPerPage: 10, page: 0 });

后端搜索

您还可以使用 search 方法,但不推荐实现即时/实时搜索体验

Contact::search('jon doe');

您还可以向搜索函数传递额外的参数

Contact::search('jon doe', array('hitsPerPage' => 5));

选项

自动索引 & 异步

每次保存记录时,它将异步索引。另一方面,每次销毁记录时,它将异步从索引中删除。

您可以通过设置以下选项来禁用自动索引和自动删除设置

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
	use AlgoliaEloquentTrait;

	public static $autoIndex = false;
	public static $autoDelete = false;
}

您可以暂时禁用自动索引。这通常用于性能原因。

Contact::$autoIndex = false;
Contact::clearIndices();

for ($i = 0; $i < 10000; $i++) {
	$contact = Contact::firstOrCreate(['name' => 'Jean']);
}

Contact::reindex(); // Will use batch operations.

自定义索引名称

默认情况下,索引名称将是复数形式的类名,例如 "Contacts"。您可以通过使用 $indices 选项来自定义索引名称

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public $indices = ['contact_all'];
}

按环境索引

您可以使用以下选项在索引名称后缀中包含当前应用程序环境

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public static $perEnvironment = true; // Index name will be 'Contacts_{\App::environnement()}';
}

自定义 objectID

默认情况下,objectID 基于您的记录的 keyName(默认为 id)。您可以通过指定 objectIdKey 选项来更改此行为(请确保使用一个唯一的字段)。

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

	public static $objectIdKey = 'new_key';
}

限制索引到您数据的一个子集

您可以通过定义 indexOnly() 方法来添加约束,以控制记录是否必须被索引。

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
   	use AlgoliaEloquentTrait;

	public function indexOnly($index_name)
	{
		return (bool) $condition;
	}
}

关系

默认情况下,Algolia包将获取 已加载 的关系。

如果您想索引尚未加载任何关系的记录,您可以在您的模型中创建 getAlgoliaRecord 来实现。

它看起来像这样

public function getAlgoliaRecord()
{
	/**
	 * Load the categories relation so that it's available
	 * 	in the laravel toArray method
	 */
	$this->categories;

   return $this->toArray();
}

在结果对象中,您将具有由Laravel转换成数组的分类。如果您想自定义关系结构,您将执行类似以下操作

public function getAlgoliaRecord()
{
	/**
	 * Load the categories relation so that it's available
	 * 	in the laravel toArray method
	 */
	$extra_data = [];
	$extra_data['categories'] = array_map(function ($data) {
							            return $data['name'];
						        }, $this->categories->toArray();

   return array_merge($this->toArray(), $extra_data);
}

索引

手动索引

您可以使用 pushToIndex 实例方法来触发索引。

$contact = Contact::firstOrCreate(['name' => 'Jean']);
$contact->pushToIndex();

手动删除

并使用 removeFromIndex 实例方法来触发删除。

$contact = Contact::firstOrCreate(['name' => 'Jean']);
$contact->removeFromIndex();

重新索引

要安全地重新索引所有记录(将索引移动到临时索引+原子性地将临时索引移动到当前索引),请使用 reindex 类方法

Contact::reindex();

要重新索引所有记录(就地,不删除过时的记录)

Contact::reindex(false);

清除索引

要清除索引,请使用 clearIndices 类方法

Contact::clearIndices();

主/从

您可以使用 $algolia_settings 变量来定义从索引。

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
	 use AlgoliaEloquentTrait;

	 public $algoliaSettings = [
		'attributesToIndex' => [
			'id',
			'name',
		],
    	'customRanking' => [
    		'desc(popularity)',
    		'asc(name)',
    	],
    	'slaves' => [
    		'contacts_desc',
    	],
    ];

    public $slavesSettings = [
        'contacts_desc' => [
            'ranking' => [
                'desc(name)',
                'typo',
                'geo',
                'words',
                'proximity',
                'attribute',
                'exact',
                'custom'
            ]
        ]
    ];
}

要使用从索引进行搜索,请使用以下代码

Book::search('foo bar', ['index' => 'contacts_desc']);

目标多个索引

您可以使用 $indices 属性在多个索引中索引记录

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
	use AlgoliaEloquentTrait;

	public $indices = [
		'contact_public',
		'contact_private',
	];

	public function indexOnly($indexName)
	{
		if ($indexName == 'contact_public')
			return true;

		return $this->private;
	}

}

要使用额外索引进行搜索,请使用以下代码:

Book::search('foo bar', ['index' => 'contacts_private']);

Eloquent 兼容性

执行

Ad::where('id', $id)->update($attributes);

不会在模型中触发任何操作(因此不会在 Algolia 中发生更新)。这是因为这并不是一个 Eloquent 调用,而只是隐藏在模型背后的查询的便捷方式

要使此查询与 Algolia 兼容,您需要这样做

Ad::find($id)->update($attributes);

兼容性

与 5.x 应用程序兼容

许可证

Laravel Algolia Search 依据 MIT 许可证 (MIT) 许可。