Lens là editor visualization chính của Kibana 8+, thay gần như hết Visualize Classic. Nó thân thiện với người mới vì drag-drop, nhưng đủ sâu để dev backend làm ra các chart production: error rate, SLO burn rate, so sánh tuần trước, threshold color-code. Điểm chuyển giao là khi bạn bước từ drag-drop sang Formula mode — khoảng 80% nhu cầu “chart đặc biệt” không cần đến Vega hay Canvas, chỉ cần 2-3 function trong Formula.

Đây là bài thứ 4 trong series Kibana từ A đến Z. Sau bài này bạn sẽ:

  • Dựng được 6 loại chart phổ biến bằng drag-drop
  • Viết Formula cho metric composite (error rate, ratio, percentage)
  • Dùng time shift để so sánh “tuần này vs tuần trước”
  • Thêm annotation layer đánh dấu deploy, incident lên time chart
  • Thêm reference line cho SLO threshold và đổi màu theo mức
  • Tránh 5 pitfall hay gặp khi Lens chậm hoặc ra số sai

Phần 1: Lens cơ bản — drag-drop 6 loại chart

Vào Dashboards → Create dashboard → Create visualization. Cửa sổ Lens mở ra với 4 vùng:

  • Trái: field list của data view.
  • Giữa: preview chart đang dựng.
  • Phải: chart config (axis, breakdown, style).
  • Trên cùng: chart type selector + filter + time range.

Bar chart — phổ biến nhất

Ví dụ “error theo giờ”:

  1. Drag @timestamp vào Horizontal axis.
  2. Drag Level (keyword) vào Vertical axis — Kibana tự suggest Count of records.
  3. Drag Level vào Breakdown — mỗi level màu riêng.
  4. Filter panel: Level : ("Error" or "Fatal").
  5. Save → đặt tên → Save and return.

Line chart — trend theo thời gian

Giống bar nhưng chart type chọn Line. Tốt cho metric liên tục: response time, CPU, request rate.

Area chart — stacked composition

Chart type Area stacked. Hiển thị tỉ lệ thành phần theo thời gian (ví dụ: share traffic theo service).

Pie / donut — tỉ lệ tổng

  1. Chart type Pie hoặc Donut.
  2. Slice by: Properties.ApplicationName.
  3. Size by: Count of records.

Lưu ý: pie không nên dùng khi có hơn 7 category — dùng bar horizontal.

Table — số liệu raw

  1. Chart type Table.
  2. Drag nhiều field vào Rows và metric vào Metrics.
  3. Click header column → sort.

Table tốt để embed vào dashboard làm “top N list” (top endpoint, top user, top error message).

Metric — KPI đơn lẻ

  1. Chart type Metric.
  2. Drag 1 field → chọn function.
  3. Tuỳ chọn Secondary metric + Comparison (so sánh với baseline).

Ví dụ: tổng request hôm nay, có dấu mũi tên lên/xuống so với hôm qua.

Time interval — lỗi thường gặp

Mặc định Lens chọn interval auto. Nhưng khi query dữ liệu mỏng hoặc time range hẹp, chart nhìn gồ ghề hoặc quá mịn. Chuyển thủ công:

  • Click vào field @timestamp trong axis config → Customize time interval → chọn 1m, 5m, 1h, 1d.

Quy tắc tay: interval ≈ time range / 60 là đẹp nhất. Range 24h → interval 30m. Range 7 ngày → interval 3h.

Phần 2: Formula — khi drag-drop không đủ

Bất cứ metric field nào trong Lens đều có option “Formula” ngay dưới function selector. Formula cho phép viết biểu thức kiểu Excel kết hợp ES aggregation.

Function list chính

FunctionVai tròVí dụ
count()Đếm doccount()
count(kql='...')Đếm doc thoả filtercount(kql='Level:Error')
sum(field)Tổngsum(bytes)
average(field)Trung bìnhaverage(response_time)
unique_count(field)Distinct countunique_count(user_id)
percentile(field, percentile=95)Phân vịpercentile(rt, percentile=99)
min(field) / max(field)Min / Maxmax(cpu_percent)
last_value(field)Giá trị cuối cùnglast_value(gauge, sort=@timestamp)
moving_average(metric)Trung bình độngmoving_average(count(), window=5)
cumulative_sum(metric)Tổng tích luỹcumulative_sum(sum(revenue))
differences(metric)Delta giữa 2 bucketdifferences(count())

Các phép toán cơ bản

count(kql='Level:Error') / count() * 100

Đây là error rate (%). Cấu trúc chung của ratio:

<numerator> / <denominator> [* 100 nếu muốn phần trăm]

5 Formula thực chiến

Error rate (%):

count(kql='Level:Error') / count() * 100

Ratio p95 / p50 (chỉ số latency skew):

percentile(response_time_ms, percentile=95) / percentile(response_time_ms, percentile=50)

Apdex (threshold 500ms):

(count(kql='response_time_ms <= 500') + count(kql='response_time_ms > 500 AND response_time_ms <= 2000') / 2) / count()

Throughput per minute (từ count):

count() / 60

Giả sử interval = 1 phút. Với interval khác, chia theo số giây tương ứng.

SLO burn rate (tỉ lệ error so với budget 1%):

(count(kql='status >= 500') / count()) / 0.01

Burn rate > 1 = đang ngốn budget nhanh hơn bình thường.

Time shift — so sánh với tuần trước

Trong axis config, click vào metric → Advanced → Time shift → chọn preset hoặc custom (1w, 1d, 1h).

Dùng 2 metric cạnh nhau: 1 không time shift (current), 1 shift 1w (last week) → chart overlay 2 line để so sánh.

Hoặc dùng trong Formula:

count() - count(shift='1w')

