0
# Query Services
1
2
The SkyWalking query services provide comprehensive APIs for retrieving metrics, traces, topology, metadata, logs, and alarm data. These services offer debugging capabilities, pagination support, and flexible query conditions for building observability dashboards and analytics applications.
3
4
## Core Query Services
5
6
### MetricsQueryService
7
8
Primary service for querying metrics data with debugging and time-series support.
9
10
```java { .api }
11
public class MetricsQueryService implements Service {
12
13
/**
14
* Reads single metric value for given conditions
15
* @param condition Metrics query conditions including name and entity
16
* @param duration Time range for the query
17
* @return Nullable value result with debugging info
18
* @throws IOException If query execution fails
19
*/
20
public NullableValue readMetricsValue(MetricsCondition condition, Duration duration)
21
throws IOException;
22
23
/**
24
* Reads time-series metrics values over duration
25
* @param condition Metrics query conditions
26
* @param duration Time range with step configuration
27
* @return Time-series values with timestamps
28
* @throws IOException If query execution fails
29
*/
30
public MetricsValues readMetricsValues(MetricsCondition condition, Duration duration)
31
throws IOException;
32
33
/**
34
* Reads labeled metrics values for multi-dimensional data
35
* @param condition Base metrics query conditions
36
* @param labels List of label key-value pairs for filtering
37
* @param duration Time range for the query
38
* @return List of labeled time-series values
39
* @throws IOException If query execution fails
40
*/
41
public List<MetricsValues> readLabeledMetricsValues(MetricsCondition condition,
42
List<KeyValue> labels, Duration duration) throws IOException;
43
44
/**
45
* Reads heat map metrics data for percentile analysis
46
* @param condition Metrics query conditions for heat map data
47
* @param duration Time range for aggregation
48
* @return Heat map data structure with value distributions
49
* @throws IOException If query execution fails
50
*/
51
public HeatMap readHeatMap(MetricsCondition condition, Duration duration)
52
throws IOException;
53
54
/**
55
* Reads sampled records for detailed analysis
56
* @param condition Query conditions for sample selection
57
* @param duration Time range for sampling
58
* @return List of sampled records
59
* @throws IOException If query execution fails
60
*/
61
public List<SelectedRecord> readSampledRecords(MetricsCondition condition, Duration duration)
62
throws IOException;
63
64
/**
65
* Executes expression-based queries for complex metrics calculations
66
* @param expression Metrics query expression (MQE format)
67
* @param duration Time range for evaluation
68
* @return Expression evaluation results
69
* @throws IOException If expression execution fails
70
*/
71
public ExpressionResult queryExpressionSeries(String expression, Duration duration)
72
throws IOException;
73
}
74
```
75
76
### TraceQueryService
77
78
Service for querying distributed trace data and segments.
79
80
```java { .api }
81
public class TraceQueryService implements Service {
82
83
/**
84
* Queries trace list with pagination and filtering
85
* @param condition Trace query conditions
86
* @return Paginated trace list
87
* @throws IOException If query fails
88
*/
89
public TraceBrief queryBasicTraces(TraceQueryCondition condition) throws IOException;
90
91
/**
92
* Queries detailed trace by trace ID
93
* @param traceId Unique trace identifier
94
* @return Complete trace with all spans
95
* @throws IOException If query fails
96
*/
97
public Trace queryTrace(String traceId) throws IOException;
98
99
/**
100
* Queries trace segments by segment ID
101
* @param segmentId Segment identifier
102
* @return Trace segment with span details
103
* @throws IOException If query fails
104
*/
105
public List<Segment> queryTraceSegments(String segmentId) throws IOException;
106
107
/**
108
* Queries span details by span ID
109
* @param spanId Span identifier within trace
110
* @return Detailed span information
111
* @throws IOException If query fails
112
*/
113
public Span querySpan(String spanId) throws IOException;
114
}
115
```
116
117
### TopologyQueryService
118
119
Service for querying service topology and relationships.
120
121
```java { .api }
122
public class TopologyQueryService implements Service {
123
124
/**
125
* Queries global service topology
126
* @param duration Time range for topology data
127
* @return Service topology with nodes and edges
128
* @throws IOException If query fails
129
*/
130
public Topology getGlobalTopology(Duration duration) throws IOException;
131
132
/**
133
* Queries service topology around specific service
134
* @param serviceId Central service identifier
135
* @param duration Time range for analysis
136
* @return Service-centric topology
137
* @throws IOException If query fails
138
*/
139
public Topology getServiceTopology(String serviceId, Duration duration) throws IOException;
140
141
/**
142
* Queries instance topology for service
143
* @param serviceId Parent service identifier
144
* @param duration Time range for instance data
145
* @return Instance topology within service
146
* @throws IOException If query fails
147
*/
148
public ServiceInstanceTopology getServiceInstanceTopology(String serviceId, Duration duration)
149
throws IOException;
150
151
/**
152
* Queries endpoint topology for service
153
* @param serviceId Parent service identifier
154
* @param duration Time range for endpoint data
155
* @return Endpoint relationships within service
156
* @throws IOException If query fails
157
*/
158
public Topology getEndpointTopology(String serviceId, Duration duration) throws IOException;
159
}
160
```
161
162
### MetadataQueryService
163
164
Service for querying services, instances, endpoints and other metadata.
165
166
```java { .api }
167
public class MetadataQueryService implements Service {
168
169
/**
170
* Lists all services with optional keyword filtering
171
* @param keyword Optional service name filter
172
* @return List of services
173
* @throws IOException If query fails
174
*/
175
public List<Service> getAllServices(String keyword) throws IOException;
176
177
/**
178
* Lists services within time duration
179
* @param duration Time range for service activity
180
* @return List of active services
181
* @throws IOException If query fails
182
*/
183
public List<Service> listServices(Duration duration) throws IOException;
184
185
/**
186
* Gets service instances for specific service
187
* @param serviceId Parent service identifier
188
* @param duration Time range for instance activity
189
* @return List of service instances
190
* @throws IOException If query fails
191
*/
192
public List<ServiceInstance> getServiceInstances(String serviceId, Duration duration)
193
throws IOException;
194
195
/**
196
* Gets endpoints for specific service
197
* @param serviceId Parent service identifier
198
* @param keyword Optional endpoint name filter
199
* @param limit Maximum number of results
200
* @return List of service endpoints
201
* @throws IOException If query fails
202
*/
203
public List<Endpoint> getEndpoints(String serviceId, String keyword, int limit)
204
throws IOException;
205
206
/**
207
* Finds service by exact name match
208
* @param serviceName Service name to search
209
* @return Service entity or null if not found
210
* @throws IOException If query fails
211
*/
212
public Service findService(String serviceName) throws IOException;
213
214
/**
215
* Finds service instance by name
216
* @param serviceId Parent service identifier
217
* @param instanceName Instance name to search
218
* @return Service instance or null if not found
219
* @throws IOException If query fails
220
*/
221
public ServiceInstance findServiceInstance(String serviceId, String instanceName)
222
throws IOException;
223
224
/**
225
* Finds endpoint by name within service
226
* @param serviceId Parent service identifier
227
* @param endpointName Endpoint name to search
228
* @return Endpoint entity or null if not found
229
* @throws IOException If query fails
230
*/
231
public Endpoint findEndpoint(String serviceId, String endpointName) throws IOException;
232
}
233
```
234
235
### LogQueryService
236
237
Service for querying log data with filtering and pagination.
238
239
```java { .api }
240
public class LogQueryService implements Service {
241
242
/**
243
* Queries logs with filtering conditions and pagination
244
* @param condition Log query conditions including service, instance, keywords
245
* @return Paginated log results
246
* @throws IOException If query fails
247
*/
248
public Logs queryLogs(LogQueryCondition condition) throws IOException;
249
250
/**
251
* Tests log query conditions for validation
252
* @param condition Log query conditions to test
253
* @return Test result with validation status
254
* @throws IOException If test fails
255
*/
256
public LogTestResponse test(LogQueryCondition condition) throws IOException;
257
}
258
```
259
260
### AlarmQueryService
261
262
Service for querying alarms and alerting data.
263
264
```java { .api }
265
public class AlarmQueryService implements Service {
266
267
/**
268
* Queries alarms with pagination and filtering
269
* @param duration Time range for alarm search
270
* @param scope Alarm scope (service, instance, endpoint, etc.)
271
* @param keyword Optional keyword filter
272
* @param paging Pagination configuration
273
* @param tags Optional tag filters
274
* @return Paginated alarm results
275
* @throws IOException If query fails
276
*/
277
public Alarms getAlarm(Duration duration, Scope scope, String keyword,
278
Pagination paging, List<Tag> tags) throws IOException;
279
}
280
```
281
282
## Specialized Query Services
283
284
### MetricsMetadataQueryService
285
286
Service for querying metadata about available metrics.
287
288
```java { .api }
289
public class MetricsMetadataQueryService implements Service {
290
291
/**
292
* Lists all available metrics
293
* @param regex Optional regex pattern for metric name filtering
294
* @return List of metric metadata
295
* @throws IOException If query fails
296
*/
297
public List<MetricDefinition> listMetrics(String regex) throws IOException;
298
299
/**
300
* Gets definition for specific metric
301
* @param metricName Metric name to describe
302
* @return Detailed metric definition with type and scope
303
* @throws IOException If query fails
304
*/
305
public MetricDefinition getMetricDefinition(String metricName) throws IOException;
306
307
/**
308
* Lists metric types (gauge, counter, histogram, etc.)
309
* @return List of available metric types
310
* @throws IOException If query fails
311
*/
312
public List<String> listMetricTypes() throws IOException;
313
}
314
```
315
316
### AggregationQueryService
317
318
Service for data aggregation and statistical queries.
319
320
```java { .api }
321
public class AggregationQueryService implements Service {
322
323
/**
324
* Performs aggregation over metrics data
325
* @param aggregation Aggregation configuration (sum, avg, max, min, etc.)
326
* @param condition Query conditions
327
* @param duration Time range
328
* @return Aggregated result
329
* @throws IOException If aggregation fails
330
*/
331
public AggregationResult aggregate(Aggregation aggregation, MetricsCondition condition,
332
Duration duration) throws IOException;
333
334
/**
335
* Performs top-N aggregation
336
* @param condition Query conditions
337
* @param duration Time range
338
* @param topN Number of top results
339
* @param order Sort order (ASC/DESC)
340
* @return Top-N results
341
* @throws IOException If query fails
342
*/
343
public List<TopNEntity> getTopN(MetricsCondition condition, Duration duration,
344
int topN, Order order) throws IOException;
345
}
346
```
347
348
### HierarchyQueryService
349
350
Service for querying service hierarchies and relationships.
351
352
```java { .api }
353
public class HierarchyQueryService implements Service {
354
355
/**
356
* Gets service hierarchy structure
357
* @param serviceId Root service identifier
358
* @param layer Hierarchy layer (auto, k8s, mesh, etc.)
359
* @return Service hierarchy tree
360
* @throws IOException If query fails
361
*/
362
public ServiceHierarchy getServiceHierarchy(String serviceId, String layer)
363
throws IOException;
364
365
/**
366
* Gets instance hierarchy for service
367
* @param serviceId Parent service identifier
368
* @param instanceId Instance identifier
369
* @return Instance hierarchy information
370
* @throws IOException If query fails
371
*/
372
public InstanceHierarchy getInstanceHierarchy(String serviceId, String instanceId)
373
throws IOException;
374
375
/**
376
* Lists available hierarchy layers
377
* @return List of supported hierarchy layers
378
* @throws IOException If query fails
379
*/
380
public List<String> listLayers() throws IOException;
381
}
382
```
383
384
## Query Support Classes
385
386
### DurationUtils
387
388
Utility for duration calculations and manipulation.
389
390
```java { .api }
391
public class DurationUtils {
392
393
/**
394
* Converts duration to time range in milliseconds
395
* @param duration Duration configuration
396
* @return Start and end timestamps
397
*/
398
public static TimeRange durationToTimeRange(Duration duration);
399
400
/**
401
* Calculates step interval based on duration
402
* @param duration Duration configuration
403
* @return Step interval in milliseconds
404
*/
405
public static long calculateStep(Duration duration);
406
407
/**
408
* Validates duration configuration
409
* @param duration Duration to validate
410
* @return True if duration is valid
411
*/
412
public static boolean isValidDuration(Duration duration);
413
}
414
```
415
416
### PaginationUtils
417
418
Utility for handling query result pagination.
419
420
```java { .api }
421
public class PaginationUtils {
422
423
/**
424
* Calculates offset from page number and size
425
* @param pageNum Page number (1-based)
426
* @param pageSize Number of items per page
427
* @return Offset for database query
428
*/
429
public static int calculateOffset(int pageNum, int pageSize);
430
431
/**
432
* Creates pagination from offset and limit
433
* @param offset Starting offset
434
* @param limit Maximum items to return
435
* @return Pagination configuration
436
*/
437
public static Pagination createPagination(int offset, int limit);
438
}
439
```
440
441
### PointOfTime
442
443
Utility for point-in-time calculations.
444
445
```java { .api }
446
public class PointOfTime {
447
448
private long timestamp;
449
450
/**
451
* Creates point of time from timestamp
452
* @param timestamp Unix timestamp in milliseconds
453
*/
454
public PointOfTime(long timestamp);
455
456
/**
457
* Gets timestamp
458
* @return Unix timestamp in milliseconds
459
*/
460
public long getTimestamp();
461
462
/**
463
* Converts to time bucket with downsampling
464
* @param downSampling Downsampling level
465
* @return Time bucket value
466
*/
467
public long toTimeBucket(DownSampling downSampling);
468
}
469
```
470
471
## Query Data Types
472
473
### Query Conditions
474
475
```java { .api }
476
/**
477
* Metrics query conditions
478
*/
479
public class MetricsCondition {
480
private String name;
481
private String entity;
482
private Map<String, String> labels;
483
484
public String getName();
485
public String getEntity();
486
public Map<String, String> getLabels();
487
}
488
489
/**
490
* Trace query conditions
491
*/
492
public class TraceQueryCondition {
493
private String serviceId;
494
private String serviceInstanceId;
495
private String endpointId;
496
private String traceId;
497
private int minDuration;
498
private int maxDuration;
499
private TraceState traceState;
500
private QueryOrder queryOrder;
501
private Pagination paging;
502
503
public String getServiceId();
504
public int getMinDuration();
505
public int getMaxDuration();
506
public TraceState getTraceState();
507
public Pagination getPaging();
508
}
509
510
/**
511
* Log query conditions
512
*/
513
public class LogQueryCondition {
514
private String serviceId;
515
private String serviceInstanceId;
516
private String endpointId;
517
private String relatedTraceId;
518
private ContentType contentType;
519
private List<String> keywords;
520
private List<String> excludingKeywords;
521
private Pagination paging;
522
523
public String getServiceId();
524
public List<String> getKeywords();
525
public Pagination getPaging();
526
}
527
```
528
529
### Query Results
530
531
```java { .api }
532
/**
533
* Nullable value result with debugging info
534
*/
535
public class NullableValue {
536
private Long value;
537
private boolean isEmptyValue;
538
private String debuggingMessage;
539
540
public Long getValue();
541
public boolean isEmptyValue();
542
public String getDebuggingMessage();
543
}
544
545
/**
546
* Time-series metrics values
547
*/
548
public class MetricsValues {
549
private String label;
550
private List<KVInt> values;
551
552
public String getLabel();
553
public List<KVInt> getValues();
554
}
555
556
/**
557
* Key-value integer pair with timestamp
558
*/
559
public class KVInt {
560
private long id; // timestamp
561
private long value;
562
563
public long getId();
564
public long getValue();
565
}
566
567
/**
568
* Heat map data structure
569
*/
570
public class HeatMap {
571
private List<HeatMapColumn> values;
572
573
public List<HeatMapColumn> getValues();
574
}
575
576
/**
577
* Heat map column with bucket data
578
*/
579
public class HeatMapColumn {
580
private long id; // timestamp
581
private List<Long> values; // bucket values
582
583
public long getId();
584
public List<Long> getValues();
585
}
586
587
/**
588
* Complete trace information
589
*/
590
public class Trace {
591
private List<Span> spans;
592
593
public List<Span> getSpans();
594
}
595
596
/**
597
* Trace span details
598
*/
599
public class Span {
600
private String traceId;
601
private String segmentId;
602
private int spanId;
603
private int parentSpanId;
604
private List<Ref> refs;
605
private String serviceCode;
606
private String serviceInstanceName;
607
private String startTime;
608
private String endTime;
609
private String endpointName;
610
private String type;
611
private String peer;
612
private String component;
613
private boolean isError;
614
private String layer;
615
private List<KeyValue> tags;
616
private List<LogEntity> logs;
617
618
public String getTraceId();
619
public String getEndpointName();
620
public boolean isError();
621
public List<KeyValue> getTags();
622
}
623
624
/**
625
* Service topology structure
626
*/
627
public class Topology {
628
private List<Node> nodes;
629
private List<Call> calls;
630
631
public List<Node> getNodes();
632
public List<Call> getCalls();
633
}
634
635
/**
636
* Topology node (service, instance, endpoint)
637
*/
638
public class Node {
639
private String id;
640
private String name;
641
private String type;
642
private boolean isReal;
643
644
public String getId();
645
public String getName();
646
public boolean isReal();
647
}
648
649
/**
650
* Service call relationship
651
*/
652
public class Call {
653
private String source;
654
private String target;
655
private List<String> detectPoints;
656
657
public String getSource();
658
public String getTarget();
659
public List<String> getDetectPoints();
660
}
661
```
662
663
## Usage Examples
664
665
### Querying Metrics Data
666
667
```java
668
// Query single metric value
669
MetricsCondition condition = new MetricsCondition();
670
condition.setName("service_cpm");
671
condition.setEntity("dGVzdC1zZXJ2aWNl.1"); // encoded service ID
672
673
Duration duration = new Duration();
674
duration.setStart("2023-01-01 00:00:00");
675
duration.setEnd("2023-01-01 01:00:00");
676
duration.setStep(Step.MINUTE);
677
678
NullableValue result = metricsQueryService.readMetricsValue(condition, duration);
679
if (!result.isEmptyValue()) {
680
System.out.println("Service CPM: " + result.getValue());
681
}
682
683
// Query time-series metrics
684
MetricsValues timeSeries = metricsQueryService.readMetricsValues(condition, duration);
685
for (KVInt point : timeSeries.getValues()) {
686
System.out.println("Time: " + point.getId() + ", Value: " + point.getValue());
687
}
688
689
// Query labeled metrics (multi-dimensional)
690
List<KeyValue> labels = Arrays.asList(
691
new KeyValue("status_code", "200"),
692
new KeyValue("method", "GET")
693
);
694
695
List<MetricsValues> labeledResults = metricsQueryService.readLabeledMetricsValues(
696
condition, labels, duration
697
);
698
699
for (MetricsValues labeledSeries : labeledResults) {
700
System.out.println("Label: " + labeledSeries.getLabel());
701
// Process time series for this label
702
}
703
```
704
705
### Querying Trace Data
706
707
```java
708
// Query trace list with filtering
709
TraceQueryCondition traceCondition = new TraceQueryCondition();
710
traceCondition.setServiceId("service-123");
711
traceCondition.setMinDuration(1000); // minimum 1 second
712
traceCondition.setMaxDuration(10000); // maximum 10 seconds
713
traceCondition.setTraceState(TraceState.ERROR);
714
715
Pagination paging = new Pagination();
716
paging.setPageNum(1);
717
paging.setPageSize(20);
718
traceCondition.setPaging(paging);
719
720
TraceBrief traceBrief = traceQueryService.queryBasicTraces(traceCondition);
721
for (BasicTrace trace : traceBrief.getTraces()) {
722
System.out.println("Trace ID: " + trace.getTraceId());
723
System.out.println("Duration: " + trace.getDuration() + "ms");
724
}
725
726
// Query detailed trace
727
String traceId = "trace-456";
728
Trace detailedTrace = traceQueryService.queryTrace(traceId);
729
for (Span span : detailedTrace.getSpans()) {
730
System.out.println("Span: " + span.getEndpointName());
731
System.out.println("Duration: " + (span.getEndTime() - span.getStartTime()));
732
if (span.isError()) {
733
System.out.println("Error span found!");
734
}
735
}
736
```
737
738
### Querying Topology
739
740
```java
741
// Query global service topology
742
Duration duration = createDuration("2023-01-01 00:00:00", "2023-01-01 01:00:00");
743
Topology globalTopology = topologyQueryService.getGlobalTopology(duration);
744
745
System.out.println("Services: " + globalTopology.getNodes().size());
746
System.out.println("Calls: " + globalTopology.getCalls().size());
747
748
for (Node node : globalTopology.getNodes()) {
749
System.out.println("Service: " + node.getName() + " (ID: " + node.getId() + ")");
750
}
751
752
for (Call call : globalTopology.getCalls()) {
753
System.out.println("Call: " + call.getSource() + " -> " + call.getTarget());
754
}
755
756
// Query service-specific topology
757
String serviceId = "service-123";
758
Topology serviceTopology = topologyQueryService.getServiceTopology(serviceId, duration);
759
```
760
761
### Querying Metadata
762
763
```java
764
// List all services
765
List<Service> allServices = metadataQueryService.getAllServices(null);
766
for (Service service : allServices) {
767
System.out.println("Service: " + service.getName());
768
769
// Get instances for this service
770
List<ServiceInstance> instances = metadataQueryService.getServiceInstances(
771
service.getId(), duration
772
);
773
774
for (ServiceInstance instance : instances) {
775
System.out.println(" Instance: " + instance.getName());
776
}
777
778
// Get endpoints for this service
779
List<Endpoint> endpoints = metadataQueryService.getEndpoints(
780
service.getId(), null, 100
781
);
782
783
for (Endpoint endpoint : endpoints) {
784
System.out.println(" Endpoint: " + endpoint.getName());
785
}
786
}
787
788
// Find specific service
789
Service specificService = metadataQueryService.findService("my-service");
790
if (specificService != null) {
791
System.out.println("Found service: " + specificService.getId());
792
}
793
```
794
795
### Querying Logs
796
797
```java
798
// Query logs with filtering
799
LogQueryCondition logCondition = new LogQueryCondition();
800
logCondition.setServiceId("service-123");
801
logCondition.setKeywords(Arrays.asList("error", "exception"));
802
logCondition.setContentType(ContentType.TEXT);
803
804
Pagination logPaging = new Pagination();
805
logPaging.setPageNum(1);
806
logPaging.setPageSize(50);
807
logCondition.setPaging(logPaging);
808
809
Logs logs = logQueryService.queryLogs(logCondition);
810
for (Log log : logs.getLogs()) {
811
System.out.println("Log: " + log.getContent());
812
System.out.println("Timestamp: " + log.getTimestamp());
813
if (log.getTraceId() != null) {
814
System.out.println("Related trace: " + log.getTraceId());
815
}
816
}
817
```
818
819
## Core Query Types
820
821
```java { .api }
822
/**
823
* Duration configuration for time-based queries
824
*/
825
public class Duration {
826
private String start;
827
private String end;
828
private Step step;
829
830
public String getStart();
831
public String getEnd();
832
public Step getStep();
833
}
834
835
/**
836
* Time step for duration queries
837
*/
838
public enum Step {
839
SECOND, MINUTE, HOUR, DAY
840
}
841
842
/**
843
* Pagination configuration
844
*/
845
public class Pagination {
846
private int pageNum;
847
private int pageSize;
848
private boolean needTotal;
849
850
public int getPageNum();
851
public int getPageSize();
852
public boolean isNeedTotal();
853
}
854
855
/**
856
* Key-value pair for labels and tags
857
*/
858
public class KeyValue {
859
private String key;
860
private String value;
861
862
public KeyValue(String key, String value);
863
public String getKey();
864
public String getValue();
865
}
866
867
/**
868
* Query module definition
869
*/
870
public class QueryModule extends ModuleDefine {
871
public static final String NAME = "query";
872
873
@Override
874
public String name();
875
876
@Override
877
public Class[] services();
878
}
879
```