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