import {Injectable, Inject} from '@angular/core'; import {ES_SEARCH_CONFIG, ISearchConfig} from '../config/config.module'; import {AuthHttp} from 'angular2-jwt'; import {IEsSearchFilter} from './search-filter'; import {Response, RequestOptions, Headers} from '@angular/http'; import {Observable} from 'rxjs/Rx'; import {RecordCollection} from '../records/record-collection'; import {EsSearchRecordTransformService} from '../records/transformers/es-search-record-transformer.service'; @Injectable() export class EsSearchService { private MAX_SEARCH_SIZE = 10000; constructor( private http: AuthHttp, @Inject(ES_SEARCH_CONFIG) private config: ISearchConfig, private transformer: EsSearchRecordTransformService) { } get( docType: string, searchFilter: IEsSearchFilter) : Observable { return this.http.post( this.config.searchUrl, this.buildRequestBody(searchFilter), this.buildRequestOptions() ).map(response => this.parseResponse(response, docType)) .cache(); } private buildRequestBody(searchFilter: IEsSearchFilter): string { const body: IEsSearchRequest = { app: 'atla', datasets: ['ok_production'], search: this.buildSearchObject(searchFilter) }; return JSON.stringify(body); } private parseResponse(response: Response, docType: string) { return this.transformer.transform( response.json().hits.hits, { label: _.startCase(docType), name: docType } ); } private buildSearchObject(filter: IEsSearchFilter): IEsSearchObject { const shapeFilter = { 'geoJson': { 'shape': { 'type': 'polygon', 'coordinates': filter.aoi.geometry.coordinates } } }; const search: IEsSearchObject = { filter: { bool: { must: [ { 'geo_shape': shapeFilter } ] } } }; if (filter.dateQuery) { const dateFilter = { range: { 'lastReportedMonth': { 'gte': filter.dateQuery } } }; search.filter.bool.must.push(dateFilter); } search.size = this.MAX_SEARCH_SIZE; return search; } private buildRequestOptions(): RequestOptions { const headers = new Headers({ 'Content-Type': 'application/json' }); return new RequestOptions({headers}); } } export interface IEsSearchRequest { app: string; datasets: string[]; search: IEsSearchObject; } export interface IEsSearchObject { size?: number; filter: IEsFilter; } export interface IEsFilter { bool?: any; }