PHP code example of php-module / elastic-php-based-official
1. Go to this page and download the library: Download php-module/elastic-php-based-official library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
php-module / elastic-php-based-official example snippets
use PhpES\EsClient\Client;
use PhpEs\EsClient\DSLBuilder;
$es = new Client();
/**
* matchType 可选项:
* phrase 短语匹配
* phrase_prefix 前缀匹配
* cross_fields(出现在越多的字段得分越高)
* best_fields(匹配度越高得分越高)
* most_fields(出现频率越高得分越高)
*/
$res = $es
->select(array('field', 'field2'))
->from('index')
->where('field', DSLBuilder::OPERATOR_EQ, 'value')
->whereGeo('geo_point', $lat, $lon, $distance, $minDistance, $unit, $distanceType, $type)
->orWhere('field', DSLBuilder::OPERATOR_NE, value8)
->andWhereBegin()
->orWhere('field', DSLBuilder::OPERATOR_EQ, value)
->orWhere('field', DSLBuilder::OPERATOR_NE, value)
->orWhere('field', DSLBuilder::OPERATOR_NE, value)
->match(要匹配的字段(单个字段或数组), "关键词", $matchType = 'phrase', $type = 'must')
->andWhereEnd()
->orderBy('field', 'value')
->offset($offset)
->limit($limit)
->debug() //if need
->search()
->getFormat();
$res = $es
->select(array('field', 'field2'))
->from('index')
->beginNested()
->setNested('parentField') // 标记嵌套文档聚合开始
->where('parentField.field', '!=', 0)
->dateHistogram('parentField.filed1', 'year', \PhpES\EsClient\DSLBuilder::AGG_HISTOGRAM_TYPE_CALENDAR, $child)
->endNested() // 标记嵌套文档结束
->groupBy('field') // 普通聚合 返回值中将自动拼接上 agg_字段名
->sum(field) // 获取参与聚合的文档数量 自动拼接 count_字段名
->cardinality('field') // 获取不重复的符合条件的总数 自动拼接 cardinality_字段名
->sum('field') // 获取sum
->search()
->getFormat();
# 继承Client, 重写getClient, 实例化Client时用: setHandler来设置链接数量
class classNmae extends Client{
/**
* @throws \Exception
*/
public function getClient()
{
if (empty($this->hosts)) {
throw new \Exception('using getClient , You must set host before');
}
if ($this->client == null) {
$this->client = self::create()
->setHosts($this->hosts)
->setHandler(new CurlHandler(['max_handles' => 0]))
->build();
}
return $this->client;
}
}
$c = [
'hosts' => [
'http://host:port',
],
'retries' => 1,
];
$es = new Client();
$es->setHost($c);
$res = $es->from('test')
->sum('field')
->debug()
->search();