PHPackages                             spatie/searchindex - 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. spatie/searchindex

Abandoned → [This package has been abandoned. Please use laravel/scout instead.](/?search=This%20package%20has%20been%20abandoned.%20Please%20use%20laravel%2Fscout%20instead.)Library[Search &amp; Filtering](/categories/search)

spatie/searchindex
==================

Store and retrieve objects from Elasticsearch or Algolia

3.5.0(8y ago)44695.4k48MITPHPPHP &gt;=5.5.0

Since Jan 15Pushed 1mo ago20 watchersCompare

[ Source](https://github.com/spatie/searchindex)[ Packagist](https://packagist.org/packages/spatie/searchindex)[ Docs](https://github.com/spatie/searchindex)[ RSS](/packages/spatie-searchindex/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (5)Versions (17)Used By (0)

Store and retrieve objects from a search index
==============================================

[](#store-and-retrieve-objects-from-a-search-index)

[![Latest Version](https://camo.githubusercontent.com/b271a4783c2f4de95a9e126787f5ea09ed8851666a2c09b4acf5786129676855/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f7370617469652f736561726368696e6465782e7376673f7374796c653d666c61742d737175617265)](https://github.com/spatie/searchindex/releases)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build status](https://camo.githubusercontent.com/2df07ba1ba2c418ff2df482928e461323047a969dfba8557addac2829bd38542/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7370617469652f736561726368696e6465782e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/spatie/searchindex)[![Quality Score](https://camo.githubusercontent.com/5db3a2ff824fdabf7c1d8ba1715253353bdcd18c09ee68ef4698cc9bc8dd5dc5/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f736561726368696e6465782e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/searchindex)[![StyleCI](https://camo.githubusercontent.com/c3e0f884196a194c09d0a4b84a14f130e794654f0ecb545777c4ec2d725b8544/68747470733a2f2f7374796c6563692e696f2f7265706f732f32393330363936322f736869656c64)](https://styleci.io/repos/29306962)[![Total Downloads](https://camo.githubusercontent.com/606846dfd8fadd1dff69408de0b765f96e3906aba5241df700b0395ad62ba1fe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f736561726368696e6465782e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/searchindex)

This is an opinionated Laravel 5.1 package to store and retrieve objects from a search index. Currently [Elasticsearch](http://www.elasticsearch.org) and [Algolia](https://www.algolia.com) are supported.

Once the package is installed objects can be easily indexed and retrieved:

```
//$product is an object that implements the Searchable interface
SearchIndex::upsertToIndex($product);

SearchIndex::getResults('look for this');
```

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Support us
----------

[](#support-us)

Learn how to create a package like this one, by watching our premium video course:

[![Laravel Package training](https://camo.githubusercontent.com/4c7f3720a29525e627f6004ee367e55def510e45d18e6bc974725812fa5cf257/68747470733a2f2f7370617469652e62652f6769746875622f7061636b6167652d747261696e696e672e6a7067)](https://laravelpackage.training)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Postcardware
------------

[](#postcardware)

You're free to use this package (it's [MIT-licensed](LICENSE.md)), but if it makes it to your production environment you are required to send us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

The best postcards will get published on the open source page on our website.

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

[](#installation)

This package can be installed through Composer.

```
composer require spatie/searchindex
```

You must install this service provider.

```
// config/app.php
'providers' => [
    ...
    Spatie\SearchIndex\SearchIndexServiceProvider::class,
];
```

This package also comes with a facade, which provides an easy way to call the the class.

```
// config/app.php
'aliases' => [
	...
	'SearchIndex' => Spatie\SearchIndex\SearchIndexFacade::class,
]
```

You can publish the config-file with:

```
php artisan vendor:publish --provider="Spatie\SearchIndex\SearchIndexServiceProvider"
```

The options in the config file are set with sane default values and they should be self-explanatory.

The next installation steps depend on if you want to use Elasticsearch or Algolia.

### Elasticsearch

[](#elasticsearch)

To use Elasticsearch you must install the official 1.x series low level client:

```
composer require elasticsearch/elasticsearch "^1.3"
```

You also should have a server with Elasticsearch installed. If you want to install it on your local development machine you can use [these instructions](https://github.com/fideloper/Vaprobash/blob/master/scripts/elasticsearch.sh)from the excellent [Vaprobash repo](https://github.com/fideloper/Vaprobash).

### Algolia

[](#algolia)

To use Algolia you must install the official low level client:

```
composer require algolia/algoliasearch-client-php
```

Usage
-----

[](#usage)

### Prepare your object

[](#prepare-your-object)

Objects that you want to store in the index should implement the provided `Spatie\SearchIndex\Searchable`- interface.

```
namespace Spatie\SearchIndex;

interface Searchable {

    /**
     * Returns an array with properties which must be indexed
     *
     * @return array
     */
    public function getSearchableBody();

    /**
     * Return the type of the searchable subject
     *
     * @return string
     */
    public function getSearchableType();

    /**
     * Return the id of the searchable subject
     *
     * @return string
     */
    public function getSearchableId();
```

Here is an example how you could implement it with an Eloquent model:

```
class Product extends Eloquent implements Searchable
{

    ...

    /**
     * Returns an array with properties which must be indexed
     *
     * @return array
     */
    public function getSearchableBody()
    {
        $searchableProperties = [
            'name' => $this->name,
            'brand' => $this->brand->name,
            'category' => $this->category->name
        ];

        return $searchableProperties;

    }

    /**
     * Return the type of the searchable subject
     *
     * @return string
     */
    public function getSearchableType()
    {
        return 'product';
    }

    /**
     * Return the id of the searchable subject
     *
     * @return string
     */
    public function getSearchableId()
    {
        return $this->id;
    }
}
```

The searchindex will use the returned searchableType and searchableId to identify an object in the index.

### Add an object to the index

[](#add-an-object-to-the-index)

If you are using the facade it couldn't be simpler.

```
//$product is an object that implements the Searchable interface

SearchIndex::upsertToIndex($product);
```

### Update an object in the index

[](#update-an-object-in-the-index)

You probably would have guessed it.

```
//$product is an object that implements the Searchable interface

SearchIndex::upsertToIndex($product);
```

### Remove an object from the index

[](#remove-an-object-from-the-index)

Yep. Easy.

```
//$product is an object that implements the Searchable interface

SearchIndex::removeFromIndex($product);
```

Alternatively you can remove an object from the index by passing type and id:

```
SearchIndex::removeFromIndexByTypeAndId('product', 1);
```

This can be handy when you've already deleted your model.

### Clear the entire index

[](#clear-the-entire-index)

If only you could to this with your facebook account.

```
SearchIndex::clearIndex();
```

### Perform a search on the index

[](#perform-a-search-on-the-index)

You can retrieve search results with this method:

```
SearchIndex::getResults($query);
```

#### Elasticsearch

[](#elasticsearch-1)

`$query` should be an array that adheres to the scheme provided by [the elasticsearch documentation](http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_search_operations.html).

A query to perform a fuzzy like search that operates all fields of the index could look like this:

```
$query =
    [
        'body' =>
            [
                'from' => 0,
                'size' => 500,
                'query' =>
                    [
                        'fuzzy_like_this' =>
                            [
                                '_all' =>
                                    [
                                        'like_text' => 'look for this',
                                        'fuzziness' => 0.5,
                                    ],
                            ],
                    ],
            ]
    ];
```

The search results that come back are simply elasticsearch response elements serialized into an array. You can see [an example of a response](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-body.html)in the official elasticsearch documentation.

#### Algolia

[](#algolia-1)

You can just pass a string to search the index:

```
SearchIndex::getResults('look for this');
```

To perform more advanced queries an array may be passed. Read the [official documentation](https://github.com/algolia/algoliasearch-client-php#search) to learn what's possible.

### All other operations

[](#all-other-operations)

For all other operations you can get the underlying client:

```
SearchIndex::getClient(); // will return the Elasticsearch or Algolia client.
```

Query helpers
-------------

[](#query-helpers)

If you're using Algolia you can use a `SearchQuery`-object to perform searches.

```
use Spatie\SearchIndex\Query\Algolia\SearchIndex();

$searchQuery = new SearchQuery();
$searchQuery->searchFor('my query')
            ->withFacet('facetName', 'facetValue');

//a searchQuery object may be passed to the getResults-function directly.
SearchIndex::getResults($searchQuery);
```

Tests
-----

[](#tests)

This package comes with a set of unit tests. Every time the package gets updated [Travis CI](https://travis-ci.org) will automatically run them.

You can also run them manually. You'll have first run `composer install --dev` to install phpspec. After that's out of the way you can run the tests with `vendor/bin/phpspec run`.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

About Spatie
------------

[](#about-spatie)

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

###  Health Score

53

↑

FairBetter than 97% of packages

Maintenance59

Moderate activity, may be stable

Popularity47

Moderate usage in the ecosystem

Community27

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 83.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~76 days

Recently: every ~213 days

Total

15

Last Release

3015d ago

Major Versions

0.2 → 1.0.02015-02-16

1.0.0 → 2.0.02015-02-16

2.x-dev → 3.0.02015-08-04

PHP version history (2 changes)0.1PHP &gt;=5.4.0

3.0.0PHP &gt;=5.5.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (99 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![carusogabriel](https://avatars.githubusercontent.com/u/16328050?v=4)](https://github.com/carusogabriel "carusogabriel (1 commits)")[![dvlpp](https://avatars.githubusercontent.com/u/973325?v=4)](https://github.com/dvlpp "dvlpp (1 commits)")[![Garbee](https://avatars.githubusercontent.com/u/868301?v=4)](https://github.com/Garbee "Garbee (1 commits)")[![Jono20201](https://avatars.githubusercontent.com/u/2374192?v=4)](https://github.com/Jono20201 "Jono20201 (1 commits)")[![matthewbdaly](https://avatars.githubusercontent.com/u/450801?v=4)](https://github.com/matthewbdaly "matthewbdaly (1 commits)")[![MatthiasDeWinter](https://avatars.githubusercontent.com/u/8791525?v=4)](https://github.com/MatthiasDeWinter "MatthiasDeWinter (1 commits)")[![olefirenko](https://avatars.githubusercontent.com/u/5434459?v=4)](https://github.com/olefirenko "olefirenko (1 commits)")[![repat](https://avatars.githubusercontent.com/u/516807?v=4)](https://github.com/repat "repat (1 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (1 commits)")[![Tjoosten](https://avatars.githubusercontent.com/u/5157609?v=4)](https://github.com/Tjoosten "Tjoosten (1 commits)")[![WyriHaximus](https://avatars.githubusercontent.com/u/147145?v=4)](https://github.com/WyriHaximus "WyriHaximus (1 commits)")[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (1 commits)")

---

Tags

searchlaravelelasticsearchalgoliaindex

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/spatie-searchindex/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-searchindex/health.svg)](https://phpackages.com/packages/spatie-searchindex)
```

###  Alternatives

[algolia/scout-extended

Scout Extended extends Laravel Scout adding algolia-specific features

4166.2M5](/packages/algolia-scout-extended)[mmanos/laravel-search

A search package for Laravel 5.

35375.7k1](/packages/mmanos-laravel-search)[mailerlite/laravel-elasticsearch

An easy way to use the official PHP ElasticSearch client in your Laravel applications.

934507.9k2](/packages/mailerlite-laravel-elasticsearch)[jeroen-g/explorer

Next-gen Elasticsearch driver for Laravel Scout.

399590.5k](/packages/jeroen-g-explorer)[gtk/larasearch

A driver based solution to searching your Eloquent models supports Laravel 5.2 and Elasticsearch engine.

133.9k](/packages/gtk-larasearch)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
