-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathelastic.ts
More file actions
70 lines (61 loc) · 1.65 KB
/
elastic.ts
File metadata and controls
70 lines (61 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import {
BucketAggregation,
ElasticsearchQuery,
MetricAggregation,
TermsQuery,
} from '../types';
type OrderByType = '_key' | '_term' | '_count'
function getTermsAgg(
fieldName: string,
size: number,
shard_size: number,
orderBy: OrderByType = "_key",
order: 'asc'|'desc' = 'asc'
): BucketAggregation {
return {
type: 'terms',
id: "",
field: fieldName,
settings:{
size: size.toString(),
shard_size: shard_size.toString(),
order: order,
orderBy: orderBy,
}
}
}
export function getDataQuery(queryDef: TermsQuery, refId: string): ElasticsearchQuery {
const metrics: MetricAggregation[] = [
{id:"count1", type:'count'}
];
// Default behaviour is to order results by { _key: asc } and get 100 terms,
// shard_size is set to 100 to limit terms fetched by shard (by default it's 100 * 10).
// queryDef.order allows selection of asc/desc
// queryDef.orderBy allows selection of doc_count ordering (defaults desc)
let orderBy: OrderByType;
switch (queryDef.orderBy || 'key') {
case 'key':
case 'term':
orderBy = '_key'
break;
case 'doc_count':
orderBy = '_count'
break;
default:
throw { message: `Invalid query sort type ${queryDef.orderBy}` };
}
const {order = orderBy === '_count' ? 'desc' : 'asc' } = queryDef;
if (['asc', 'desc'].indexOf(order) < 0) {
throw { message: `Invalid query sort order ${order}` };
}
const bucketAggs: BucketAggregation[] = [];
if (queryDef.field) {
bucketAggs.push(getTermsAgg(queryDef.field, 100, 100, orderBy, order))
}
return {
refId,
metrics,
bucketAggs,
query: queryDef.query,
}
}