您的位置:首页 > 编程语言 > PHP开发

yii2.0 查询elasticsearch常用语句

2017-07-28 15:12 686 查看
整理一下最近用到的yii2.0查询es的语句,总结几个常用的查询语句

1、不用聚合函数的,直接获取源数据,可以用yii2.0 yii\elasticsearch\Query类直接查询

如:

public function get_single_index_data(&$index_arr, $table, &$conditons){
$this->from($index_arr,$table)->where($conditons)->addOrderBy('data_date asc')->limit(10000);
$command = $this->createCommand();
$rows = $command->search([],'post');
$data_arr = $rows['hits']['hits'];
return $data_arr;
}


 es支持多个数据结构相同的index,type查找,addOrderBy() 相当于es查询的order,limit(10000)相当于es的size:10000,不设置的时候es默认查找10条。

2、带有聚合函数的

$first_pay=array(
"terms" =>array(
"field" => "type_i",
"size"=>10000,
"order"=>array("_term"=>"asc")
),
"aggregations" => array(
"total_num"=>array(
"sum" =>array(
"field"=>"num_l"
)
)
)
);
$this->aggregations=array();
$this->from($index_arr_new_first_pay,$table)->where($condition)->addAggregate('first',$first_pay)->limit(0);
$command_first = $this->createCommand();
$rows_first = $command_first->search([],'post');
$first_pay_result = $rows_first['aggregations']['first']['buckets'];


  yii中有一个函数addAggregate(),可以添加es中的聚合函数,terms相当于mysql中的group by关键字,上面就是求同一个类型的和。同理,除了sum关键字,还可以求max,min,avg,有一个关键字stats可以同时求出sum,min,max,avg值。内es内置排序"order"=>array("_term"=>"asc"),是按词项的字符串值的字母顺序排序,也可以按
doc_count
值的升序排序,是"order"=>array("_count",=>"asc")。

引用文档上面的,内置排序有以下几种:

_count
按文档数排序。对
terms
histogram
date_histogram
有效。

_term
按词项的字符串值的字母顺序排序。只在
terms
内使用。

_key
按每个桶的键值数值排序(理论上与
_term
类似)。 只在
histogram
date_histogram
内使用。

除了聚合时候用到的sum,min,max,avg外,有时候还需要把其他字段展示出来。用到了一个top_hits。引用文档的例子:

"top_hits"=>array(
  "sort"=>array(
    "date"=>array(
      "order"=>"desc"
    )
  ),
  "_source"=>array(
    "includes"=>["date","price"]
  ),
  "size"=>1,
)


  top_hit按照排序的数据取一条,并且把源数据取出来,包括的字段是date和price字段。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: