rias / craft-scout
Craft Scout 为添加全文搜索到您的条目提供了一种简单解决方案。Scout 将自动将您的搜索索引与条目同步。
Requires
- php: ^8.2.0
- algolia/algoliasearch-client-php: ^2.3|^3.0
- craftcms/cms: ^5.0.0-beta.1
- league/fractal: ^0.20
Requires (Dev)
- codeception/codeception: ^5.0.0
- codeception/lib-asserts: ^2.1.0
- codeception/module-asserts: ^3.0
- codeception/module-yii2: ^1.1.10
- craftcms/ecs: dev-main
- craftcms/phpstan: dev-main
- phpunit/phpunit: ^11.2.7
- vlucas/phpdotenv: ^5.3.0
Conflicts
- craftcms/element-api: <4.0.0
- v5.x-dev
- 5.0.1
- 5.0.0
- 5.0.0-beta.1
- 5.0.0-alpha.1
- 4.1.1
- 4.1.0
- 4.1.0-beta.2
- 4.1.0-beta.1
- 4.0.0
- 3.4.1
- 3.4.0
- 3.3.3
- 3.3.3-beta.2
- 3.3.3-beta.1
- 3.3.2
- 3.3.1
- 3.3.0
- 3.2.1
- 3.2.0
- 3.1.3
- 3.1.2.x-dev
- 3.1.2
- 3.1.1
- 3.1.0
- 3.0.0
- 3.0.0-beta.1
- 2.8.1
- 2.8.0
- 2.8.0-beta.3
- 2.8.0-beta.2
- 2.8.0-beta.1
- 2.7.2
- 2.7.1
- 2.7.0
- 2.6.1
- 2.6.0
- 2.5.0
- 2.4.2
- 2.4.1
- 2.4.0
- 2.3.1
- 2.3.0
- 2.2.2
- 2.2.1
- 2.2.0
- 2.1.4
- 2.1.3
- 2.1.2
- 2.1.1
- 2.1.0
- 2.0.2
- 2.0.1
- 2.0.0
- 1.3.2
- 1.3.1
- 1.3.0
- 1.2.3
- 1.2.2
- 1.2.1
- 1.2.0
- 1.1.4
- 1.1.3
- 1.1.2
- 1.1.1
- 1.1.0
- 1.0.2
- 1.0.1
- 1.0.0
- 0.4.2
- 0.4.1
- 0.4.0
- 0.3.0
- 0.2.8
- 0.2.7
- 0.2.6
- 0.2.5
- 0.2.4
- 0.2.3
- 0.2.2
- 0.2.1
- 0.2.0
- 0.1.1
- dev-dependabot/composer/algolia/algoliasearch-client-php-tw-4.4.3
- dev-dependabot/composer/algolia/algoliasearch-client-php-tw-4.4.2
- dev-dependabot/npm_and_yarn/vite-5.4.6
- dev-develop-v5
- dev-master
- dev-develop
- dev-revert-304-patch-1
- dev-feature/multi-elementtypes
- dev-feature/site-search-index
- dev-craft3
- dev-97-multisite-single-index
- dev-override-batch-size
This package is auto-updated.
Last update: 2024-09-20 04:08:24 UTC
README
Craft Scout 为添加全文搜索到您的条目提供了一种简单解决方案。Scout 将自动将您的搜索索引与条目同步。
要求
此插件需要 Craft CMS 4.x 或更高版本以及 PHP 8.0.2 或更高版本。
安装
打开您的终端并转到您的 Craft 项目
# go to the project directory cd /path/to/my-craft-project.dev # tell Composer to install the plugin composer require studioespresso/craft-scout # tell Craft to install the plugin php craft plugin/install scout
设置
为了定义您的索引,将 scout.php 文件复制到您的 config
文件夹。
<?php return [ /* * Scout listens to numerous Element events to keep them updated in * their respective indices. You can disable these and update * your indices manually using the commands. */ 'sync' => true, /* * * @depcretio * By default Scout handles all indexing in a queued job, you can disable * this so the indices are updated as soon as the elements are updated * * Disabling the `queue` option will no longer be supported in the next version of Scout * */ 'queue' => true, /* * The connection timeout (in seconds), increase this only if necessary */ 'connect_timeout' => 1, /* * The batch size Scout uses when importing a large amount of elements */ 'batch_size' => 1000, /* * By default Scout will index elements related to the element being save (that are in the same index). * Disabling this can improve performance on larger sites that have lots of relations. */ 'indexRelations' => true, /** * The element types to look for when indexRelations is enabled. * By default, all Craft elements are checked for relations. * Use this to avoid unnecessary queries to Elements that aren't * used by your indices or to check custom Elements that may be * related to your indices */ 'relatedElementTypes' => [], /* * The Algolia Application ID, this id can be found in your Algolia Account * https://www.algolia.com/api-keys. This id is used to update records. */ 'application_id' => '$ALGOLIA_APPLICATION_ID', /* * The Algolia Admin API key, this key can be found in your Algolia Account * https://www.algolia.com/api-keys. This key is used to update records. */ 'admin_api_key' => '$ALGOLIA_ADMIN_API_KEY', /* * The Algolia search API key, this key can be found in your Algolia Account * https://www.algolia.com/api-keys. This search key is not used in Scout * but can be used through the Scout variable in your template files. */ 'search_api_key' => '$ALGOLIA_SEARCH_API_KEY', //optional /* * A collection of indices that Scout should sync to, these can be configured * by using the \rias\scout\ScoutIndex::create('IndexName') command. Each * index should define an ElementType, criteria and a transformer. */ 'indices' => [], ];
索引配置示例
<?php return [ 'indices' => [ \rias\scout\ScoutIndex::create('Blog') // Scout uses this by default, so this is optional ->elementType(\craft\elements\Entry::class) // If you don't define a siteId, the primary site is used ->criteria(function (\craft\elements\db\EntryQuery $query) { return $query->section('blog'); }) /* * The element gets passed into the transform function, you can omit this * and Scout will use the \rias\scout\ElementTransformer class instead */ ->transformer(function (\craft\elements\Entry $entry) { return [ 'title' => $entry->title, 'body' => $entry->body, ]; }) /* * You can use this to define index settings that get synced when you call * the ./craft scout/settings/update console command. This way you can * keep your index settings in source control. The IndexSettings * object provides autocompletion for all Algolia's settings */ ->indexSettings( \rias\scout\IndexSettings::create() ->minWordSizefor1Typo(4) ) ], ];
->elementType(string $class)
此索引包含的元素类型,默认情况下 Scout 使用 craft\elements\Entry::class
Craft 的默认元素类型类包括
craft\elements\Asset
craft\elements\Entry
craft\elements\User
->criteria(callable $query)
此函数接受一个 ElementQuery
并应返回一个 ElementQuery
->criteria(function (ElementQuery $query) { return $query->section('blog'); });
->transformer(callable|string|array|TransformerAbstract $transformer)
用于将数据发送到 Algolia 的每个元素的 转换器。如果您不设置此,则将使用默认转换器,它包括元素的直接属性值,但不包括自定义字段值。
// Can be set to a function ->transformer(function(craft\elements\Entry $entry) { return [ 'title' => $entry->title, 'id' => $entry->id, 'url' => $entry->url, ]; }), // Or a string/array that defines a Transformer class configuration ->transformer('MyTransformerClassName'), // Or a Transformer class instance ->transformer(new MyTransformerClassName()),
您的自定义转换器类可能看起来像这样
<?php use craft\elements\Entry; use League\Fractal\TransformerAbstract; class MyTransformerClassName extends TransformerAbstract { public function transform(Entry $entry) { return [ // ... ]; } }
->splitElementsOn(array $keys)
对于长文档,建议将元素分割成多行以保持每行数据大小。这可以通过使用 splitElementsOn()
完成。
请确保为这些键返回一个数组。
->splitElementsOn([ 'summary', 'matrixFieldHandle' ])
重要 -
distinctID
(在索引后可用)必须设置为用于分面的属性,以便在使用 splitElementsOn 时删除对象时正常工作。
->indexSettings(IndexSettings $settings)
您可以使用此命令定义索引设置,这些设置在您调用 ./craft scout/settings/update
控制台命令时同步。这样,您可以将索引设置保持在源代码控制中。IndexSettings 对象提供了 Algolia 所有设置的自动完成功能
注意
请注意,设置不会自动同步,只有当运行 ./craft scout/settings/update
控制台命令时才会同步。
->indexSettings( \rias\scout\IndexSettings::create() ->minWordSizefor1Typo(4) )
副本
您可以使用 IndexSettings
上的 replicas
函数创建副本。要配置副本,请将它们包含在 indices
数组中,并将它们的 replicaIndex
设置为 true
以确保它们不包含在任何同步操作中。
可以使用 ./craft scout/settings/update
控制台命令更新副本索引的配置。
<?php return [ 'indices' => [ \rias\scout\ScoutIndex::create('Products') // ... ->indexSettings( \rias\scout\IndexSettings::create() ->minWordSizefor1Typo(4) ->replicas(['virtual(Products_desc)']) ) ], [ \rias\scout\ScoutIndex::create('Products_desc') ->replicaIndex(true) ->indexSettings(IndexSettings::create()->customRanking(['desc(price)'])), ], ];
Twig 变量
您可以通过以下 Twig 变量访问您在配置文件中设置的 Algolia 设置。
{{ craft.scout.pluginName }} {{ craft.scout.algoliaApplicationId }} {{ craft.scout.algoliaAdminApiKey }} {{ craft.scout.algoliaSearchApiKey }}
控制台命令
Scout 提供了两个简单的控制台命令来管理您的索引。
导入
要导入一个或所有索引,您可以运行以下控制台命令
./craft scout/index/import <indexName?>
indexName
参数不是必需的,当你省略它时,所有映射都会被导入。
刷新/清除
清除索引就像在控制台运行一个命令一样简单。
./craft scout/index/flush <indexName?>
与导入命令一样,indexName
不是必需的。
在刷新时,Scout 会询问你是否真的想要清除索引中的所有数据。你可以通过添加一个 --force
标志来跳过确认。
刷新
先清除/清除,然后再重新导入索引。
./craft scout/index/refresh <indexName?>
跳过元素
你可以通过从 transform
方法返回一个 空数组 来省略一个元素被索引。
ScoutIndex::create() ->transform(function (Entry $entry) { // Check if entry is valid for indexing $isValid = yourCustomValidation($entry); // If entry fails validation, return empty array if (! $isValid) { return []; } // Return normal data attributes return [ 'name' => $entry->title, ... 'lorem' => $entry->lorem, 'ipsum' => $entry->ipsum, ]; });
事件
ShouldBeSearchableEvent
此事件允许你自定义在保存时检查哪些元素或元素类型(或者更具体地说,每次触发 SearchableBehaviour
时)。
use rias\scout\behaviors\SearchableBehavior; use rias\scout\events\ShouldBeSearchableEvent; Event::on( SearchableBehavior::class, SearchableBehavior::EVENT_SHOULD_BE_SEARCHABLE, function (ShouldBeSearchableEvent $event) { $event->shouldBeSearchable = false; });
事件有以下属性
- $element(正在保存的元素)
- $shouldBeSearchable(元素是否应该可搜索,默认为
true
)
此用例的一个例子是检查正在保存的元素的类型,并在它是一个 Matrix 块时将 shouldBeSearchable
设置为 false
。
AfterIndexImport
此事件在 ImportIndex
作业结束时运行,当每个项目都已被处理。
use rias\scout\events\AfterIndexImport; use rias\scout\jobs\ImportIndex; Event::on( ImportIndex::class, ImportIndex::EVENT_AFTER_INDEX_IMPORT, function (AfterIndexImport $event) { // Your code here });
事件有一个属性
- $indexName(刚刚完成导入的索引名称)
此用例的一个例子是如果你按计划运行导入,则记录日志或日期LastImported。
从 1.x 升级
配置与 Scout v1 的配置方式有所不同。请参阅下面的 设置 部分,了解如何配置 Scout。
以下更改是最显著的
- 将
mappings
配置键更改为indices
,并且有新的方式来配置索引 - 现在
criteria
是一个返回ElementQuery
的可调用对象。每个索引都应该在标准中定义一个siteId
,否则将选择主站点。 - 在设置中添加了新的
queue
和batch
选项 - 映射上的旧配置键已被
rias\scout\ScoutIndex
对象上的函数替换
由 Studio Espresso 和 Rias 提供