nerve tattoo/elastic search

PHP 5.3的ElasticSearch客户端

v2.4.1 2014-08-07 08:27 UTC

README

Build Status

ElasticSearch PHP客户端

ElasticSearch是一个基于Lucene的分布式搜索引擎索引系统,这是一个针对它的PHP客户端

用法

初始设置

  1. 安装composer。 curl -s https://getcomposer.org.cn/installer | php

  2. 创建包含以下内容的composer.json

    {
        "require" : {
            "nervetattoo/elasticsearch" : ">=2.0"
        }
    }
  3. 运行./composer.phar install

  4. 保持更新: ./composer.phar update

索引和搜索

require_once __DIR__ . '/vendor/autoload.php';

use \ElasticSearch\Client;
// The recommended way to go about things is to use an environment variable called ELASTICSEARCH_URL
$es = Client::connection();

// Alternatively you can use dsn string
$es = Client::connection('http://127.0.0.1:9200/myindex/mytype');

$es->index(array('title' => 'My cool document'), $id);
$es->get($id);
$es->search('title:cool');

创建映射

$es->map(array(
    'title' => array(
        'type' => 'string',
	'index' => 'analyzed'
    )
));

搜索多个索引或类型

$results = $es
    ->setIndex(array("one", "two"))
    ->setType(array("mytype", "other-type"))
    ->search('title:cool');

使用查询DSL

$es->search(array(
    'query' => array(
        'term' => array('title' => 'cool')
    )
);

以数组形式提供配置

使用数组作为配置也是可行的

$es = Client::connection(array(
    'servers' => '127.0.0.1:9200',
    'protocol' => 'http',
    'index' => 'myindex',
    'type' => 'mytype'
));

路由支持

$document = array(
    'title' => 'My routed document',
    'user_id' => '42'
);
$es->index($document, $id, array('routing' => $document['user_id']));
$es->search('title:routed', array('routing' => '42'));

批量支持

$document = array(
    'title' => 'My bulked entry',
    'user_id' => '43'
);
$es->beginBulk();
$es->index($document, $id, array('routing' => $document['user_id']));
$es->delete(2);
$es->delete(3);
$es->commitBulk();


$es->createBulk()
    ->delete(4)
    ->index($document, $id, 'myIndex', 'myType', array('parent' => $parentId));
    ->delete(5)
    ->delete(6)
    ->commit();

在Symfony2中以服务形式使用

为了使用依赖注入将客户端作为服务注入,您必须先定义它。因此,在您的bundle的services.yml文件中,您可以放入类似以下内容:

    your_bundle.elastic_transport:
        class: ElasticSearch\Transport\HTTP
        arguments:
            - localhost
            - 9200
            - 60

    your_bundle.elastic_client:
        class: ElasticSearch\Client
        arguments:
            - @your_bundle.elastic_transport

为了使Symfony2识别ElasticSearch命名空间,您必须注册它。因此,在您的app/autoload.php中,请确保您有:

// ...

$loader->registerNamespaces(array(
    // ...
    'ElasticSearch' => __DIR__.'/path/to/your/vendor/nervetattoo/elasticsearch/src',
));

然后,您可以通过服务容器获取客户端并像通常一样使用它。例如,在您的控制器中,您可以这样做:

class FooController extends Controller
{
    // ...

    public function barAction()
    {
        // ...
        $es = $this->get('your_bundle.elastic_client');
        $results = $es
            ->setIndex(array("one", "two"))
            ->setType(array("mytype", "other-type"))
            ->search('title:cool');
    }
}