View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.helper;
17  
18  import java.util.Collections;
19  import java.util.HashMap;
20  import java.util.List;
21  import java.util.Locale;
22  import java.util.Map;
23  
24  import javax.annotation.PostConstruct;
25  
26  import org.codelibs.core.concurrent.CommonPoolUtil;
27  import org.codelibs.core.lang.StringUtil;
28  import org.codelibs.core.misc.Pair;
29  import org.codelibs.fess.Constants;
30  import org.codelibs.fess.entity.SearchRequestParams.SearchRequestType;
31  import org.codelibs.fess.es.client.FessEsClient;
32  import org.codelibs.fess.es.client.FessEsClient.SearchConditionBuilder;
33  import org.codelibs.fess.es.config.exbhv.KeyMatchBhv;
34  import org.codelibs.fess.es.config.exentity.KeyMatch;
35  import org.codelibs.fess.mylasta.direction.FessConfig;
36  import org.codelibs.fess.util.ComponentUtil;
37  import org.codelibs.fess.util.DocumentUtil;
38  import org.elasticsearch.index.query.BoolQueryBuilder;
39  import org.elasticsearch.index.query.QueryBuilder;
40  import org.elasticsearch.index.query.QueryBuilders;
41  import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder;
42  import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
43  import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
44  import org.slf4j.Logger;
45  import org.slf4j.LoggerFactory;
46  
47  public class KeyMatchHelper {
48      private static final Logger logger = LoggerFactory.getLogger(KeyMatchHelper.class);
49  
50      protected volatile Map<String, Map<String, Pair<QueryBuilder, ScoreFunctionBuilder<?>>>> keyMatchQueryMap = Collections.emptyMap();
51  
52      protected long reloadInterval = 1000L;
53  
54      @PostConstruct
55      public void init() {
56          reload(0);
57      }
58  
59      public void update() {
60          CommonPoolUtil.execute(() -> reload(reloadInterval));
61      }
62  
63      public List<KeyMatch> getAvailableKeyMatchList() {
64          return ComponentUtil.getComponent(KeyMatchBhv.class).selectList(cb -> {
65              cb.query().matchAll();
66              cb.fetchFirst(ComponentUtil.getFessConfig().getPageKeymatchMaxFetchSizeAsInteger());
67          });
68      }
69  
70      protected void reload(final long interval) {
71          final FessConfig fessConfig = ComponentUtil.getFessConfig();
72          final Map<String, Map<String, Pair<QueryBuilder, ScoreFunctionBuilder<?>>>> keyMatchQueryMap = new HashMap<>();
73          getAvailableKeyMatchList().stream().forEach(
74                  keyMatch -> {
75                      final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
76                      if (logger.isDebugEnabled()) {
77                          logger.debug("Loading KeyMatch Query: " + keyMatch.getQuery() + ", Size: " + keyMatch.getMaxSize());
78                      }
79                      getDocumentList(keyMatch).stream().map(doc -> {
80                          if (logger.isDebugEnabled()) {
81                              logger.debug("Loaded KeyMatch doc: " + doc);
82                          }
83                          return DocumentUtil.getValue(doc, fessConfig.getIndexFieldDocId(), String.class);
84                      }).forEach(docId -> {
85                          boolQuery.should(QueryBuilders.termQuery(fessConfig.getIndexFieldDocId(), docId));
86                      });
87  
88                      if (boolQuery.hasClauses()) {
89                          if (logger.isDebugEnabled()) {
90                              logger.debug("Loaded KeyMatch Boost Query: " + boolQuery);
91                          }
92                          String virtualHost = keyMatch.getVirtualHost();
93                          if (StringUtil.isBlank(virtualHost)) {
94                              virtualHost = StringUtil.EMPTY;
95                          }
96                          Map<String, Pair<QueryBuilder, ScoreFunctionBuilder<?>>> queryMap = keyMatchQueryMap.get(virtualHost);
97                          if (queryMap == null) {
98                              queryMap = new HashMap<>();
99                              keyMatchQueryMap.put(virtualHost, queryMap);
100                         }
101                         queryMap.put(toLowerCase(keyMatch.getTerm()),
102                                 new Pair<>(boolQuery, ScoreFunctionBuilders.weightFactorFunction(keyMatch.getBoost())));
103                     } else if (logger.isDebugEnabled()) {
104                         logger.debug("No KeyMatch boost docs");
105                     }
106 
107                     if (interval > 0) {
108                         try {
109                             Thread.sleep(interval);
110                         } catch (final InterruptedException e) {
111                             if (logger.isDebugEnabled()) {
112                                 logger.debug("Interrupted.", e);
113                             }
114                         }
115                     }
116                 });
117         this.keyMatchQueryMap = keyMatchQueryMap;
118     }
119 
120     protected List<Map<String, Object>> getDocumentList(final KeyMatch keyMatch) {
121         final FessEsClient fessEsClient = ComponentUtil.getFessEsClient();
122         final FessConfig fessConfig = ComponentUtil.getFessConfig();
123         return fessEsClient.getDocumentList(fessConfig.getIndexDocumentSearchIndex(),
124                 searchRequestBuilder -> {
125                     return SearchConditionBuilder.builder(searchRequestBuilder.setPreference(Constants.SEARCH_PREFERENCE_LOCAL))
126                             .searchRequestType(SearchRequestType.ADMIN_SEARCH).size(keyMatch.getMaxSize()).query(keyMatch.getQuery())
127                             .responseFields(new String[] { fessConfig.getIndexFieldDocId() }).build();
128                 });
129     }
130 
131     public long getReloadInterval() {
132         return reloadInterval;
133     }
134 
135     public void setReloadInterval(final long reloadInterval) {
136         this.reloadInterval = reloadInterval;
137     }
138 
139     protected Map<String, Pair<QueryBuilder, ScoreFunctionBuilder<?>>> getQueryMap() {
140         final String key = ComponentUtil.getVirtualHostHelper().getVirtualHostKey();
141         final Map<String, Pair<QueryBuilder, ScoreFunctionBuilder<?>>> map = keyMatchQueryMap.get(key);
142         if (map != null) {
143             return map;
144         }
145         return Collections.emptyMap();
146     }
147 
148     public void buildQuery(final List<String> keywordList, final List<FilterFunctionBuilder> list) {
149         keywordList.stream().forEach(keyword -> {
150             final Pair<QueryBuilder, ScoreFunctionBuilder<?>> pair = getQueryMap().get(toLowerCase(keyword));
151             if (pair != null) {
152                 list.add(new FilterFunctionBuilder(pair.getFirst(), pair.getSecond()));
153             }
154         });
155     }
156 
157     public List<Map<String, Object>> getBoostedDocumentList(final String term, final int size) {
158         final FessEsClient fessEsClient = ComponentUtil.getFessEsClient();
159         final Pair<QueryBuilder, ScoreFunctionBuilder<?>> pair = getQueryMap().get(toLowerCase(term));
160         if (pair == null) {
161             return Collections.emptyList();
162         }
163         final FessConfig fessConfig = ComponentUtil.getFessConfig();
164         return fessEsClient.getDocumentList(fessConfig.getIndexDocumentSearchIndex(), searchRequestBuilder -> {
165             searchRequestBuilder.setPreference(Constants.SEARCH_PREFERENCE_LOCAL).setQuery(pair.getFirst()).setSize(size);
166             return true;
167         });
168     }
169 
170     private String toLowerCase(final String term) {
171         return term != null ? term.toLowerCase(Locale.ROOT) : term;
172     }
173 
174 }