Grafana配置mysql展示自定義分組柱狀圖(Mac)


安裝Grafana

安裝使用環境為MAC,使用工具安裝:

brew update brew install grafana 

配置Grafana連接本地安裝的mysql,mysql安裝不做說明,配置文件列表如下:

配置文件應該位於/usr/local/etc/grafana/grafana.ini 日志文件應該位於/usr/local/var/log/grafana/grafana.log 如果你想手動安裝一個插件放在這里:/usr/local/var/lib/grafana/plugins 默認的sqlite數據庫位於 /usr/local/var/lib/grafana

其中,編輯grafana.ini文件連接數據庫,重點配置數據庫的連接類型,賬號,密碼,數據庫名(切記數據庫建立對應的數據庫)

clipboard.png

重啟Grafana服務

brew tap homebrew/services brew services start grafana 

此時網頁訪問localhost:3000即為Grafana配置數據源頁面(默認賬號密碼:admin / admin)

clipboard.png

配置mysql數據源

連接測試后保存,這樣在圖表展示數據源勾選默認即為mysql指定數據庫,或者勾選指定連接名
clipboard.png

數據庫構建表結構,錄入測試數據

clipboard.png

新建一個用於展示的Graph

編輯,鑒於展示目的為不按照時序排列的柱狀圖,但是Grafana的展示要求有時間字段在列,命名與time相關,故查詢時添加time字段為當前時間,返回結果可以為兩種可用形式,故展示兩種SQL查詢:

select now() as time, case when (score >=80) then '[80, ~)' when (score >=60 and score <80) then '[60, 80)' when (score >=40 and score <60) then '[40, 60)' when (score >=20 and score <40) then '[20, 40)' else '(~, 20)' end grade, count(*) num from grade group by case when (score >=80) then '[80, ~)' when (score >=60 and score <80) then '[60, 80)' when (score >=40 and score <60) then '[40, 60)' when (score >=20 and score <40) then '[20, 40)' else '(~, 20)' end order by 1;

展示結果為:

clipboard.png

select *, now() as time from (select count(*) as '[80, ~)' from grade g where g.score >=80) a, (select count(*) as '[60, 80)' from grade g where g.score >=60 and g.score <80) b, (select count(*) as '[40, 60)' from grade g where g.score >=40 and g.score <60) c, (select count(*) as '[20, 40)' from grade g where g.score >=20 and g.score <40) d, (select count(*) as '(~, 20)' from grade g where g.score <20) e;

展示結果為:

clipboard.png

重要設置,選擇series,選個代表數據是按series分組不是按時間,當前所選時間段進行計算。Y軸仍然表示 值。計算series的avg、min、max、total等。:

clipboard.png

效果圖為:

clipboard.png

兩種結果都能正常顯示,根據顯示規律總結為:

    1. 返回記錄中包含字符串格式的情況下,取字符串值的一列為分組名,對應的柱狀圖值為avg、min、max、total選擇的方法取聚合對應一行記錄上的其他數字值:
      如果多出來一列字符串值,則圖表報錯
      # 如果沒有字符串值列,則取數字列的列名為分組名,對應的柱狀圖值為每一列分組名下所有值的聚合
    2. 返回記錄中不包含字符串格式的情況下,取數字列的列名為分組名,對應的柱狀圖值為每一列分組名下所有值的聚合avg、min、max、total
    3. 適用上述所有的,時間字段必須存在,即使目前在分組柱狀圖中無用,否則會報錯,選擇format as中的table表現形式為表格,不考慮。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM