2017 © Pedro PelĂĄez
 

craft-plugin craft-scout

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

image

rias/craft-scout

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  • Monday, July 30, 2018
  • by Rias500
  • Repository
  • 1 Watchers
  • 33 Stars
  • 784 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 4 Forks
  • 3 Open issues
  • 18 Versions
  • 60 % Grown

The README.md

Scout for Craft CMS

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indices in sync with your entries., (*1)

Requirements

This plugin requires Craft CMS 4.x or later and PHP 8.0.2 or later., (*2)

Installation

Open your terminal and go to your Craft project:, (*3)

# 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

Setup

To define your indices, copy the scout.php file to your config folder., (*4)

 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'       => [],
];
```

### Example Index Configuration

```php
 [
        \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)`
The element type that this index contains, by default Scout uses `craft\elements\Entry::class`

Craft's default element type classes are:

- `craft\elements\Asset`
- `craft\elements\Category`
- `craft\elements\Entry`
- `craft\elements\GlobalSet`
- `craft\elements\MatrixBlock`
- `craft\elements\Tag`
- `craft\elements\User`

#### `->criteria(callable $query)`
This function accepts an `ElementQuery` and should also return an `ElementQuery`

```php
->criteria(function (ElementQuery $query) {
    return $query->section('blog');
});
```

---

#### `->getElements(callable $queries)`
This function can be used to query multiple different Element types. It should return an array of ElementQuery objects.

```php
->getElements(function () {
    return [
        Entry::find()->section('blog'),
        Category::find()->group('blogCategories'),
    ];
});
```

*Note:* When `->getElements()` is used, `->criteria()` and `->elementType()` are ignored. Combining elementTypes also changes the `->transformer()` function - that should be addapted to use `\craft\base\Element $element` as an argument:

```php
->transformer(function (\craft\base\Element $element) {
    return [
        'title' => $element->title
    ];
})
```


----
#### `->transformer(callable|string|array|TransformerAbstract $transformer)`
The [transformer](http://fractal.thephpleague.com/transformers/) that should be used to define the data that should be sent to Algolia for each element. If you don’t set this, the default transformer will be used, which includes all of the element’s direct attribute values, but no custom field values.

```php
// 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()),

```
Your custom transformer class would look something like this:
```php
splitElementsOn(array $keys)`
[For long documents](https://www.algolia.com/doc/guides/sending-and-managing-data/prepare-your-data/how-to/indexing-long-documents/) it is advised to divide the element into multiple rows to keep each row within row data size. This can be done using `splitElementsOn()`.
> Make sure to return an array in your transformer for these keys.

```php
->splitElementsOn([
    'summary',
    'matrixElement'
])
```

> *Important* - `distinctID` (available after indexing) must be set up as an attribute for faceting for deletion of objects to work when using splitElementsOn.

#### `->indexSettings(IndexSettings $settings)`

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

> [!NOTE]  
> Note that settings are not synced automatically, but only when the `./craft scout/settings/update` console command is run.

```php
->indexSettings(
    \rias\scout\IndexSettings::create()
        ->minWordSizefor1Typo(4)
)
```

### Replicas

Replicas can be created with the `replicas` function on `IndexSettings`. To configure replicas, include them in the `indices` array and set their `replicaIndex` to `true` so that they are not included in any syncing operations.

Replica indices can have their configuration updated using the `./craft scout/settings/update` console command.

```php
 [
        \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 variables
You can access the Algolia settings set in your config file through the following Twig variables.

```twig
{{ craft.scout.pluginName }}
{{ craft.scout.algoliaApplicationId }}
{{ craft.scout.algoliaAdminApiKey }}
{{ craft.scout.algoliaSearchApiKey }}
```

## Console commands
Scout provides two easy console commands for managing your indices.

### Importing
To import one or all indices you can run the following console command

```
./craft scout/index/import 

The indexName argument is not required, all your mappings will be imported when you omit it., (*5)

Flushing/Clearing

Clearing an index is as easy as running a command in your console., (*6)

./craft scout/index/flush <indexName?>

As with the import command, indexName is not required., (*7)

When flushing, Scout will ask you to confirm that you really want to clear all the data in your index. You can bypass the confirmation by appending a --force flag., (*8)

Refreshing

Does a flush/clear first and then imports the index again., (*9)

./craft scout/index/refresh <indexName?>

Skipping an Element

You can omit an element from being indexed by returning an empty array from the transform method:, (*10)

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,
        ];
    });

Events

ShouldBeSearchableEvent

This event allows you to customize which elements or element types get checked on save (or more specifically, every time the SearchableBehaviour is triggered)., (*11)


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; });

The event has a properties: - $element (the element being saved) - $shouldBeSearchable (wether or not the element should be searchable, defaults to true), (*12)

An example use-case for this would be to check the type of the element that's beind saved and settings shouldBeSearchable to false when it's a Matrix block., (*13)

AfterIndexImport

This event runs at the end of the ImportIndex job, when every item has been processed., (*14)


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 });

The event has one property: - $indexName (the name of the index that just finished importing, (*15)

An example use-case for this would be to keep a log or dateLastImported if you're running imports on a schedule., (*16)


Upgrading from 1.x

The configuration has changed from how Scout v1 did its configuration. Please see the setup section below on how to configure Scout., (*17)

The following changes are the most notable: - The mappings configuration key has been changed to indices and there is a new way to configure the indices - The criteria is now a callable that returns an ElementQuery. Every Index should define a siteId in the criteria, otherwise the primary site is chosen. - New queue and batch options added to the settings - Old confuguration keys on the mappings have been replaced by functions on the rias\scout\ScoutIndex object., (*18)


Brought to you by Studio Espresso and Rias, (*19)

The Versions

30/07 2018

dev-master

9999999-dev

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

01/05 2018

0.4.1

0.4.1.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

01/05 2018

dev-analysis-876jZ3

dev-analysis-876jZ3

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

17/04 2018

0.4.0

0.4.0.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

12/03 2018

0.3.0

0.3.0.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

28/02 2018

0.2.8

0.2.8.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

28/02 2018

dev-analysis-86Dr79

dev-analysis-86Dr79

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

27/02 2018

0.2.7

0.2.7.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

15/01 2018

dev-analysis-XWJjmV

dev-analysis-XWJjmV

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

15/01 2018

0.2.6

0.2.6.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

15/01 2018

dev-analysis-XZ49v6

dev-analysis-XZ49v6

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

15/01 2018

0.2.5

0.2.5.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

14/01 2018

0.2.4

0.2.4.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

08/01 2018

0.2.3

0.2.3.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

08/01 2018

0.2.2

0.2.2.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

12/12 2017

0.2.1

0.2.1.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

12/12 2017

0.2.0

0.2.0.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft

12/12 2017

0.1.1

0.1.1.0

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.

  Sources   Download

MIT

The Requires

 

cms scout craftcms craft-plugin craft