From 7f0e56b444a075a4ece9ed82ffa3a4e69c121393 Mon Sep 17 00:00:00 2001 From: delvedor Date: Thu, 3 Sep 2020 17:37:31 +0200 Subject: [PATCH] Added .aggs method to fluent API and improved query merger --- dsl/src/aggregation.ts | 8 ++------ dsl/src/fluent.ts | 14 ++++++++++---- dsl/src/query.ts | 9 +++++---- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/dsl/src/aggregation.ts b/dsl/src/aggregation.ts index 5bbfdbc06..202a27906 100644 --- a/dsl/src/aggregation.ts +++ b/dsl/src/aggregation.ts @@ -24,11 +24,7 @@ import * as t from './types' -interface anyObject { - [key: string]: any -} - -type aggsOptions = anyObject | string +type aggsOptions = Record | string function _A (...aggregations: any[]): any { return { @@ -106,7 +102,7 @@ interface Aggregations { } const aggregations = { - get: function (target: unknown, name: string) { + get (target: unknown, name: string) { return { // add aggregations to a parent aggregation aggs (...aggregations: any[]): t.Aggregation { diff --git a/dsl/src/fluent.ts b/dsl/src/fluent.ts index 0c14389eb..1eaee0246 100644 --- a/dsl/src/fluent.ts +++ b/dsl/src/fluent.ts @@ -25,12 +25,13 @@ /* eslint lines-between-class-members: 0 */ import Q from './query' +import A from './aggregation' import * as t from './types' -const kState = Symbol('dsl-state') -type nestedQFn = (f: Fluent) => Fluent +const kState = Symbol('dsl-query-state') +type nestedQFn = (f: FluentQ) => FluentQ -class Fluent { +class FluentQ { [kState]: Record[] constructor () { this[kState] = [] @@ -257,6 +258,11 @@ class Fluent { this[kState].push(Q.size(s)) return this } + + aggs (...aggregations: Record[]): this { + this[kState].push(A(...aggregations)) + return this + } } -export default Fluent +export default FluentQ diff --git a/dsl/src/query.ts b/dsl/src/query.ts index f85a3b58f..5f176ac8c 100644 --- a/dsl/src/query.ts +++ b/dsl/src/query.ts @@ -27,6 +27,7 @@ import deepMerge from 'deepmerge' import * as t from './types' function Q (...blocks: t.AnyQuery[]): Record { + blocks = blocks.flat() const topLevelKeys = [ 'aggs', 'collapse', @@ -51,10 +52,10 @@ function Q (...blocks: t.AnyQuery[]): Record { 'version' ] - const queries = blocks.flat().filter(block => { - return !topLevelKeys.includes(Object.keys(block)[0]) - }) - const body: Record = queries.length > 0 ? Q.bool(...queries) : {} + const queries = blocks.filter(block => !topLevelKeys.includes(Object.keys(block)[0])) + const body: Record = queries.length === 1 && !isClause(queries[0]) && !isBool(queries[0]) + ? { query: queries[0] } + : queries.length > 0 ? Q.bool(...queries) : {} for (const block of blocks) { const key = Object.keys(block)[0] if (topLevelKeys.includes(key)) {