PHPackages                             wilr/silverstripe-algolia - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. wilr/silverstripe-algolia

ActiveSilverstripe-vendormodule[Search &amp; Filtering](/categories/search)

wilr/silverstripe-algolia
=========================

Algolia Indexer and Search Functionality

2.0.4(3mo ago)1325.5k↓18.2%20[4 issues](https://github.com/wilr/silverstripe-algolia/issues)[1 PRs](https://github.com/wilr/silverstripe-algolia/pulls)BSD-3-ClausePHPPHP ^8CI passing

Since Apr 1Pushed 3mo ago5 watchersCompare

[ Source](https://github.com/wilr/silverstripe-algolia)[ Packagist](https://packagist.org/packages/wilr/silverstripe-algolia)[ RSS](/packages/wilr-silverstripe-algolia/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (55)Used By (0)

🔍 Silverstripe Algolia Module
=============================

[](#mag-silverstripe-algolia-module)

[![codecov](https://camo.githubusercontent.com/27c1de01b1400c2de4ee8fc944b4e7e16e2f2b26500e5509e90f99e7b8da5559/68747470733a2f2f636f6465636f762e696f2f67682f77696c722f73696c7665727374726970652d616c676f6c69612f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/wilr/silverstripe-algolia)[![Version](https://camo.githubusercontent.com/7653d9133d08be77749cd91fbc1b04771464c637ad5317884fbd01eab4e51ca1/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f77696c722f73696c7665727374726970652d616c676f6c69612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/wilr/silverstripe-algolia)[![License](https://camo.githubusercontent.com/fa1a5ed912903c4142ccfc1eaca3eafe40cbba2100042207f67b33f516ad2b84/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f77696c722f73696c7665727374726970652d616c676f6c69612e7376673f7374796c653d666c61742d737175617265)](LICENSE)

Maintainer Contact
------------------

[](#maintainer-contact)

- Will Rossiter (@wilr)

Installation
------------

[](#installation)

```
composer require "wilr/silverstripe-algolia"
```

Features
--------

[](#features)

☑️ Supports multiple indexes and saving records into multiple indexes.

☑️ Integrates into existing versioned workflow.

☑️ No dependencies on the CMS, supports any DataObject subclass.

☑️ Queued job support for offloading operations to Algolia.

☑️ Easily configure search configuration and indexes via YAML and PHP.

☑️ Indexes your webpage template so supports Elemental and custom fields out of the box

Documentation
-------------

[](#documentation)

Algolia’s search-as-a-service and full suite of APIs allow teams to easily develop tailored, fast Search and Discovery experiences that delight and convert.

This module adds the ability to sync Silverstripe pages to a Algolia Index.

Indexing and removing documents is done transparently for any objects which subclass `SiteTree` or by applying the `Wilr\SilverStripe\Algolia\Extensions\AlgoliaObjectExtension` to your DataObjects.

🛠️ Setting Up
-------------

[](#hammer_and_wrench-setting-up)

First, sign up for Algolia.com account and install this module. Once installed, Configure the API keys via YAML (environment variables recommended).

*app/\_config/algolia.yml*

```
---
Name: algolia
After: silverstripe-algolia
---
SilverStripe\Core\Injector\Injector:
    Wilr\SilverStripe\Algolia\Service\AlgoliaService:
        properties:
            adminApiKey: "`ALGOLIA_ADMIN_API_KEY`"
            searchApiKey: "`ALGOLIA_SEARCH_API_KEY`"
            applicationId: "`ALGOLIA_SEARCH_APP_ID`"
            indexes:
                IndexName:
                    includeClasses:
                        - SilverStripe\CMS\Model\SiteTree
                    indexSettings:
                        attributesForFaceting:
                            - "filterOnly(objectClassName)"
```

Once the indexes and API keys are configured, run a `dev/build` to update the database and refresh the indexSettings. Alternatively you can run `AlgoliaConfigure` to manually rebuild the indexSettings.

### Configuring the index names

[](#configuring-the-index-names)

This module will assume your indexes are setup as `dev_{IndexName}`, `test_{IndexName}` and `live_{IndexName}` where the result of your environment type is prefixed to the names listed in the main YAML config.

If you explictly want to disable the environment prefix (or use a custom approach) use the `ALGOLIA_PREFIX_INDEX_NAME` environment variable.

```
ALGOLIA_PREFIX_INDEX_NAME='dev_will'
```

Or for testing with live data on dev use `ALGOLIA_PREFIX_INDEX_NAME='live'`

### Defining Replica Indexes

[](#defining-replica-indexes)

If your search form provides a sort option (e.g latest or relevance) then you will be using replica indexes ()

These can be defined using the same YAML configuration.

```
---
Name: algolia
After: silverstripe-algolia
---
SilverStripe\Core\Injector\Injector:
    Wilr\SilverStripe\Algolia\Service\AlgoliaService:
        properties:
            adminApiKey: "`ALGOLIA_ADMIN_API_KEY`"
            searchApiKey: "`ALGOLIA_SEARCH_API_KEY`"
            applicationId: "`ALGOLIA_SEARCH_APP_ID`"
            indexes:
                IndexName:
                    includeClasses:
                        - SilverStripe\CMS\Model\SiteTree
                    indexSettings:
                        attributesForFaceting:
                            - "filterOnly(ObjectClassName)"
                        replicas:
                            - IndexName_Latest
                IndexName_Latest:
                    indexSettings:
                        ranking:
                            - "desc(objectCreated)"
                            - "typo"
                            - "words"
                            - "filters"
                            - "proximity"
                            - "attribute"
                            - "exact"
                            - "custom"
```

Indexing
--------

[](#indexing)

If installing on a existing website run the `AlgoliaReindex` task (via CLI) to import existing data. This will batch import all the records from your database into the indexes configured above.

```
./vendor/bin/sake algolia-configure
./vendor/bin/sake algolia-index
```

Individually records will be indexed automatically going forward via the `onAfterPublish` hook and removed via the `onAfterUnpublish` hook which is called when publishing or unpublishing a document. If your DataObject does not implement the `Versioned` extension you'll need to manage this state yourself by calling `$item->indexInAlgolia()` and `$item->removeFromAlgolia()`.

`AlgoliaReindex` takes a number of arguments to allow for customisation of bulk indexing. For instance, if you have a large amount of JobVacancies to bulk import but only need the active ones you can trigger the task as follows:

```
/vendor/bin/sake algolia-index --onlyClass="onlyClass=Vacancy" --filter="ExpiryDate>NOW()"
```

If you do not have access to a CLI (i.e Silverstripe Cloud) then you can also bulk reindex via a queued job `AlgoliaReindexAllJob`.

### Optional

[](#optional)

`force` forces every Silverstripe record to be re-synced.

```
./vendor/bin/sake algolia-index --force
```

`clear` truncates the search index before re-indexing.

```
./vendor/bin/sake algolia-index --clear
```

### Customising the indexed attributes (fields)

[](#customising-the-indexed-attributes-fields)

By default only `ID`, `Title` and `Link`, `LastEdited` will be indexed from each record. To specify additional fields, define a `algolia_index_fields` config variable.

```
class MyPage extends Page {
    // ..
    private static $algolia_index_fields = [
        'Content',
        'MyCustomColumn',
        'RelationshipName'
    ];
}
```

Or, you can define a `exportObjectToAlgolia` method on your object. This receives the default index fields and then allows you to add or remove fields as required

```
use SilverStripe\Model\List\ArrayList;
use SilverStripe\Model\List\Map;

class MyPage extends Page {

    public function exportObjectToAlgolia($data)
    {
        $data = array_merge($data, [
            'MyCustomField' => $this->MyCustomField()
        ]);

        $map = new Map(ArrayList::create());

        foreach ($data as $k => $v) {
            $map->push($k, $v);
        }

        return $map;
    }
}
```

### Customizing the indexed relationships

[](#customizing-the-indexed-relationships)

Out of the box, the default is to push the ID and Title fields of any relationships (`$has_one`, `$has_many`, `$many_many`) into a field `relation{name}` with the record `ID` and `Title` as per the behaviour with records.

Additional fields from the relationship can be indexed via a PHP function

```
public function updateAlgoliaRelationshipAttributes(\SilverStripe\ORM\Map $attributes, $related)
{
    $attributes->push('CategoryName', $related->CategoryName);
}
```

### Excluding an object from indexing

[](#excluding-an-object-from-indexing)

Objects can define a `canIndexInAlgolia` method which should return false if the object should not be indexed in algolia.

```
public function canIndexInAlgolia(): bool
{
    return ($this->Expired) ? false : true;
}
```

### Queued Indexing

[](#queued-indexing)

To reduce the impact of waiting on a third-party service while publishing changes, this module utilizes the `queued-jobs` module for uploading index operations. The queuing feature can be disabled via the Config YAML.

```
Wilr\SilverStripe\Algolia\Extensions\AlgoliaObjectExtension:
    use_queued_indexing: false
```

Displaying and fetching results
-------------------------------

[](#displaying-and-fetching-results)

For your website front-end you can use InstantSearch.js libraries if you wish, or to fetch a `PaginatedList` of results from Algolia, create a method on your `Controller` subclass to call `Wilr\SilverStripe\Algolia\Service\AlgoliaQuerier`

```
