001/*
002 * (C) Copyright 2014 Nuxeo SA (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 *     bdelbosc
018 */
019package org.nuxeo.elasticsearch.aggregate;
020
021import static org.nuxeo.elasticsearch.ElasticSearchConstants.FULLTEXT_FIELD;
022
023import org.elasticsearch.index.query.QueryBuilder;
024import org.elasticsearch.search.aggregations.Aggregation;
025import org.elasticsearch.search.aggregations.AggregationBuilder;
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.ecm.core.query.sql.NXQL;
028import org.nuxeo.ecm.platform.query.api.AggregateDefinition;
029import org.nuxeo.ecm.platform.query.api.Bucket;
030import org.nuxeo.ecm.platform.query.core.AggregateBase;
031
032/**
033 * @since 6.0
034 */
035public abstract class AggregateEsBase<A extends Aggregation, B extends Bucket> extends AggregateBase<B> {
036
037    public static final char XPATH_SEP = '/';
038
039    public static final char ES_MUTLI_LEVEL_SEP = '.';
040
041    public static final int MAX_AGG_SIZE = 1000;
042
043    public AggregateEsBase(AggregateDefinition definition, DocumentModel searchDocument) {
044        super(definition, searchDocument);
045    }
046
047    /**
048     * Return the Elasticsearch aggregate builder
049     */
050    public abstract AggregationBuilder getEsAggregate();
051
052    /**
053     * Return the Elasticsearch aggregate filter corresponding to the selection
054     */
055    public abstract QueryBuilder getEsFilter();
056
057    /**
058     * Extract the aggregation from the Elasticsearch response
059     *
060     * @since 10.3
061     */
062    public abstract void parseAggregation(A aggregation);
063
064    @Override
065    public String getField() {
066        String ret = super.getField();
067        if (NXQL.ECM_FULLTEXT.equals(ret)) {
068            ret = FULLTEXT_FIELD;
069        }
070        ret = ret.replace(XPATH_SEP, ES_MUTLI_LEVEL_SEP);
071        return ret;
072    }
073
074    protected int getAggSize(String prop) {
075        // handle the size = 0 which means all terms in ES 2 and which is not supported in ES 5
076        int size = Integer.parseInt(prop);
077        return size == 0 ? MAX_AGG_SIZE : size;
078    }
079
080}