PHPackages                             codemix/yiielasticsearch - 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. [API Development](/categories/api)
4. /
5. codemix/yiielasticsearch

ActiveLibrary[API Development](/categories/api)

codemix/yiielasticsearch
========================

Elastic Search client for Yii

1.0.4(9y ago)3342.7k16[8 issues](https://github.com/codemix/YiiElasticSearch/issues)MITPHPPHP &gt;=5.3.0

Since Jul 23Pushed 9y ago12 watchersCompare

[ Source](https://github.com/codemix/YiiElasticSearch)[ Packagist](https://packagist.org/packages/codemix/yiielasticsearch)[ RSS](/packages/codemix-yiielasticsearch/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (2)Dependencies (1)Versions (8)Used By (0)

YiiElasticSearch
================

[](#yiielasticsearch)

Elastic Search client for Yii.

Installation
============

[](#installation)

Install via composer, requires php &gt;= 5.3

Configuration
=============

[](#configuration)

Add the following to your application config:

```
'components' => array(
    'elasticSearch' => array(
        'class' => 'YiiElasticSearch\Connection',
        'baseUrl' => 'http://localhost:9200/',
    ),
    ...
)
```

Also make sure, that you include the autoloader of composer. We recommend to add this line to your `index.php` and maybe also your `yiic.php`:

```
// Include composer autoloader
require_once(__DIR__.'/protected/vendor/autoload.php');
```

Make sure to modify the path so that it matches the location of your `vendor/`directory.

Usage
=====

[](#usage)

Index your ActiveRecords
------------------------

[](#index-your-activerecords)

Attach the `YiiElasticSearch\SearchableBehavior` to any of your ActiveRecords to make it easy to index and search your normal models with elasticsearch.

```
class MyModel extends CActiveRecord
{
    public function behaviors()
    {
        return array(
            'searchable' => array(
                'class' => 'YiiElasticSearch\SearchableBehavior',
            ),
        );
    }
}
```

Now when MyModel instances are saved or deleted they will be automatically indexed or deleted in elasticsearch as appropriate.

### Define an index for a record

[](#define-an-index-for-a-record)

By default your records will be stored in an index that uses your sanitized application name (`Yii::app()->name`). To change it you can define

```
class MyModel extends CActiveRecord
{
    public $elasticIndex = 'myindex';
```

or, if you need more control, create a method

```
class MyModel extends CActiveRecord
{
    public function getElasticIndex()
    {
        return 'myindex';
    }
```

### Define a type for a record

[](#define-a-type-for-a-record)

By default the lower case class name will be used as type name in elasticsearch. If you want to change that you can define

```
class MyModel extends CActiveRecord
{
    public $elasticType = 'mymodel';
```

or, again, if you need more control, create a method

```
class MyModel extends CActiveRecord
{
    public function getElasticType()
    {
        return 'mymodel';
    }
```

### Customize indexed data

[](#customize-indexed-data)

By default all attributes are stored in the index. If you need to customize the data that should be indexed in elasticsearch, you can override these two methods.

```
class MyModel extends CActiveRecord
{
    /**
     * @param DocumentInterface $document the document where the indexable data must be applied to.
     */
    public function populateElasticDocument(DocumentInterface $document)
    {
        $document->setId($this->id);
        $document->name     = $this->name;
        $document->street   = $this->street;
    }

    /**
     * @param DocumentInterface $document the document that is providing the data for this record.
     */
    public function parseElasticDocument(DocumentInterface $document)
    {
        // You should always set the match score from the result document
        if ($document instanceof SearchResult)
            $this->setElasticScore($document->getScore());

        $this->id       = $document->getId();
        $this->name     = $document->name;
        $this->street   = $document->stree;
    }
```

Query records
-------------

[](#query-records)

You can specify queries using the `YiiElasticSearch\Search` object. This object provides a simple OO wrapper for the vanilla elasticsearch [search API](http://www.elasticsearch.org/guide/reference/api/search/).

For example:

```
$search = new \YiiElasticSearch\Search("myindex", "mymodel");
$search->query = array(
    "match_all" => array()
);

// start returning results from the 20th onwards
$search->offset = 20;
```

With a search you can either perform a 'raw' query, e.g.

```
$resultSet = Yii::app()->elasticSearch->search($search);
```

This will return a result set that is a very simple wrapper around the raw elastic search response.

Alternatively, when combined with a `SearchableBehavior` you can use data providers, e.g.

```
$dataProvider = new \YiiElasticSearch\DataProvider(MyModel::model(), array(
        'search' => $search
));
```

The data from `$dataProvider->data` is a list of ActiveRecords, just like from an ordinary `CActiveDataProvider`. So you can use it in any list or grid view.

Raw requests
------------

[](#raw-requests)

You can also use the connection component to send raw requests to elasticsearch.

```
// Will be an instance of a Guzzle\Http\Client
$client = Yii::app()->elasticSearch->client;

$mapping = array(
   'country' => array(
        'properties' => array(
            'name' => array(
                'type' => 'string',
            ),
        ),
    ),

// Create a mapping
$request = $client->put('myindex', array("Content-type" => "application/json"));
$request->setBody(array('mapping' => $mapping));

$response = $request->send();

$result = $response->getBody();
```

Console Maintenance
-------------------

[](#console-maintenance)

The extension comes with two simple maintenance commands that can be helpful to find out what's going on in your index. To configure them, add this to your `console.php` configuration:

```
'commandMap' => array(
    'elastic' => array(
        'class' => 'YiiElasticSearch\ConsoleCommand',
    ),
    'zerodowntimeelastic' => array(
        'class' => 'YiiElasticSearch\ZeroDowntimeConsoleCommand',
    ),
),
```

This will allow you to use `yiic elastic` and `yiic zerodowntimeelastic` on the console. Here are the commands help:

### Console Command

[](#console-command)

This is the maintenance command for the elasticSearch component.

```
ACTIONS

  index --model= [--skipExisting]

    Add all models  to the index. This will replace any previous
    entries for this model in the index. Index and type will be auto-detected
    from the model class unless --index or --type is set explicitely.
    If --skipExisting is used, no action is performed if there are already
    documents indexed under this type.

  map --model= --map= [--skipExisting]
  map --index= --map= [--skipExisting]

    Create a mapping in the index specified with the  or implicitly
    through the  parameter. The mapping must be available from a JSON
    file in  where the JSON must have this form:

        {
            "tweet" : {
                "properties": {
                    "name" : {"type" : "string"},
                    ...
            },
            ...
        }

    If --skipExisting is used, no action is performed if there's are already
    a mapping for this index.

  list [--limit=10] [--offset=0]
  list [--model=] [--limit=10] [--offset=0]
  list [--index=] [--type=] [--limit=10] [--offset=0]

    List all entries in elasticsearch. If a model or an index (optionally with
    a type) is specified only entries matching index and type of the model will be listed.

  delete --model= [--id=]

    Delete a document from an index. If no  is specified the whole
    index will be deleted.

  help

    Show this help

```

### ZeroDowntime Command

[](#zerodowntime-command)

This is a zero downtime maintenance command for the elasticSearch component. More details:

```
ACTIONS

  * index --models=,...
    Add all models to the index.

  * status --models=,...
    Displays actual indexes and aliases

  * schema --models=,...
        [--version=201512121212] [--forceMigrate=false] [--bulkCopy=true] [--updateAlias=true] [--deleteIndexes=true]

    Creates schema for the given models. Steps:
     1, compare mapping
     2, if migration is needed, create the new schema version, always create new if  is true
     3, bulk copy the previous data if  is true
     4, update aliases if  is true
     5, delete indexes if  is true

  * bulkCopy --from=index/type --to=index2/type [--properties=]
    Bulk copy all data

  * changeAlias --from=value --to=value [--old=]
    Change alias

  * deleteIndex --indexesToDelete=value
    Delete index with all types

  help

    Show this help

```

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance15

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 55.6% 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 ~163 days

Total

5

Last Release

3604d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3acf6b979253030380f45271ce4efc9d5f3a207a96fafe6c92da41876ae33b24?d=identicon)[codemix](/maintainers/codemix)

---

Top Contributors

[![mikehaertl](https://avatars.githubusercontent.com/u/675062?v=4)](https://github.com/mikehaertl "mikehaertl (40 commits)")[![phpnode](https://avatars.githubusercontent.com/u/363611?v=4)](https://github.com/phpnode "phpnode (21 commits)")[![burci](https://avatars.githubusercontent.com/u/864531?v=4)](https://github.com/burci "burci (6 commits)")[![Maxsh](https://avatars.githubusercontent.com/u/630001?v=4)](https://github.com/Maxsh "Maxsh (3 commits)")[![bartaakos](https://avatars.githubusercontent.com/u/5137447?v=4)](https://github.com/bartaakos "bartaakos (1 commits)")[![schmunk42](https://avatars.githubusercontent.com/u/649031?v=4)](https://github.com/schmunk42 "schmunk42 (1 commits)")

### Embed Badge

![Health badge](/badges/codemix-yiielasticsearch/health.svg)

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

###  Alternatives

[rackspace/php-opencloud

PHP SDK for Rackspace/OpenStack APIs

4495.9M38](/packages/rackspace-php-opencloud)[cdaguerre/php-trello-api

Trello API v2 client

255666.7k3](/packages/cdaguerre-php-trello-api)[dchesterton/marketo-rest-api

A PHP client for the Marketo.com REST API

41844.1k1](/packages/dchesterton-marketo-rest-api)[carlosio/geckoboard

A PHP library for dealing with Geckoboard API (http://www.geckoboard.com)

40172.2k](/packages/carlosio-geckoboard)[teepluss/api

Laravel 4 Internal Request (HMVC)

7034.0k](/packages/teepluss-api)[jlinn/mandrill-api-php

A PHP client library for Mandrill's REST API

24117.4k](/packages/jlinn-mandrill-api-php)

PHPackages © 2026

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