001/* 002 * (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Gethin James 018 */ 019package org.nuxeo.elasticsearch.aggregate; 020 021import java.util.Collections; 022 023import org.elasticsearch.index.query.QueryBuilder; 024import org.elasticsearch.index.query.QueryBuilders; 025import org.elasticsearch.search.aggregations.bucket.SingleBucketAggregation; 026import org.nuxeo.ecm.core.api.DocumentModel; 027import org.nuxeo.ecm.platform.query.api.AggregateDefinition; 028import org.nuxeo.ecm.platform.query.core.BucketTerm; 029 030import com.fasterxml.jackson.annotation.JsonIgnore; 031 032/** 033 * An aggregate that returns a single bucket. 034 * 035 * @since 10.3 036 */ 037public abstract class SingleBucketAggregate extends AggregateEsBase<SingleBucketAggregation, BucketTerm> { 038 039 protected long docCount; 040 041 public SingleBucketAggregate(AggregateDefinition definition, DocumentModel searchDocument) { 042 super(definition, searchDocument); 043 } 044 045 @Override 046 public void parseAggregation(SingleBucketAggregation aggregation) { 047 this.docCount = aggregation.getDocCount(); 048 this.buckets = Collections.singletonList(new BucketTerm(definition.getType(), docCount)); 049 } 050 051 @JsonIgnore 052 @Override 053 public QueryBuilder getEsFilter() { 054 if (getSelection().isEmpty()) { 055 return null; 056 } 057 return QueryBuilders.termsQuery(getField(), getSelection()); 058 } 059 060 public long getDocCount() { 061 return docCount; 062 } 063}