欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

elasticsearch聚合查詢實踐示例

 更新時間:2023年12月06日 11:37:26   作者:mylife_sf  
這篇文章主要為大家介紹了elasticsearch聚合查詢實踐示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

概念

用于聚合的字段必須是 exact value,即doc_value=true。分詞字段不可進行聚合,對于 text 字段如需使用聚合,需開啟 fielddata,不推薦因容易造成 OOM。

聚合分類

  • Bucket aggregations(桶聚合)
  • Metric aggregations(指標聚合)
  • Pipeline aggregations(管道聚合)

聚合語法

request

GET /my-index/_search
{
  "aggs": {
    "my-agg-name": {
      "terms": {
        "field": "my-field"
      }
    }
  }
}

response

{
  "took": 78,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 5,
      "relation": "eq"
    },
    "max_score": 1.0,
    "hits": [...]
  },
  "aggregations": {
    "my-agg-name": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": []
    }
  }
}

聚合作用范圍及排序

  • query 和 filter,是先選定數(shù)據(jù)范圍,再聚合桶;
  • post_filter 對聚合桶沒影響,桶全部返回,只對查詢結(jié)果進行過濾返回,功能類似 mysql 中的 having;
  • global 的作用是覆蓋掉 query 的查詢作用。

聚合原理及 terms 精準度

Terms Aggregation 的返回中有兩個特殊的數(shù)值

  • doc_count_error_upper_bound:被遺漏的 term 分桶,包含的文檔,有可能的最大值
  • sum_other_doc_count:除了返回結(jié)果 bucket 的 terms 以外,其他的 terms 的文檔總數(shù)(總數(shù)-返回的總數(shù))

聚合實驗

實驗數(shù)據(jù)引用自《Elasticsearch 核心技術與實戰(zhàn)》- 阮一鳴(eBay Pronto 平臺技術負責人)

創(chuàng)建索引

PUT /employees/
{
  "mappings" : {
      "properties" : {
        "age" : {
          "type" : "integer"
        },
        "gender" : {
          "type" : "keyword"
        },
        "job" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 50
            }
          }
        },
        "name" : {
          "type" : "keyword"
        },
        "salary" : {
          "type" : "integer"
        }
      }
    }
}

批量寫入數(shù)據(jù)

PUT /employees/_bulk
{ "index" : {  "_id" : "1" } }
{ "name" : "Emma","age":32,"job":"Product Manager","gender":"female","salary":35000 }
{ "index" : {  "_id" : "2" } }
{ "name" : "Underwood","age":41,"job":"Dev Manager","gender":"male","salary": 50000}
{ "index" : {  "_id" : "3" } }
{ "name" : "Tran","age":25,"job":"Web Designer","gender":"male","salary":18000 }
{ "index" : {  "_id" : "4" } }
{ "name" : "Rivera","age":26,"job":"Web Designer","gender":"female","salary": 22000}
{ "index" : {  "_id" : "5" } }
{ "name" : "Rose","age":25,"job":"QA","gender":"female","salary":18000 }
{ "index" : {  "_id" : "6" } }
{ "name" : "Lucy","age":31,"job":"QA","gender":"female","salary": 25000}
{ "index" : {  "_id" : "7" } }
{ "name" : "Byrd","age":27,"job":"QA","gender":"male","salary":20000 }
{ "index" : {  "_id" : "8" } }
{ "name" : "Foster","age":27,"job":"Java Programmer","gender":"male","salary": 20000}
{ "index" : {  "_id" : "9" } }
{ "name" : "Gregory","age":32,"job":"Java Programmer","gender":"male","salary":22000 }
{ "index" : {  "_id" : "10" } }
{ "name" : "Bryant","age":20,"job":"Java Programmer","gender":"male","salary": 9000}
{ "index" : {  "_id" : "11" } }
{ "name" : "Jenny","age":36,"job":"Java Programmer","gender":"female","salary":38000 }
{ "index" : {  "_id" : "12" } }
{ "name" : "Mcdonald","age":31,"job":"Java Programmer","gender":"male","salary": 32000}
{ "index" : {  "_id" : "13" } }
{ "name" : "Jonthna","age":30,"job":"Java Programmer","gender":"female","salary":30000 }
{ "index" : {  "_id" : "14" } }
{ "name" : "Marshall","age":32,"job":"Javascript Programmer","gender":"male","salary": 25000}
{ "index" : {  "_id" : "15" } }
{ "name" : "King","age":33,"job":"Java Programmer","gender":"male","salary":28000 }
{ "index" : {  "_id" : "16" } }
{ "name" : "Mccarthy","age":21,"job":"Javascript Programmer","gender":"male","salary": 16000}
{ "index" : {  "_id" : "17" } }
{ "name" : "Goodwin","age":25,"job":"Javascript Programmer","gender":"male","salary": 16000}
{ "index" : {  "_id" : "18" } }
{ "name" : "Catherine","age":29,"job":"Javascript Programmer","gender":"female","salary": 20000}
{ "index" : {  "_id" : "19" } }
{ "name" : "Boone","age":30,"job":"DBA","gender":"male","salary": 30000}
{ "index" : {  "_id" : "20" } }
{ "name" : "Kathy","age":29,"job":"DBA","gender":"female","salary": 20000}

