import { buildEsQuery } from '@kbn/es-query' ; import { SavedObjectsClientContract , SimpleSavedObject , IUiSettingsClient } from 'src/core/public' ; import { IndexPattern , getEsQueryConfig , IndexPatternsContract , IndexPatternAttributes , } from '../../../../../../../src/plugins/data/public' ; import { matchAllQuery } from '../../common' ; import { isIndexPattern } from '../../../../common/types/index_pattern' ; export type SavedSearchQuery = object ; type IndexPatternId = string ; let indexPatternCache = [ ] ; let fullIndexPatterns ; let currentIndexPattern = null ; export let refreshIndexPatterns ; export function loadIndexPatterns ( savedObjectsClient , indexPatterns ) { fullIndexPatterns = indexPatterns ; return savedObjectsClient . find < IndexPatternAttributes > ( { type : 'index-pattern' , fields : [ 'id' , 'title' , 'type' , 'fields' ] , perPage : 10000 , } ) . then ( ( response ) => { indexPatternCache = response . savedObjects ; if ( refreshIndexPatterns === null ) { refreshIndexPatterns = ( ) => { return new Promise ( ( resolve , reject ) => { loadIndexPatterns ( savedObjectsClient , indexPatterns ) . then ( ( resp ) => { resolve ( resp ) ; } ) . catch ( ( error ) => { reject ( error ) ; } ) ; } ) ; } ; } return indexPatternCache ; } ) ; } export function getIndexPatternIdByTitle ( indexPatternTitle ) { return indexPatternCache . find ( ( d ) => d ?. attributes ?. title === indexPatternTitle ) ?. id ; } type CombinedQuery = Record < 'bool' , any > | object ; export function loadCurrentIndexPattern ( indexPatterns , indexPatternId ) { fullIndexPatterns = indexPatterns ; currentIndexPattern = fullIndexPatterns . get ( indexPatternId ) ; return currentIndexPattern ; } export interface SearchItems { indexPattern : IndexPattern ; savedSearch : any ; query : any ; combinedQuery : CombinedQuery ; } export function createSearchItems ( indexPattern , savedSearch , config ) { let query = { query : '' , language : 'lucene' , } ; let combinedQuery = { bool : { must : [ matchAllQuery ] , } , } ; if ( ! isIndexPattern ( indexPattern ) && savedSearch !== null && savedSearch . id !== undefined ) { const searchSource = savedSearch . searchSource ; indexPattern = searchSource . getField ( 'index' ) as IndexPattern ; query = searchSource . getField ( 'query' ) ; const fs = searchSource . getField ( 'filter' ) ; const filters = fs . length ? fs : [ ] ; const esQueryConfigs = getEsQueryConfig ( config ) ; combinedQuery = buildEsQuery ( indexPattern , [ query ] , filters , esQueryConfigs ) ; } if ( ! isIndexPattern ( indexPattern ) ) { throw new Error ( 'Data view is not defined.' ) ; } return { indexPattern , savedSearch , query , combinedQuery , } ; }