zoukankan      html  css  js  c++  java
  • yii2.0 查询elasticsearch常用语句

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

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

    如:

      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字段。

  • 相关阅读:
    bzoj2733 永无乡 平衡树按秩合并
    bzoj2752 高速公路 线段树
    bzoj1052 覆盖问题 二分答案 dfs
    bzoj1584 打扫卫生 dp
    bzoj1854 游戏 二分图
    bzoj3316 JC loves Mkk 二分答案 单调队列
    bzoj3643 Phi的反函数 数学 搜索
    有一种恐怖,叫大爆搜
    BZOJ3566 概率充电器 概率dp
    一些奇奇怪怪的过题思路
  • 原文地址:https://www.cnblogs.com/angellating/p/7250404.html
Copyright © 2011-2022 走看看