桶聚合

對 keword 進行聚合

GET employees/_search
{
  "size": 0,
  "aggs": {
    "jobs": {
      "terms": {
        "field":"job.keyword"
      }
    }
  }
}

指標聚合

多個 Metric 聚合,找到最低最高和平均 salary

GET employees/_search
{
  "size": 0,
  "aggs": {
    "max_salary": {
      "max": {
        "field": "salary"
      }
    },
    "min_salary": {
      "min": {
        "field": "salary"
      }
    },
    "avg_salary": {
      "avg": {
        "field": "salary"
      }
    }
  }
}

多次嵌套。根據(jù)工作類型分桶,然后按照性別分桶,計算 salary 的統(tǒng)計信息

GET employees/_search
{
  "size": 0,
  "aggs": {
    "job_gender_stats": {
      "terms": {
        "field": "job.keyword"
      },
      "aggs": {
        "gender_stats": {
          "terms": {
            "field": "gender"
          },
          "aggs": {
            "salary_stats": {
              "stats": {
                "field": "salary"
              }
            }
          }
        }
      }
    }
  }
}

response

{
  "took" : 6,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 20,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "job_gender_stats" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "Java Programmer",
          "doc_count" : 7,
          "gender_stats" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "male",
                "doc_count" : 5,
                "salary_stats" : {
                  "count" : 5,
                  "min" : 9000.0,
                  "max" : 32000.0,
                  "avg" : 22200.0,
                  "sum" : 111000.0
                }
              },
              {
                "key" : "female",
                "doc_count" : 2,
                "salary_stats" : {
                  "count" : 2,
                  "min" : 30000.0,
                  "max" : 38000.0,
                  "avg" : 34000.0,
                  "sum" : 68000.0
                }
              }
            ]
          }
        },
        ......
      ]
    }
  }
}

Pipeline 聚合

平均 salary 的統(tǒng)計分析

GET employees/_search
{
  "size": 0,
  "aggs": {
    "jobs": {
      "terms": {
        "field": "job.keyword",
        "size": 10
      },
      "aggs": {
        "avg_salary": {
          "avg": {
            "field": "salary"
          }
        }
      }
    },
    "stats_salary_by_job":{
      "stats_bucket": {
        "buckets_path": "jobs>avg_salary"
      }
    }
  }
}

實踐一:多商戶數(shù)據(jù)權限聚合分頁

collapse + cardinality 實現(xiàn)分頁去重查詢

GET my_order/_search
{
  "from": 0,
  "size": 6,
  "track_total_hits": true,
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "tenant_id": [
              1,
              2,
              3,
              4
            ]
          }
        }
      ]
    }
  },
  "aggs": {
    "cidAgg": {
      "cardinality": {
        "field": "cid"
      }
    }
  },
  "collapse": {
    "field": "cid"
  }
}

注:不支持 search_after,導出推薦 scroll

實踐二:多維度嵌套聚合

date_histogram 日期直方圖 + terms 分桶聚合過去一周每天產(chǎn)生的工單量,每天各品類工單量,每天各品類排名前 N 的爆品等等。

GET my_order/_search
{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "created_at": {
              "gte": "2023-11-10",
              "lte": "2023-11-16"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "ranges": {
      "date_histogram": {
        "field": "created_at",
        "format": "yyyy-MM-dd",
        "calendar_interval": "day"
      },
      "aggs": {
        "order_type_agg": {
          "terms": {
            "field": "order_type"
          }
        }
      }
    }
  }
}

實踐三:刪除 ES 索引重復數(shù)據(jù)

核酸檢測數(shù)據(jù)量大,數(shù)據(jù)存儲選型如使用 elasticsearch、click house 等列數(shù)據(jù)庫,數(shù)據(jù)重復是繞不開的話題,應用可通過計劃任務等方式檢測到重復數(shù)據(jù)并及時處理。

單字段查重

GET my_order/_search
{
  "size": 0,
  "query": {
    "term": {
      "tenant_id": 1
    }
  },
  "aggs": {
    "duplicateCount": {
      "terms": {
        "field": "cid",
        "size": 1000,
        "min_doc_count": 2
      }
    }
  }
}

多字段查重

GET my_order/_search
{
  "size": 0,
  "aggs": {
    "duplicateCount": {
      "terms": {
        "script": {
          "lang": "painless",
          "source": "doc['tenant_id'].value + doc['cid'].value"
        },
        "size": 100,
        "min_doc_count": 2
      }
    }
  }
}

