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 */
019
020package org.nuxeo.elasticsearch.provider;
021
022import java.io.Serializable;
023import java.util.ArrayList;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.elasticsearch.index.query.QueryBuilder;
031import org.nuxeo.ecm.core.api.CoreSession;
032import org.nuxeo.ecm.core.api.DocumentModel;
033import org.nuxeo.ecm.core.api.DocumentModelList;
034import org.nuxeo.ecm.core.api.NuxeoException;
035import org.nuxeo.ecm.core.query.QueryParseException;
036import org.nuxeo.ecm.platform.query.api.Aggregate;
037import org.nuxeo.ecm.platform.query.api.AggregateDefinition;
038import org.nuxeo.ecm.platform.query.api.Bucket;
039import org.nuxeo.ecm.platform.query.nxql.CoreQueryDocumentPageProvider;
040import org.nuxeo.elasticsearch.aggregate.AggregateEsBase;
041import org.nuxeo.elasticsearch.aggregate.AggregateFactory;
042import org.nuxeo.elasticsearch.api.ElasticSearchService;
043import org.nuxeo.elasticsearch.api.EsResult;
044import org.nuxeo.elasticsearch.query.NxQueryBuilder;
045import org.nuxeo.elasticsearch.query.NxqlQueryConverter;
046import org.nuxeo.runtime.api.Framework;
047
048/**
049 * Elasticsearch Page provider that converts the NXQL query build by CoreQueryDocumentPageProvider.
050 *
051 * @since 5.9.3
052 */
053public class ElasticSearchNxqlPageProvider extends CoreQueryDocumentPageProvider {
054
055    public static final String CORE_SESSION_PROPERTY = "coreSession";
056
057    public static final String SEARCH_ON_ALL_REPOSITORIES_PROPERTY = "searchAllRepositories";
058
059    protected static final Log log = LogFactory.getLog(ElasticSearchNxqlPageProvider.class);
060
061    private static final long serialVersionUID = 1L;
062
063    protected List<DocumentModel> currentPageDocuments;
064
065    protected HashMap<String, Aggregate<? extends Bucket>> currentAggregates;
066
067    @Override
068    public List<DocumentModel> getCurrentPage() {
069
070        long t0 = System.currentTimeMillis();
071
072        // use a cache
073        if (currentPageDocuments != null) {
074            return currentPageDocuments;
075        }
076        error = null;
077        errorMessage = null;
078        if (log.isDebugEnabled()) {
079            log.debug(String.format("Perform query for provider '%s': with pageSize=%d, offset=%d", getName(),
080                    getMinMaxPageSize(), getCurrentPageOffset()));
081        }
082        currentPageDocuments = new ArrayList<>();
083        CoreSession coreSession = getCoreSession();
084        if (query == null) {
085            buildQuery(coreSession);
086        }
087        if (query == null) {
088            throw new NuxeoException(String.format("Cannot perform null query: check provider '%s'", getName()));
089        }
090        // Build and execute the ES query
091        ElasticSearchService ess = Framework.getLocalService(ElasticSearchService.class);
092        try {
093            NxQueryBuilder nxQuery = new NxQueryBuilder(getCoreSession()).nxql(query)
094                                                                         .offset((int) getCurrentPageOffset())
095                                                                         .limit(getLimit())
096                                                                         .addAggregates(buildAggregates());
097            if (searchOnAllRepositories()) {
098                nxQuery.searchOnAllRepositories();
099            }
100            EsResult ret = ess.queryAndAggregate(nxQuery);
101            DocumentModelList dmList = ret.getDocuments();
102            currentAggregates = new HashMap<>(ret.getAggregates().size());
103            for (Aggregate<Bucket> agg : ret.getAggregates()) {
104                currentAggregates.put(agg.getId(), agg);
105            }
106            setResultsCount(dmList.totalSize());
107            currentPageDocuments = dmList;
108        } catch (QueryParseException e) {
109            error = e;
110            errorMessage = e.getMessage();
111            log.warn(e.getMessage(), e);
112        }
113
114        // send event for statistics !
115        fireSearchEvent(getCoreSession().getPrincipal(), query, currentPageDocuments, System.currentTimeMillis() - t0);
116
117        return currentPageDocuments;
118    }
119
120    protected int getLimit() {
121        int ret = (int) getMinMaxPageSize();
122        if (ret == 0) {
123            ret = -1;
124        }
125        return ret;
126    }
127
128    public QueryBuilder getCurrentQueryAsEsBuilder() {
129        String nxql = getCurrentQuery();
130        return NxqlQueryConverter.toESQueryBuilder(nxql);
131    }
132
133    @Override
134    protected void pageChanged() {
135        currentPageDocuments = null;
136        currentAggregates = null;
137        super.pageChanged();
138    }
139
140    @Override
141    public void refresh() {
142        currentPageDocuments = null;
143        currentAggregates = null;
144        super.refresh();
145    }
146
147    @Override
148    protected CoreSession getCoreSession() {
149        Map<String, Serializable> props = getProperties();
150        CoreSession coreSession = (CoreSession) props.get(CORE_SESSION_PROPERTY);
151        if (coreSession == null) {
152            throw new NuxeoException("cannot find core session");
153        }
154        return coreSession;
155    }
156
157    private List<AggregateEsBase<? extends Bucket>> buildAggregates() {
158        ArrayList<AggregateEsBase<? extends Bucket>> ret = new ArrayList<>(getAggregateDefinitions().size());
159        for (AggregateDefinition def : getAggregateDefinitions()) {
160            ret.add(AggregateFactory.create(def, getSearchDocumentModel()));
161        }
162        return ret;
163    }
164
165    protected boolean searchOnAllRepositories() {
166        String value = (String) getProperties().get(SEARCH_ON_ALL_REPOSITORIES_PROPERTY);
167        if (value == null) {
168            return false;
169        }
170        return Boolean.parseBoolean(value);
171    }
172
173    @Override
174    public boolean hasAggregateSupport() {
175        return true;
176    }
177
178    @Override
179    public Map<String, Aggregate<? extends Bucket>> getAggregates() {
180        getCurrentPage();
181        return currentAggregates;
182    }
183
184    /**
185     * Extends the default implementation to add results of aggregates
186     *
187     * @since 7.4
188     */
189    @Override
190    protected void incorporateAggregates(Map<String, Serializable> eventProps) {
191
192        super.incorporateAggregates(eventProps);
193        if (currentAggregates != null) {
194            HashMap<String, Serializable> aggregateMatches = new HashMap<>();
195            for (String key : currentAggregates.keySet()) {
196                Aggregate<? extends Bucket> ag = currentAggregates.get(key);
197                ArrayList<HashMap<String, Serializable>> buckets = new ArrayList<>();
198                for (Bucket bucket : ag.getBuckets()) {
199                    HashMap<String, Serializable> b = new HashMap<>();
200                    b.put("key", bucket.getKey());
201                    b.put("count", bucket.getDocCount());
202                    buckets.add(b);
203                }
204                aggregateMatches.put(key, buckets);
205            }
206            eventProps.put("aggregatesMatches", aggregateMatches);
207        }
208    }
209}