import _ from 'lodash' ; import { nodeTypes } from '../node_types' ; import * as ast from '../ast' ; import { getRangeScript , RangeFilterParams } from '../../filters' ; import { getFields } from './utils/get_fields' ; import { getTimeZoneFromSettings } from '../../utils' ; import { getFullFieldNameNode } from './utils/get_full_field_name_node' ; import { IIndexPattern , KueryNode , IFieldType } from '../../..' ; export function buildNodeParams ( fieldName , params ) { const paramsToMap = _ . pick ( params , 'gt' , 'lt' , 'gte' , 'lte' , 'format' ) ; const fieldNameArg = typeof fieldName === 'string' ? ast . fromLiteralExpression ( fieldName ) : nodeTypes . literal . buildNode ( fieldName ) ; const args = _ . map ( paramsToMap , ( value , key ) => { return nodeTypes . namedArg . buildNode ( key , value ) ; } ) ; return { arguments : [ fieldNameArg , ... args ] , } ; } export function toOpenSearchQuery ( node , indexPattern ? , config = { } , context = { } ) { const [ fieldNameArg , ... args ] = node . arguments ; const fullFieldNameArg = getFullFieldNameNode ( fieldNameArg , indexPattern , context ?. nested ? context . nested . path : undefined ) ; const fields = indexPattern ? getFields ( fullFieldNameArg , indexPattern ) : [ ] ; const namedArgs = extractArguments ( args ) ; const queryParams = _ . mapValues ( namedArgs , ( arg ) => { return ast . toOpenSearchQuery ( arg ) ; } ) ; if ( fields && fields . length === 0 ) { fields . push ( { name : ( ast . toOpenSearchQuery ( fullFieldNameArg ) as unknown ) as string , scripted : false , type : '' , } ) ; } const queries = fields ! . map ( ( field ) => { const wrapWithNestedQuery = ( query ) => { if ( ! ( fullFieldNameArg . type === 'wildcard' ) || ! _ . get ( field , 'subType.nested' ) || context ! . nested ) { return query ; } else { return { nested : { path : field . subType ! . nested ! . path , query , score_mode : 'none' , } , } ; } } ; if ( field . scripted ) { return { script : getRangeScript ( field , queryParams ) , } ; } else if ( field . type === 'date' ) { const timeZoneParam = config . dateFormatTZ ? { time_zone : getTimeZoneFromSettings ( config ! . dateFormatTZ ) } : { } ; return wrapWithNestedQuery ( { range : { [ field . name ] : { ... queryParams , ... timeZoneParam , } , } , } ) ; } return wrapWithNestedQuery ( { range : { [ field . name ] : queryParams , } , } ) ; } ) ; return { bool : { should : queries , minimum_should_match : 1 , } , } ; } function extractArguments ( args ) { if ( ( args . gt && args . gte ) || ( args . lt && args . lte ) ) { throw new Error ( 'range ends cannot be both inclusive and exclusive' ) ; } const unnamedArgOrder = [ 'gte' , 'lte' , 'format' ] ; return args . reduce ( ( acc , arg , index ) => { if ( arg . type === 'namedArg' ) { acc [ arg . name ] = arg . value ; } else { acc [ unnamedArgOrder [ index ] ] = arg ; } return acc ; } , { } ) ; }