codemix/yiielasticsearch

Yii的Elastic Search客户端

1.0.4 2016-07-06 07:05 UTC

This package is auto-updated.

Last update: 2024-08-24 04:13:02 UTC


README

Yii的Elastic Search客户端。

安装

通过composer安装,需要php >= 5.3

配置

将以下内容添加到您的应用程序配置中

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

同时确保包含composer的自动加载器。我们建议将此行添加到您的index.php文件中,也许也添加到yiic.php文件中

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

确保修改路径以匹配您的vendor/目录的位置。

使用

索引您的ActiveRecords

YiiElasticSearch\SearchableBehavior附加到任何ActiveRecords上,以便轻松使用Elasticsearch索引和搜索您的常规模型。

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

现在,当MyModel实例保存或删除时,它们将在Elasticsearch中自动索引或删除。

为记录定义索引

默认情况下,您的记录将存储在名为您的清理应用程序名称(Yii::app()->name)的索引中。要更改它,您可以定义

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

或者,如果您需要更多控制,可以创建一个方法

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

为记录定义类型

默认情况下,将使用小写类名作为Elasticsearch中的类型名称。如果您想更改它,可以定义

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

或者,如果需要更多控制,可以创建一个方法

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

自定义索引数据

默认情况下,所有属性都存储在索引中。如果您需要自定义应索引到Elasticsearch中的数据,可以覆盖这两个方法。

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

查询记录

您可以使用YiiElasticSearch\Search对象指定查询。该对象为原始Elasticsearch 搜索API提供了一个简单的OO包装器。

例如

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

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

使用搜索,您可以执行一个'raw'查询,例如

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

这将返回一个结果集,该结果集是原始Elasticsearch响应的一个非常简单的包装器。

或者,当与SearchableBehavior结合使用时,您可以使用数据提供程序,例如

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

$dataProvider->data中的数据是ActiveRecords的列表,就像来自普通的CActiveDataProvider一样。因此,您可以在任何列表或网格视图中使用它。

原始请求

您还可以使用连接组件向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.php配置中

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

这将允许您在控制台中使用yiic elasticyiic zerodowntimeelastic。以下是对这些命令的帮助信息

控制台命令

这是Elasticsearch组件的维护命令。

ACTIONS

  index --model=<model> [--skipExisting]

    Add all models <model> 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=<model> --map=<filename> [--skipExisting]
  map --index=<index> --map=<filename> [--skipExisting]

    Create a mapping in the index specified with the <index> or implicitly
    through the <model> parameter. The mapping must be available from a JSON
    file in <filename> 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=<name>] [--limit=10] [--offset=0]
  list [--index=<name>] [--type=<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=<name> [--id=<id>]

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

  help

    Show this help

零停机命令

这是Elasticsearch组件的零停机维护命令。更多详情:https://elastic.ac.cn/blog/changing-mapping-with-zero-downtime

ACTIONS

  * index --models=<model1>,...
    Add all models to the index.

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

  * schema --models=<model1>,...
        [--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 <forceMigrate> is true
     3, bulk copy the previous data if <bulkCopy> is true
     4, update aliases if <updateAlias> is true
     5, delete indexes if <deleteIndexes> 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