數(shù)據(jù)查重并在 duplicateDocuments 數(shù)組展示細節(jié)

GET my_order/_search
{
  "size": 0,
  "aggs": {
    "duplicateCount": {
      "terms": {
        "script": {
          "lang": "painless",
          "source": "doc['tenant_id'].value + doc['cid'].value"
        },
        "size": 100,
        "min_doc_count": 2
      },
      "aggs": {
        "duplicateDocuments": {
          "top_hits": {}
        }
      }
    }
  }
}

查詢到的重復數(shù)據(jù)記入日志,核實后使用_delete_by_query刪除

POST my_order/_delete_by_query?conflicts=proceed&max_docs=1
{
  "query": {
    "term": {
      "cid": 2
    }
  }
}

max_docs為 response 當前 key 中bucket.doc_count的數(shù)量-1

php版本 demo 供參考

public function clearDuplicate()
{
    $index = 'my_order';
    $client = ClientBuilder::create()->build();
    $params = [
        'index' => $index,
        'size' => 0,
        'body' => [
            'query' => [
                ...
            ],
            'aggs' => [
                'duplicateCount' => [
                    'terms' => [
                        'field' => 'cid',
                        'size' => 1000,
                        'min_doc_count' => 2
                    ]
                ]
            ],
        ],
    ];
    $result = $client->search($params);
    $bucket = ArrayHelper::getValue($result, 'aggregations.duplicateCount.buckets');
    if (!is_array($bucket) || empty($bucket)) {
        return;
    }
    foreach ($bucket as $item) {
        $maxDocs = ArrayHelper::getValue($item, 'doc_count', 0) - 1;
        $key = ArrayHelper::getValue($item, 'key');
        if ($maxDocs < 1 || empty($key)) {
            continue;
        }
        $client->deleteByQuery([
            'index' => $index,
            'conflicts' => 'proceed',
            'max_docs' => $maxDocs,
            'body' => [
                'query' => [
                    'bool' => [
                        ...
                    ],
                ],
            ],
        ]);
    }
}

附:實驗環(huán)境

linux 操作系統(tǒng)

$ uname -a
Linux LAPTOP-QK4HAU1D 5.15.90.1-microsoft-standard-WSL2 #1 SMP Fri Jan 27 02:56:13 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/issue
Ubuntu 22.04.2 LTS \n \l

elasticsearch 版本

GET /
{
  "name" : "elasticsearch",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "6xwN3rfbQ2KGgQdt8IUKqg",
  "version" : {
    "number" : "7.16.2",
    "build_flavor" : "default",
    "build_type" : "docker",
    "build_hash" : "2b937c44140b6559905130a8650c64dbd0879cfb",
    "build_date" : "2021-12-18T19:42:46.604893745Z",
    "build_snapshot" : false,
    "lucene_version" : "8.10.1",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

參考:

[1] https://gitee.com/geektime-geekbang/geektime-ELK

[2] https://www.elastic.co/guide/en/elasticsearch/reference/7.17/... 

以上就是elasticsearch聚合查詢實踐示例的詳細內(nèi)容,更多關于elasticsearch聚合查詢的資料請關注腳本之家其它相關文章!

相關文章

  • 如何使用axis調(diào)用WebService及Java?WebService調(diào)用工具類

    如何使用axis調(diào)用WebService及Java?WebService調(diào)用工具類

    Axis是一個基于Java的Web服務框架,可以用來調(diào)用Web服務接口,下面這篇文章主要給大家介紹了關于如何使用axis調(diào)用WebService及Java?WebService調(diào)用工具類的相關資料,需要的朋友可以參考下
    2023-04-04
  • Java封裝數(shù)組實現(xiàn)在數(shù)組中查詢元素和修改元素操作示例

    Java封裝數(shù)組實現(xiàn)在數(shù)組中查詢元素和修改元素操作示例

    這篇文章主要介紹了Java封裝數(shù)組實現(xiàn)在數(shù)組中查詢元素和修改元素操作,結(jié)合實例形式分析了java針對數(shù)組元素查詢、修改的封裝操作實現(xiàn)技巧,需要的朋友可以參考下
    2020-03-03
  • Java8如何利用Lambda快速生成map、多層嵌套map

    Java8如何利用Lambda快速生成map、多層嵌套map

    這篇文章主要介紹了Java8如何利用Lambda快速生成map、多層嵌套map問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • springboot項目中controller層與前端的參數(shù)傳遞方式

    springboot項目中controller層與前端的參數(shù)傳遞方式

    這篇文章主要介紹了springboot項目中controller層與前端的參數(shù)傳遞方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • Java三種IO模型原理實例詳解

    Java三種IO模型原理實例詳解

    這篇文章主要介紹了Java三種IO模型原理實例詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-05-05
  • 最新評論