import { ElasticUtils } from "./utils"; export class ElasticQuery extends ElasticUtils { parents: any[] = []; children: any[] = []; query: any = {}; parentAdditional: any = {}; sortOrder: any = [] constructor() { super() } bool(callback: Function) { this.parents = [] this.parents.push('bool') const result = callback(this) return result; } should(callback: Function) { this.parents.push('should') this.children = []; const result = callback(this) this.parentResolver() this.parents.splice(-1, 1) return result; } must(callback: Function) { this.parents.push('must') this.children = []; const result = callback(this) console.table(this.children); this.parentResolver() this.parents.splice(-1, 1) return result; } match(key: string, value: any) { if (this.isDefined(key, value)) this.children.push({ match: { [key]: value } }) return this; } term(key: string, value: any) { if (this.isDefined(key, value)) this.children.push({ term: { [key]: value } }) return this; } terms(key: string, value: any) { if (this.isDefined(key, value)) this.children.push({ terms: { [key]: value } }) return this; } search(fields: string, value: any) { if (this.isDefined(fields, value) && value != "") { this.children.push({ multi_match: { query: value, fields, fuzziness: 2 } }) } return this; } multiMatch(query: string, fields: any) { if (query && fields) this.children.push({ multi_match: { query, fields, } }) return this; } range(query: string, fields: any) { if (query && fields && (fields.gt || fields.gte || fields.lt || fields.lte)) { this.children.push({ range: { [query]: fields, } }) } return this; } when(status: any, process: Function) { console.log('# status', status); if (status) process(this) return this; } sort(field: string, type: string = 'asc') { this.sortOrder.push({ [field]: type }) return this; } sortDesc(field: string) { this.sortOrder.push({ [field]: "desc" }) return this; } sortDate(field: string, type: string) { this.sortOrder.push({ [field]: { "order": type, "format": "yyyy-MM-dd" } }) return this; } pagination(size: number, from: number) { this.parentAdditional = { ...this.parentAdditional, size, from: (from - 1) * size } return this; } async get(index: string, _source = []) { const filter = { index, body: { query: this.query, }, _source, ...this.parentAdditional, } console.log('# this.sortOrder', this.sortOrder); console.log('# this.parentAdditional', this.parentAdditional); console.table(this.query.bool.must); if (this.sortOrder.length) { filter.sort = this.sortOrder; } // @ts-ignore return await this.searchQuery(filter); } }