整理一下最近用到的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字段。
