yii2.0 查询elasticsearch经常使用语句

整理一下最近用到的yii2.0查询es的语句,总结几个经常使用的查询语句php

一、不用聚合函数的,直接获取源数据,能够用yii2.0  yii\elasticsearch\Query类直接查询mysql

如:sql

  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条。yii2

二、带有聚合函数的数据结构

 $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")。yii

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

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

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

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

除了聚合时候用到的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字段。