Kết quả: delta so với cùng kỳ tuần trước. Âm = traffic giảm.

Filter trong Formula — sức mạnh thật

Trick ít biết nhất của Formula là filter inline qua kql param. Ví dụ:

count(kql='status >= 500') / count(kql='status >= 200') * 100

→ “Tỉ lệ lỗi trong tổng request hợp lệ” trong 1 panel duy nhất — không cần tạo 2 index, không cần sub-query.

Kết hợp với time shift:

count(kql='status >= 500', shift='1w') / count(kql='status >= 200', shift='1w') * 100

→ Error rate tuần trước, để so sánh.

Phần 3: Annotation layer — đánh dấu sự kiện

Time chart thường thấy spike/dip nhưng không biết vì sao. Annotation layer overlay các sự kiện (deploy, incident, config change) lên chart.

Static annotation

Click + Layer → Annotations → Add static annotation:

  • Điền Date cụ thể.
  • Text: “Deploy v2.4.1”.
  • Icon: triangle / circle / square.
  • Color: đỏ cho incident, xanh cho deploy.

Chart sẽ hiện dấu mốc dọc theo trục thời gian.

Dynamic annotation từ query

Tốt hơn nhiều: annotation từ 1 data view khác.

  • + Layer → Annotations → Query annotations.
  • Data view: ví dụ deploys-* (index lưu log deploy).
  • Time field: @timestamp.
  • Query: service : "order-service".
  • Tooltip field: version.

Từ giờ mọi deploy của order-service tự động hiện mốc lên chart error rate. Nhìn chart xong kết luận ngay: “spike error sau deploy v2.4.1 lúc 14:03”.

Use case khác cho dynamic annotation

  • Incident từ PagerDuty index → mốc đỏ.
  • Config change từ Git webhook → mốc vàng.
  • Marketing campaign → mốc xanh trên chart traffic.

Phần 4: Reference line và threshold color

Reference line là đường ngang trên chart thể hiện threshold. Ví dụ SLO 99.9% uptime:

Thêm reference line

  • + Layer → Reference lines → Add reference line.
  • Value: cố định (99.9) hoặc query (percentile(rt, percentile=95) last hour).
  • Label: “SLO 99.9%”.
  • Line style: dashed đậm.

Threshold color cho metric

Với chart type Metric hoặc Gauge:

  • Metric config → Colors → Custom color ranges.
  • Định nghĩa 3 band: xanh < 500ms, vàng 500-1000ms, đỏ > 1000ms.

Dashboard glance-view dev nhìn là biết tình trạng hệ thống.

Phần 5: Pitfall hay gặp

1. Cardinality quá cao → chart chậm hoặc crash

Drag user_id vào breakdown trên index 10M users → Lens sẽ cố render 10M series. Giới hạn:

  • Breakdown top N (config mặc định 5-10): Lens tự group phần còn lại thành “Other”.
  • Tăng N trong Breakdown config nếu cần, nhưng đừng quá 50.

2. Time interval sai → số sai

Chart “request per minute” với interval = 5 phút thì count() trả số request trong 5 phút, không phải per minute. Phải chia thủ công:

count() / 5

Hoặc đặt interval về 1m rồi dùng moving_average(count(), window=5).

3. Text field không aggregate được

Drag field Message (text) vào breakdown → lỗi hoặc ra “Other” hết. Dùng Message.keyword. Quy tắc: breakdown luôn trên keyword, không trên text.

4. Formula trả NaN

Phép chia cho 0: count(kql='Level:Error') / count() khi count() = 0 trong 1 bucket. Wrap bằng defaults:

defaults(count(kql='Level:Error') / count() * 100, 0)

(Lens 8.11+ có function defaults(expr, fallback).)

5. Panel trong dashboard không refresh khi filter dashboard-level

Nếu Lens panel có filter hardcoded, nó KHÔNG combine với filter dashboard. Để panel inherit:

  • Edit panel → Remove panel-level filters hoặc dùng query (respect dashboard filter) thay vì filter (hardcoded).

Cheatsheet

Nhu cầuChart / Formula
Error rate (%)count(kql='Level:Error') / count() * 100
p95 latencypercentile(response_time_ms, percentile=95)
Top 10 endpointBar horizontal, breakdown path.keyword, top 10
Deploy markerAnnotation layer → Query annotation từ deploys-*
SLO lineReference line, value 99.9 hoặc từ query
So sánh tuần trướccount() - count(shift='1w') hoặc 2 metric layer
KPI đơn lẻChart type Metric + Comparison
Distinct countunique_count(user_id)
Moving average 5-pointmoving_average(count(), window=5)
Cumulativecumulative_sum(sum(revenue))
ApdexXem Formula phần 2
Fallback khi chia 0defaults(expr, 0)

Lời kết

Lens vừa đủ đơn giản để người mới làm được chart đầu tiên trong 2 phút, vừa đủ mạnh cho dev backend tính burn rate SLO, apdex, ratio, time-shift — hầu hết đều trong Formula chứ không cần rời khỏi UI. 20% nhu cầu còn lại (visualization rất custom, infographic branded, layout pixel-precise) sẽ thuộc về Canvas — công cụ bài tiếp theo.

Bài 5 trong series Kibana từ A đến Z sẽ đi vào Canvas — dựng report branded cho stakeholder: khác Dashboard thế nào, expression language, data source với ESSQL, dynamic image/color theo value, và export PDF multi-page để giao CEO/CFO. Nếu có topic Lens cụ thể bạn muốn mình đi sâu hơn — ví dụ “dùng Lens để vẽ SLO burn rate chart”, “annotation thực chiến với CI/CD index”, hoặc “chuyển dashboard Visualize Classic sang Lens” — cứ drop comment hoặc email.