Home

Awesome

Elasticsearch Behavior for Yii 2

Latest Stable Version Total Downloads Latest Unstable Version License

Yii2 AR behavior to support Elasticsearch auto-indexing.

image

Installation

The preferred way to install this extension is through composer.

Either run

$ php composer.phar require "borales/yii2-elasticsearch-behavior" "*"

or add

"borales/yii2-elasticsearch-behavior": "*"

to the require section of your composer.json file.

Configuring

Configure model as follows (for "command" mode):

class Post extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            ...
            'elasticsearch' => [
                'class' => \borales\behaviors\elasticsearch\Behavior::className(),
                'mode' => 'command',
                'elasticIndex' => 'project-index',
                'elasticType' => 'posts',
                'dataMap' => [
                    'id' => 'id',
                    'title' => 'name',
                    'body' => function() {
                        return strip_tags($this->body);
                    },
                    'date_publish' => function() {
                        return date('U', strtotime($this->date_create));
                    },
                    'author' => function() {
                        return ucfirst($this->author->name);
                    }
                ]
            ],
        ];
    }
    
    ...
}

Configuration values of the behavior:

Example of using "model" mode

class Post extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            ...
            'elasticsearch' => [
                'class' => \borales\behaviors\elasticsearch\Behavior::className(),
                'mode' => 'model',
                'elasticClass' => \common\models\elastic\PostElastic::className(),
                'dataMap' => [
                    'id' => 'id',
                    'title' => 'name',
                    'body' => function() {
                        return strip_tags($this->body);
                    },
                    'date_publish' => function() {
                        return date('U', strtotime($this->date_create));
                    },
                    'author' => function() {
                        return ucfirst($this->author->name);
                    }
                ]
            ],
        ];
    }
    
    ...
}

...

class PostElastic extends \yii\elasticsearch\ActiveRecord
{
    /**
     * @return array the list of attributes for this record
     */
    public function attributes()
    {
        // path mapping for '_id' is setup to field 'id'
        return ['id', 'title', 'body', 'date_publish', 'author'];
    }
}

More details and features about Elasticsearch ActiveRecord you will find here.