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.es.client;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  import static org.codelibs.elasticsearch.runner.ElasticsearchClusterRunner.newConfigs;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.net.InetAddress;
24  import java.net.UnknownHostException;
25  import java.nio.charset.StandardCharsets;
26  import java.text.SimpleDateFormat;
27  import java.util.ArrayList;
28  import java.util.Arrays;
29  import java.util.Collections;
30  import java.util.Date;
31  import java.util.HashMap;
32  import java.util.List;
33  import java.util.Map;
34  import java.util.function.BiConsumer;
35  import java.util.function.BiFunction;
36  import java.util.function.Function;
37  import java.util.regex.Pattern;
38  import java.util.stream.Collectors;
39  
40  import javax.annotation.PostConstruct;
41  import javax.annotation.PreDestroy;
42  
43  import org.codelibs.core.beans.util.BeanUtil;
44  import org.codelibs.core.exception.ResourceNotFoundRuntimeException;
45  import org.codelibs.core.io.FileUtil;
46  import org.codelibs.core.io.ResourceUtil;
47  import org.codelibs.core.lang.StringUtil;
48  import org.codelibs.curl.CurlResponse;
49  import org.codelibs.elasticsearch.client.HttpClient;
50  import org.codelibs.elasticsearch.runner.ElasticsearchClusterRunner;
51  import org.codelibs.elasticsearch.runner.ElasticsearchClusterRunner.Configs;
52  import org.codelibs.fess.Constants;
53  import org.codelibs.fess.entity.FacetInfo;
54  import org.codelibs.fess.entity.GeoInfo;
55  import org.codelibs.fess.entity.HighlightInfo;
56  import org.codelibs.fess.entity.PingResponse;
57  import org.codelibs.fess.entity.QueryContext;
58  import org.codelibs.fess.entity.SearchRequestParams.SearchRequestType;
59  import org.codelibs.fess.exception.FessSystemException;
60  import org.codelibs.fess.exception.InvalidQueryException;
61  import org.codelibs.fess.exception.ResultOffsetExceededException;
62  import org.codelibs.fess.exception.SearchQueryException;
63  import org.codelibs.fess.helper.DocumentHelper;
64  import org.codelibs.fess.helper.QueryHelper;
65  import org.codelibs.fess.mylasta.direction.FessConfig;
66  import org.codelibs.fess.util.ComponentUtil;
67  import org.codelibs.fess.util.DocMap;
68  import org.dbflute.exception.IllegalBehaviorStateException;
69  import org.dbflute.optional.OptionalEntity;
70  import org.elasticsearch.ElasticsearchException;
71  import org.elasticsearch.action.Action;
72  import org.elasticsearch.action.ActionFuture;
73  import org.elasticsearch.action.ActionListener;
74  import org.elasticsearch.action.ActionRequest;
75  import org.elasticsearch.action.ActionResponse;
76  import org.elasticsearch.action.DocWriteRequest;
77  import org.elasticsearch.action.DocWriteRequest.OpType;
78  import org.elasticsearch.action.DocWriteResponse.Result;
79  import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
80  import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequestBuilder;
81  import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
82  import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
83  import org.elasticsearch.action.admin.indices.flush.FlushResponse;
84  import org.elasticsearch.action.admin.indices.get.GetIndexResponse;
85  import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
86  import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
87  import org.elasticsearch.action.bulk.BulkItemResponse;
88  import org.elasticsearch.action.bulk.BulkItemResponse.Failure;
89  import org.elasticsearch.action.bulk.BulkRequest;
90  import org.elasticsearch.action.bulk.BulkRequestBuilder;
91  import org.elasticsearch.action.bulk.BulkResponse;
92  import org.elasticsearch.action.delete.DeleteRequest;
93  import org.elasticsearch.action.delete.DeleteRequestBuilder;
94  import org.elasticsearch.action.delete.DeleteResponse;
95  import org.elasticsearch.action.explain.ExplainRequest;
96  import org.elasticsearch.action.explain.ExplainRequestBuilder;
97  import org.elasticsearch.action.explain.ExplainResponse;
98  import org.elasticsearch.action.fieldcaps.FieldCapabilitiesRequest;
99  import org.elasticsearch.action.fieldcaps.FieldCapabilitiesRequestBuilder;
100 import org.elasticsearch.action.fieldcaps.FieldCapabilitiesResponse;
101 import org.elasticsearch.action.get.GetRequest;
102 import org.elasticsearch.action.get.GetRequestBuilder;
103 import org.elasticsearch.action.get.GetResponse;
104 import org.elasticsearch.action.get.MultiGetRequest;
105 import org.elasticsearch.action.get.MultiGetRequestBuilder;
106 import org.elasticsearch.action.get.MultiGetResponse;
107 import org.elasticsearch.action.index.IndexRequest;
108 import org.elasticsearch.action.index.IndexRequestBuilder;
109 import org.elasticsearch.action.index.IndexResponse;
110 import org.elasticsearch.action.search.ClearScrollRequest;
111 import org.elasticsearch.action.search.ClearScrollRequestBuilder;
112 import org.elasticsearch.action.search.ClearScrollResponse;
113 import org.elasticsearch.action.search.MultiSearchRequest;
114 import org.elasticsearch.action.search.MultiSearchRequestBuilder;
115 import org.elasticsearch.action.search.MultiSearchResponse;
116 import org.elasticsearch.action.search.SearchPhaseExecutionException;
117 import org.elasticsearch.action.search.SearchRequest;
118 import org.elasticsearch.action.search.SearchRequestBuilder;
119 import org.elasticsearch.action.search.SearchResponse;
120 import org.elasticsearch.action.search.SearchScrollRequest;
121 import org.elasticsearch.action.search.SearchScrollRequestBuilder;
122 import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
123 import org.elasticsearch.action.support.master.AcknowledgedResponse;
124 import org.elasticsearch.action.termvectors.MultiTermVectorsRequest;
125 import org.elasticsearch.action.termvectors.MultiTermVectorsRequestBuilder;
126 import org.elasticsearch.action.termvectors.MultiTermVectorsResponse;
127 import org.elasticsearch.action.termvectors.TermVectorsRequest;
128 import org.elasticsearch.action.termvectors.TermVectorsRequestBuilder;
129 import org.elasticsearch.action.termvectors.TermVectorsResponse;
130 import org.elasticsearch.action.update.UpdateRequest;
131 import org.elasticsearch.action.update.UpdateRequestBuilder;
132 import org.elasticsearch.action.update.UpdateResponse;
133 import org.elasticsearch.client.AdminClient;
134 import org.elasticsearch.client.Client;
135 import org.elasticsearch.cluster.metadata.MappingMetaData;
136 import org.elasticsearch.common.collect.ImmutableOpenMap;
137 import org.elasticsearch.common.document.DocumentField;
138 import org.elasticsearch.common.settings.Settings;
139 import org.elasticsearch.common.settings.Settings.Builder;
140 import org.elasticsearch.common.unit.TimeValue;
141 import org.elasticsearch.common.xcontent.XContentType;
142 import org.elasticsearch.index.query.InnerHitBuilder;
143 import org.elasticsearch.index.query.QueryBuilder;
144 import org.elasticsearch.index.query.QueryBuilders;
145 import org.elasticsearch.search.SearchHit;
146 import org.elasticsearch.search.SearchHits;
147 import org.elasticsearch.search.aggregations.AggregationBuilders;
148 import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
149 import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
150 import org.elasticsearch.search.collapse.CollapseBuilder;
151 import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
152 import org.elasticsearch.threadpool.ThreadPool;
153 import org.lastaflute.core.message.UserMessages;
154 import org.lastaflute.di.exception.ContainerInitFailureException;
155 import org.slf4j.Logger;
156 import org.slf4j.LoggerFactory;
157 
158 import com.fasterxml.jackson.core.type.TypeReference;
159 import com.fasterxml.jackson.databind.ObjectMapper;
160 import com.google.common.io.BaseEncoding;
161 
162 public class FessEsClient implements Client {
163     private static final Logger logger = LoggerFactory.getLogger(FessEsClient.class);
164 
165     protected ElasticsearchClusterRunner runner;
166 
167     protected String httpAddress;
168 
169     protected Client client;
170 
171     protected Map<String, String> settings;
172 
173     protected String indexConfigPath = "fess_indices";
174 
175     protected List<String> indexConfigList = new ArrayList<>();
176 
177     protected Map<String, List<String>> configListMap = new HashMap<>();
178 
179     protected String scrollForSearch = "1m";
180 
181     protected int sizeForDelete = 100;
182 
183     protected String scrollForDelete = "1m";
184 
185     protected int sizeForUpdate = 100;
186 
187     protected String scrollForUpdate = "1m";
188 
189     protected int maxConfigSyncStatusRetry = 10;
190 
191     protected int maxEsStatusRetry = 60;
192 
193     protected String clusterName = "elasticsearch";
194 
195     public void addIndexConfig(final String path) {
196         indexConfigList.add(path);
197     }
198 
199     public void addConfigFile(final String index, final String path) {
200         List<String> list = configListMap.get(index);
201         if (list == null) {
202             list = new ArrayList<>();
203             configListMap.put(index, list);
204         }
205         list.add(path);
206     }
207 
208     public void setSettings(final Map<String, String> settings) {
209         this.settings = settings;
210     }
211 
212     public String getStatus() {
213         return admin().cluster().prepareHealth().execute().actionGet(ComponentUtil.getFessConfig().getIndexHealthTimeout()).getStatus()
214                 .name();
215     }
216 
217     public void setRunner(final ElasticsearchClusterRunner runner) {
218         this.runner = runner;
219     }
220 
221     public boolean isEmbedded() {
222         return this.runner != null;
223     }
224 
225     protected InetAddress getInetAddressByName(final String host) {
226         try {
227             return InetAddress.getByName(host);
228         } catch (final UnknownHostException e) {
229             throw new FessSystemException("Failed to resolve the hostname: " + host, e);
230         }
231     }
232 
233     @PostConstruct
234     public void open() {
235         final FessConfig fessConfig = ComponentUtil.getFessConfig();
236 
237         String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
238         if (StringUtil.isBlank(httpAddress)) {
239             if (runner == null) {
240                 runner = new ElasticsearchClusterRunner();
241                 final Configs config = newConfigs().clusterName(clusterName).numOfNode(1).useLogger();
242                 final String esDir = System.getProperty("fess.es.dir");
243                 if (esDir != null) {
244                     config.basePath(esDir);
245                 }
246                 config.disableESLogger();
247                 runner.onBuild((number, settingsBuilder) -> {
248                     final File pluginDir = new File(esDir, "plugins");
249                     if (pluginDir.isDirectory()) {
250                         settingsBuilder.put("path.plugins", pluginDir.getAbsolutePath());
251                     } else {
252                         settingsBuilder.put("path.plugins", new File(System.getProperty("user.dir"), "plugins").getAbsolutePath());
253                     }
254                     if (settings != null) {
255                         settingsBuilder.putProperties(settings, s -> s);
256                     }
257                 });
258                 runner.build(config);
259             }
260             final int port = runner.node().settings().getAsInt("http.port", 9200);
261             httpAddress = "http://localhost:" + port;
262             logger.warn("Embedded Elasticsearch is running. This configuration is not recommended for production use.");
263         }
264         client = createHttpClient(fessConfig, httpAddress);
265 
266         if (StringUtil.isNotBlank(httpAddress)) {
267             System.setProperty(Constants.FESS_ES_HTTP_ADDRESS, httpAddress);
268         }
269 
270         waitForYellowStatus(fessConfig);
271 
272         indexConfigList.forEach(configName -> {
273             final String[] values = configName.split("/");
274             if (values.length == 2) {
275                 final String configIndex = values[0];
276                 final String configType = values[1];
277 
278                 final boolean isFessIndex = configIndex.equals("fess");
279                 final String indexName;
280                 if (isFessIndex) {
281                     final boolean exists = existsIndex(fessConfig.getIndexDocumentUpdateIndex());
282                     if (!exists) {
283                         indexName = generateNewIndexName(configIndex);
284                         createIndex(configIndex, indexName);
285                         createAlias(configIndex, indexName);
286                     } else {
287                         client.admin().cluster().prepareHealth(fessConfig.getIndexDocumentUpdateIndex()).setWaitForYellowStatus().execute()
288                                 .actionGet(fessConfig.getIndexIndicesTimeout());
289                         final GetIndexResponse response =
290                                 client.admin().indices().prepareGetIndex().addIndices(fessConfig.getIndexDocumentUpdateIndex()).execute()
291                                         .actionGet(fessConfig.getIndexIndicesTimeout());
292                         final String[] indices = response.indices();
293                         if (indices.length == 1) {
294                             indexName = indices[0];
295                         } else {
296                             indexName = configIndex;
297                         }
298                     }
299                 } else {
300                     if (configIndex.startsWith(".fess_config")) {
301                         final String name = fessConfig.getIndexConfigIndex();
302                         indexName = configIndex.replaceFirst(Pattern.quote(".fess_config"), name);
303                     } else if (configIndex.startsWith(".fess_user")) {
304                         final String name = fessConfig.getIndexUserIndex();
305                         indexName = configIndex.replaceFirst(Pattern.quote(".fess_config"), name);
306                     } else if (configIndex.startsWith("fess_log")) {
307                         final String name = fessConfig.getIndexLogIndex();
308                         indexName = configIndex.replaceFirst(Pattern.quote(".fess_config"), name);
309                     } else {
310                         throw new FessSystemException("Unknown config index: " + configIndex);
311                     }
312                     final boolean exists = existsIndex(indexName);
313                     if (!exists) {
314                         createIndex(configIndex, indexName);
315                         createAlias(configIndex, indexName);
316                     }
317                 }
318 
319                 addMapping(configIndex, configType, indexName);
320             } else {
321                 logger.warn("Invalid index config name: " + configName);
322             }
323         });
324     }
325 
326     protected Client createHttpClient(final FessConfig fessConfig, final String host) {
327         final Builder builder = Settings.builder().putList("http.hosts", host).put("processors", fessConfig.availableProcessors());
328         return new HttpClient(builder.build(), null);
329     }
330 
331     public boolean existsIndex(final String indexName) {
332         final FessConfig fessConfig = ComponentUtil.getFessConfig();
333         boolean exists = false;
334         try {
335             final IndicesExistsResponse response =
336                     client.admin().indices().prepareExists(indexName).execute().actionGet(fessConfig.getIndexSearchTimeout());
337             exists = response.isExists();
338         } catch (final Exception e) {
339             // ignore
340         }
341         return exists;
342     }
343 
344     public boolean reindex(final String fromIndex, final String toIndex, final boolean waitForCompletion) {
345         final String source = "{\"source\":{\"index\":\"" + fromIndex + "\"},\"dest\":{\"index\":\"" + toIndex + "\"}}";
346         try (CurlResponse response =
347                 ComponentUtil.getCurlHelper().post("/_reindex").param("wait_for_completion", Boolean.toString(waitForCompletion))
348                         .body(source).execute()) {
349             if (response.getHttpStatusCode() == 200) {
350                 return true;
351             } else {
352                 logger.warn("Failed to reindex from " + fromIndex + " to " + toIndex);
353             }
354         } catch (final IOException e) {
355             logger.warn("Failed to reindex from " + fromIndex + " to " + toIndex, e);
356         }
357         return false;
358     }
359 
360     public boolean createIndex(final String index, final String indexName) {
361         final FessConfig fessConfig = ComponentUtil.getFessConfig();
362         return createIndex(index, indexName, fessConfig.getIndexNumberOfShards(), fessConfig.getIndexAutoExpandReplicas(), true);
363     }
364 
365     public boolean createIndex(final String index, final String indexName, final String numberOfShards, final String autoExpandReplicas,
366             final boolean uploadConfig) {
367         final FessConfig fessConfig = ComponentUtil.getFessConfig();
368 
369         if (uploadConfig) {
370             waitForConfigSyncStatus();
371             sendConfigFiles(index);
372         }
373 
374         final String indexConfigFile = indexConfigPath + "/" + index + ".json";
375         try {
376             String source = FileUtil.readUTF8(indexConfigFile);
377             String dictionaryPath = System.getProperty("fess.dictionary.path", StringUtil.EMPTY);
378             if (StringUtil.isNotBlank(dictionaryPath) && !dictionaryPath.endsWith("/")) {
379                 dictionaryPath = dictionaryPath + "/";
380             }
381             source = source.replaceAll(Pattern.quote("${fess.dictionary.path}"), dictionaryPath);
382             source = source.replaceAll(Pattern.quote("${fess.index.codec}"), fessConfig.getIndexCodec());
383             source = source.replaceAll(Pattern.quote("${fess.index.number_of_shards}"), numberOfShards);
384             source = source.replaceAll(Pattern.quote("${fess.index.auto_expand_replicas}"), autoExpandReplicas);
385             final CreateIndexResponse indexResponse =
386                     client.admin().indices().prepareCreate(indexName).setSource(source, XContentType.JSON).execute()
387                             .actionGet(fessConfig.getIndexIndicesTimeout());
388             if (indexResponse.isAcknowledged()) {
389                 logger.info("Created " + indexName + " index.");
390                 return true;
391             } else if (logger.isDebugEnabled()) {
392                 logger.debug("Failed to create " + indexName + " index.");
393             }
394         } catch (final Exception e) {
395             logger.warn(indexConfigFile + " is not found.", e);
396         }
397 
398         return false;
399     }
400 
401     public void addMapping(final String index, final String docType, final String indexName) {
402         final FessConfig fessConfig = ComponentUtil.getFessConfig();
403 
404         final GetMappingsResponse getMappingsResponse =
405                 client.admin().indices().prepareGetMappings(indexName).execute().actionGet(fessConfig.getIndexIndicesTimeout());
406         final ImmutableOpenMap<String, MappingMetaData> indexMappings = getMappingsResponse.mappings().get(indexName);
407         if (indexMappings == null || !indexMappings.containsKey("properties")) {
408             String source = null;
409             final String mappingFile = indexConfigPath + "/" + index + "/" + docType + ".json";
410             try {
411                 source = FileUtil.readUTF8(mappingFile);
412             } catch (final Exception e) {
413                 logger.warn(mappingFile + " is not found.", e);
414             }
415             try {
416                 final AcknowledgedResponse putMappingResponse =
417                         client.admin().indices().preparePutMapping(indexName).setSource(source, XContentType.JSON).execute()
418                                 .actionGet(fessConfig.getIndexIndicesTimeout());
419                 if (putMappingResponse.isAcknowledged()) {
420                     logger.info("Created " + indexName + "/" + docType + " mapping.");
421                 } else {
422                     logger.warn("Failed to create " + indexName + "/" + docType + " mapping.");
423                 }
424 
425                 final String dataPath = indexConfigPath + "/" + index + "/" + docType + ".bulk";
426                 if (ResourceUtil.isExist(dataPath)) {
427                     insertBulkData(fessConfig, indexName, docType, dataPath);
428                 }
429             } catch (final Exception e) {
430                 logger.warn("Failed to create " + indexName + "/" + docType + " mapping.", e);
431             }
432         } else if (logger.isDebugEnabled()) {
433             logger.debug(indexName + "/" + docType + " mapping exists.");
434         }
435     }
436 
437     public boolean updateAlias(final String newIndex) {
438         final FessConfig fessConfig = ComponentUtil.getFessConfig();
439         final String updateAlias = fessConfig.getIndexDocumentUpdateIndex();
440         final String searchAlias = fessConfig.getIndexDocumentSearchIndex();
441         final GetIndexResponse response1 =
442                 client.admin().indices().prepareGetIndex().addIndices(updateAlias).execute().actionGet(fessConfig.getIndexIndicesTimeout());
443         final String[] updateIndices = response1.indices();
444         final GetIndexResponse response2 =
445                 client.admin().indices().prepareGetIndex().addIndices(searchAlias).execute().actionGet(fessConfig.getIndexIndicesTimeout());
446         final String[] searchIndices = response2.indices();
447 
448         final IndicesAliasesRequestBuilder builder =
449                 client.admin().indices().prepareAliases().addAlias(newIndex, updateAlias).addAlias(newIndex, searchAlias);
450         for (final String index : updateIndices) {
451             builder.removeAlias(index, updateAlias);
452         }
453         for (final String index : searchIndices) {
454             builder.removeAlias(index, searchAlias);
455         }
456         final AcknowledgedResponse response = builder.execute().actionGet(fessConfig.getIndexIndicesTimeout());
457         return response.isAcknowledged();
458     }
459 
460     protected void createAlias(final String index, final String createdIndexName) {
461         final FessConfig fessConfig = ComponentUtil.getFessConfig();
462         // alias
463         final String aliasConfigDirPath = indexConfigPath + "/" + index + "/alias";
464         try {
465             final File aliasConfigDir = ResourceUtil.getResourceAsFile(aliasConfigDirPath);
466             if (aliasConfigDir.isDirectory()) {
467                 stream(aliasConfigDir.listFiles((dir, name) -> name.endsWith(".json"))).of(
468                         stream -> stream.forEach(f -> {
469                             final String aliasName = f.getName().replaceFirst(".json$", "");
470                             String source = FileUtil.readUTF8(f);
471                             if (source.trim().equals("{}")) {
472                                 source = null;
473                             }
474                             final AcknowledgedResponse response =
475                                     client.admin().indices().prepareAliases().addAlias(createdIndexName, aliasName, source).execute()
476                                             .actionGet(fessConfig.getIndexIndicesTimeout());
477                             if (response.isAcknowledged()) {
478                                 logger.info("Created " + aliasName + " alias for " + createdIndexName);
479                             } else if (logger.isDebugEnabled()) {
480                                 logger.debug("Failed to create " + aliasName + " alias for " + createdIndexName);
481                             }
482                         }));
483             }
484         } catch (final ResourceNotFoundRuntimeException e) {
485             // ignore
486         } catch (final Exception e) {
487             logger.warn(aliasConfigDirPath + " is not found.", e);
488         }
489     }
490 
491     protected void sendConfigFiles(final String index) {
492         configListMap.getOrDefault(index, Collections.emptyList()).forEach(
493                 path -> {
494                     String source = null;
495                     final String filePath = indexConfigPath + "/" + index + "/" + path;
496                     try {
497                         source = FileUtil.readUTF8(filePath);
498                         try (CurlResponse response =
499                                 ComponentUtil.getCurlHelper().post("/_configsync/file").param("path", path).body(source).execute()) {
500                             if (response.getHttpStatusCode() == 200) {
501                                 logger.info("Register " + path + " to " + index);
502                             } else {
503                                 if (response.getContentException() != null) {
504                                     logger.warn("Invalid request for " + path + ".", response.getContentException());
505                                 } else {
506                                     logger.warn("Invalid request for " + path + ". The response is " + response.getContentAsString());
507                                 }
508                             }
509                         }
510                     } catch (final Exception e) {
511                         logger.warn("Failed to register " + filePath, e);
512                     }
513                 });
514         try (CurlResponse response = ComponentUtil.getCurlHelper().post("/_configsync/flush").execute()) {
515             if (response.getHttpStatusCode() == 200) {
516                 logger.info("Flushed config files.");
517             } else {
518                 logger.warn("Failed to flush config files.");
519             }
520         } catch (final Exception e) {
521             logger.warn("Failed to flush config files.", e);
522         }
523     }
524 
525     protected String generateNewIndexName(final String configIndex) {
526         return configIndex + "." + new SimpleDateFormat("yyyyMMdd").format(new Date());
527     }
528 
529     protected void insertBulkData(final FessConfig fessConfig, final String configIndex, final String configType, final String dataPath) {
530         try {
531             final BulkRequestBuilder builder = client.prepareBulk();
532             final ObjectMapper mapper = new ObjectMapper();
533             Arrays.stream(FileUtil.readUTF8(dataPath).split("\n")).reduce(
534                     (prev, line) -> {
535                         try {
536                             if (StringUtil.isBlank(prev)) {
537                                 final Map<String, Map<String, String>> result =
538                                         mapper.readValue(line, new TypeReference<Map<String, Map<String, String>>>() {
539                                         });
540                                 if (result.keySet().contains("index")) {
541                                     return line;
542                                 } else if (result.keySet().contains("update")) {
543                                     return line;
544                                 } else if (result.keySet().contains("delete")) {
545                                     return StringUtil.EMPTY;
546                                 }
547                             } else {
548                                 final Map<String, Map<String, String>> result =
549                                         mapper.readValue(prev, new TypeReference<Map<String, Map<String, String>>>() {
550                                         });
551                                 if (result.keySet().contains("index")) {
552                                     final IndexRequestBuilder requestBuilder =
553                                             client.prepareIndex().setIndex(configIndex).setId(result.get("index").get("_id"))
554                                                     .setSource(line, XContentType.JSON);
555                                     builder.add(requestBuilder);
556                                 }
557                             }
558                         } catch (final Exception e) {
559                             logger.warn("Failed to parse " + dataPath);
560                         }
561                         return StringUtil.EMPTY;
562                     });
563             final BulkResponse response = builder.execute().actionGet(fessConfig.getIndexBulkTimeout());
564             if (response.hasFailures()) {
565                 logger.warn("Failed to register " + dataPath + ": " + response.buildFailureMessage());
566             }
567         } catch (final Exception e) {
568             logger.warn("Failed to create " + configIndex + "/" + configType + " mapping.");
569         }
570     }
571 
572     protected void waitForYellowStatus(final FessConfig fessConfig) {
573         Exception cause = null;
574         final long startTime = System.currentTimeMillis();
575         for (int i = 0; i < maxEsStatusRetry; i++) {
576             try {
577                 final ClusterHealthResponse response =
578                         client.admin().cluster().prepareHealth().setWaitForYellowStatus().execute()
579                                 .actionGet(fessConfig.getIndexHealthTimeout());
580                 if (logger.isDebugEnabled()) {
581                     logger.debug("Elasticsearch Cluster Status: " + response.getStatus());
582                 }
583                 return;
584             } catch (final Exception e) {
585                 cause = e;
586             }
587             if (logger.isDebugEnabled()) {
588                 logger.debug("Failed to access to Elasticsearch:" + i, cause);
589             }
590             try {
591                 Thread.sleep(1000L);
592             } catch (final InterruptedException e) {
593                 // ignore
594             }
595         }
596         final String message =
597                 "Elasticsearch (" + System.getProperty(Constants.FESS_ES_HTTP_ADDRESS)
598                         + ") is not available. Check the state of your Elasticsearch cluster (" + clusterName + ") in "
599                         + (System.currentTimeMillis() - startTime) + "ms.";
600         throw new ContainerInitFailureException(message, cause);
601     }
602 
603     protected void waitForConfigSyncStatus() {
604         FessSystemException cause = null;
605         for (int i = 0; i < maxConfigSyncStatusRetry; i++) {
606             try (CurlResponse response = ComponentUtil.getCurlHelper().get("/_configsync/wait").param("status", "green").execute()) {
607                 final int httpStatusCode = response.getHttpStatusCode();
608                 if (httpStatusCode == 200) {
609                     logger.info("ConfigSync is ready.");
610                     return;
611                 } else {
612                     final String message = "Configsync is not available. HTTP Status is " + httpStatusCode;
613                     if (response.getContentException() != null) {
614                         throw new FessSystemException(message, response.getContentException());
615                     } else {
616                         throw new FessSystemException(message);
617                     }
618                 }
619             } catch (final Exception e) {
620                 cause = new FessSystemException("Configsync is not available.", e);
621             }
622             if (logger.isDebugEnabled()) {
623                 logger.debug("Failed to access to configsync:" + i, cause);
624             }
625             try {
626                 Thread.sleep(1000L);
627             } catch (final InterruptedException e) {
628                 // ignore
629             }
630         }
631         throw cause;
632     }
633 
634     @Override
635     @PreDestroy
636     public void close() {
637         if (runner != null) {
638             try {
639                 client.admin().indices().prepareFlush().setForce(true).execute()
640                         .actionGet(ComponentUtil.getFessConfig().getIndexIndicesTimeout());
641             } catch (final Exception e) {
642                 logger.warn("Failed to flush indices.", e);
643             }
644         }
645         try {
646             client.close();
647         } catch (final ElasticsearchException e) {
648             logger.warn("Failed to close Client: " + client, e);
649         }
650     }
651 
652     public long updateByQuery(final String index, final Function<SearchRequestBuilder, SearchRequestBuilder> option,
653             final BiFunction<UpdateRequestBuilder, SearchHit, UpdateRequestBuilder> builder) {
654 
655         final FessConfig fessConfig = ComponentUtil.getFessConfig();
656         SearchResponse response =
657                 option.apply(
658                         client.prepareSearch(index).setScroll(scrollForUpdate).setSize(sizeForUpdate)
659                                 .setPreference(Constants.SEARCH_PREFERENCE_LOCAL)).execute()
660                         .actionGet(fessConfig.getIndexScrollSearchTimeout());
661 
662         int count = 0;
663         String scrollId = response.getScrollId();
664         try {
665             while (scrollId != null) {
666                 final SearchHits searchHits = response.getHits();
667                 final SearchHit[] hits = searchHits.getHits();
668                 if (hits.length == 0) {
669                     break;
670                 }
671 
672                 final BulkRequestBuilder bulkRequest = client.prepareBulk();
673                 for (final SearchHit hit : hits) {
674                     final UpdateRequestBuilder requestBuilder =
675                             builder.apply(client.prepareUpdate().setIndex(index).setId(hit.getId()), hit);
676                     if (requestBuilder != null) {
677                         bulkRequest.add(requestBuilder);
678                     }
679                     count++;
680                 }
681                 final BulkResponse bulkResponse = bulkRequest.execute().actionGet(fessConfig.getIndexBulkTimeout());
682                 if (bulkResponse.hasFailures()) {
683                     throw new IllegalBehaviorStateException(bulkResponse.buildFailureMessage());
684                 }
685 
686                 response =
687                         client.prepareSearchScroll(scrollId).setScroll(scrollForUpdate).execute()
688                                 .actionGet(fessConfig.getIndexBulkTimeout());
689                 if (!scrollId.equals(response.getScrollId())) {
690                     deleteScrollContext(scrollId);
691                 }
692                 scrollId = response.getScrollId();
693             }
694         } finally {
695             deleteScrollContext(scrollId);
696         }
697         return count;
698     }
699 
700     public long deleteByQuery(final String index, final QueryBuilder queryBuilder) {
701 
702         final FessConfig fessConfig = ComponentUtil.getFessConfig();
703         SearchResponse response =
704                 client.prepareSearch(index).setScroll(scrollForDelete).setSize(sizeForDelete)
705                         .setFetchSource(new String[] { fessConfig.getIndexFieldId() }, null).setQuery(queryBuilder)
706                         .setPreference(Constants.SEARCH_PREFERENCE_LOCAL).execute().actionGet(fessConfig.getIndexScrollSearchTimeout());
707 
708         int count = 0;
709         String scrollId = response.getScrollId();
710         try {
711             while (scrollId != null) {
712                 final SearchHits searchHits = response.getHits();
713                 final SearchHit[] hits = searchHits.getHits();
714                 if (hits.length == 0) {
715                     break;
716                 }
717 
718                 final BulkRequestBuilder bulkRequest = client.prepareBulk();
719                 for (final SearchHit hit : hits) {
720                     bulkRequest.add(client.prepareDelete().setIndex(index).setId(hit.getId()));
721                     count++;
722                 }
723                 final BulkResponse bulkResponse = bulkRequest.execute().actionGet(fessConfig.getIndexBulkTimeout());
724                 if (bulkResponse.hasFailures()) {
725                     throw new IllegalBehaviorStateException(bulkResponse.buildFailureMessage());
726                 }
727 
728                 response =
729                         client.prepareSearchScroll(scrollId).setScroll(scrollForDelete).execute()
730                                 .actionGet(fessConfig.getIndexBulkTimeout());
731                 if (!scrollId.equals(response.getScrollId())) {
732                     deleteScrollContext(scrollId);
733                 }
734                 scrollId = response.getScrollId();
735             }
736         } finally {
737             deleteScrollContext(scrollId);
738         }
739         return count;
740     }
741 
742     protected void deleteScrollContext(final String scrollId) {
743         if (scrollId != null) {
744             client.prepareClearScroll().addScrollId(scrollId)
745                     .execute(ActionListener.wrap(res -> {}, e -> logger.warn("Failed to clear the scroll context.", e)));
746         }
747     }
748 
749     protected <T> T get(final String index, final String type, final String id, final SearchCondition<GetRequestBuilder> condition,
750             final SearchResult<T, GetRequestBuilder, GetResponse> searchResult) {
751         final long startTime = System.currentTimeMillis();
752 
753         GetResponse response = null;
754         final GetRequestBuilder requestBuilder = client.prepareGet(index, type, id);
755         if (condition.build(requestBuilder)) {
756             response = requestBuilder.execute().actionGet(ComponentUtil.getFessConfig().getIndexSearchTimeout());
757         }
758         final long execTime = System.currentTimeMillis() - startTime;
759 
760         return searchResult.build(requestBuilder, execTime, OptionalEntity.ofNullable(response, () -> {}));
761     }
762 
763     public <T> T search(final String index, final SearchCondition<SearchRequestBuilder> condition,
764             final SearchResult<T, SearchRequestBuilder, SearchResponse> searchResult) {
765         final long startTime = System.currentTimeMillis();
766 
767         SearchResponse searchResponse = null;
768         final SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
769         if (condition.build(searchRequestBuilder)) {
770 
771             final FessConfig fessConfig = ComponentUtil.getFessConfig();
772             final long queryTimeout = fessConfig.getQueryTimeoutAsInteger().longValue();
773             if (queryTimeout >= 0) {
774                 searchRequestBuilder.setTimeout(TimeValue.timeValueMillis(queryTimeout));
775             }
776 
777             try {
778                 if (logger.isDebugEnabled()) {
779                     logger.debug("Query DSL:\n" + searchRequestBuilder.toString());
780                 }
781                 searchResponse = searchRequestBuilder.execute().actionGet(ComponentUtil.getFessConfig().getIndexSearchTimeout());
782             } catch (final SearchPhaseExecutionException e) {
783                 throw new InvalidQueryException(messages -> messages.addErrorsInvalidQueryParseError(UserMessages.GLOBAL_PROPERTY_KEY),
784                         "Invalid query: " + searchRequestBuilder, e);
785             }
786         }
787         final long execTime = System.currentTimeMillis() - startTime;
788 
789         return searchResult.build(searchRequestBuilder, execTime, OptionalEntity.ofNullable(searchResponse, () -> {}));
790     }
791 
792     public <T> long scrollSearch(final String index, final SearchCondition<SearchRequestBuilder> condition,
793             final EntityCreator<T, SearchResponse, SearchHit> creator, final Function<T, Boolean> cursor) {
794         long count = 0;
795 
796         final SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index).setScroll(scrollForSearch);
797         if (condition.build(searchRequestBuilder)) {
798             final FessConfig fessConfig = ComponentUtil.getFessConfig();
799 
800             String scrollId = null;
801             try {
802                 if (logger.isDebugEnabled()) {
803                     logger.debug("Query DSL:\n" + searchRequestBuilder.toString());
804                 }
805                 SearchResponse response = searchRequestBuilder.execute().actionGet(ComponentUtil.getFessConfig().getIndexSearchTimeout());
806 
807                 scrollId = response.getScrollId();
808                 while (scrollId != null) {
809                     final SearchHits searchHits = response.getHits();
810                     final SearchHit[] hits = searchHits.getHits();
811                     if (hits.length == 0) {
812                         break;
813                     }
814 
815                     for (final SearchHit hit : hits) {
816                         count++;
817                         if (!cursor.apply(creator.build(response, hit))) {
818                             if (scrollId != null) {
819                                 client.prepareClearScroll().addScrollId(scrollId)
820                                         .execute(ActionListener.wrap(res -> {}, e1 -> logger.warn("Failed to clear scrollId.", e1)));
821                             }
822                             break;
823                         }
824                     }
825 
826                     response =
827                             client.prepareSearchScroll(scrollId).setScroll(scrollForDelete).execute()
828                                     .actionGet(fessConfig.getIndexBulkTimeout());
829                     scrollId = response.getScrollId();
830                 }
831             } catch (final SearchPhaseExecutionException e) {
832                 if (scrollId != null) {
833                     client.prepareClearScroll().addScrollId(scrollId)
834                             .execute(ActionListener.wrap(res -> {}, e1 -> logger.warn("Failed to clear scrollId.", e1)));
835                 }
836                 throw new InvalidQueryException(messages -> messages.addErrorsInvalidQueryParseError(UserMessages.GLOBAL_PROPERTY_KEY),
837                         "Invalid query: " + searchRequestBuilder, e);
838             }
839         }
840 
841         return count;
842     }
843 
844     public OptionalEntity<Map<String, Object>> getDocument(final String index, final SearchCondition<SearchRequestBuilder> condition) {
845         return getDocument(
846                 index,
847                 condition,
848                 (response, hit) -> {
849                     final FessConfig fessConfig = ComponentUtil.getFessConfig();
850                     final Map<String, Object> source = hit.getSourceAsMap();
851                     if (source != null) {
852                         final Map<String, Object> docMap = new HashMap<>(source);
853                         docMap.put(fessConfig.getIndexFieldId(), hit.getId());
854                         docMap.put(fessConfig.getIndexFieldVersion(), hit.getVersion());
855                         docMap.put(fessConfig.getIndexFieldSeqNo(), hit.getSeqNo());
856                         docMap.put(fessConfig.getIndexFieldPrimaryTerm(), hit.getPrimaryTerm());
857                         return docMap;
858                     }
859                     final Map<String, DocumentField> fields = hit.getFields();
860                     if (fields != null) {
861                         final Map<String, Object> docMap =
862                                 fields.entrySet().stream()
863                                         .collect(Collectors.toMap(e -> e.getKey(), e -> (Object) e.getValue().getValues()));
864                         docMap.put(fessConfig.getIndexFieldId(), hit.getId());
865                         docMap.put(fessConfig.getIndexFieldVersion(), hit.getVersion());
866                         docMap.put(fessConfig.getIndexFieldSeqNo(), hit.getSeqNo());
867                         docMap.put(fessConfig.getIndexFieldPrimaryTerm(), hit.getPrimaryTerm());
868                         return docMap;
869                     }
870                     return null;
871                 });
872     }
873 
874     protected <T> OptionalEntity<T> getDocument(final String index, final SearchCondition<SearchRequestBuilder> condition,
875             final EntityCreator<T, SearchResponse, SearchHit> creator) {
876         return search(index, searchRequestBuilder -> {
877             searchRequestBuilder.setVersion(true);
878             return condition.build(searchRequestBuilder);
879         }, (queryBuilder, execTime, searchResponse) -> {
880             return searchResponse.map(response -> {
881                 final SearchHit[] hits = response.getHits().getHits();
882                 if (hits.length > 0) {
883                     return creator.build(response, hits[0]);
884                 }
885                 return null;
886             });
887         });
888     }
889 
890     public List<Map<String, Object>> getDocumentList(final String index, final SearchCondition<SearchRequestBuilder> condition) {
891         return getDocumentList(
892                 index,
893                 condition,
894                 (response, hit) -> {
895                     final FessConfig fessConfig = ComponentUtil.getFessConfig();
896                     final Map<String, Object> source = hit.getSourceAsMap();
897                     if (source != null) {
898                         final Map<String, Object> docMap = new HashMap<>(source);
899                         docMap.put(fessConfig.getIndexFieldId(), hit.getId());
900                         return docMap;
901                     }
902                     final Map<String, DocumentField> fields = hit.getFields();
903                     if (fields != null) {
904                         final Map<String, Object> docMap =
905                                 fields.entrySet().stream()
906                                         .collect(Collectors.toMap(e -> e.getKey(), e -> (Object) e.getValue().getValues()));
907                         docMap.put(fessConfig.getIndexFieldId(), hit.getId());
908                         return docMap;
909                     }
910                     return null;
911                 });
912     }
913 
914     protected <T> List<T> getDocumentList(final String index, final SearchCondition<SearchRequestBuilder> condition,
915             final EntityCreator<T, SearchResponse, SearchHit> creator) {
916         return search(index, condition, (searchRequestBuilder, execTime, searchResponse) -> {
917             final List<T> list = new ArrayList<>();
918             searchResponse.ifPresent(response -> {
919                 response.getHits().forEach(hit -> {
920                     list.add(creator.build(response, hit));
921                 });
922             });
923             return list;
924         });
925     }
926 
927     public boolean update(final String index, final String id, final String field, final Object value) {
928         try {
929             final Result result =
930                     client.prepareUpdate().setIndex(index).setId(id).setDoc(field, value).execute()
931                             .actionGet(ComponentUtil.getFessConfig().getIndexIndexTimeout()).getResult();
932             return result == Result.CREATED || result == Result.UPDATED;
933         } catch (final ElasticsearchException e) {
934             throw new FessEsClientException("Failed to set " + value + " to " + field + " for doc " + id, e);
935         }
936     }
937 
938     public void refresh(final String... indices) {
939         client.admin().indices().prepareRefresh(indices).execute(new ActionListener<RefreshResponse>() {
940             @Override
941             public void onResponse(final RefreshResponse response) {
942                 if (logger.isDebugEnabled()) {
943                     logger.debug("Refreshed " + stream(indices).get(stream -> stream.collect(Collectors.joining(", "))) + ".");
944                 }
945             }
946 
947             @Override
948             public void onFailure(final Exception e) {
949                 logger.error("Failed to refresh " + stream(indices).get(stream -> stream.collect(Collectors.joining(", "))) + ".", e);
950             }
951         });
952 
953     }
954 
955     public void flush(final String... indices) {
956         client.admin().indices().prepareFlush(indices).execute(new ActionListener<FlushResponse>() {
957 
958             @Override
959             public void onResponse(final FlushResponse response) {
960                 if (logger.isDebugEnabled()) {
961                     logger.debug("Flushed " + stream(indices).get(stream -> stream.collect(Collectors.joining(", "))) + ".");
962                 }
963             }
964 
965             @Override
966             public void onFailure(final Exception e) {
967                 logger.error("Failed to flush " + stream(indices).get(stream -> stream.collect(Collectors.joining(", "))) + ".", e);
968             }
969         });
970 
971     }
972 
973     public PingResponse ping() {
974         try {
975             final ClusterHealthResponse response =
976                     client.admin().cluster().prepareHealth().execute().actionGet(ComponentUtil.getFessConfig().getIndexHealthTimeout());
977             return new PingResponse(response);
978         } catch (final ElasticsearchException e) {
979             throw new FessEsClientException("Failed to process a ping request.", e);
980         }
981     }
982 
983     public void addAll(final String index, final List<Map<String, Object>> docList,
984             final BiConsumer<Map<String, Object>, IndexRequestBuilder> options) {
985         final FessConfig fessConfig = ComponentUtil.getFessConfig();
986         final BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
987         for (final Map<String, Object> doc : docList) {
988             final Object id = doc.remove(fessConfig.getIndexFieldId());
989             final IndexRequestBuilder builder = client.prepareIndex().setIndex(index).setId(id.toString()).setSource(new DocMap(doc));
990             options.accept(doc, builder);
991             bulkRequestBuilder.add(builder);
992         }
993         final BulkResponse response = bulkRequestBuilder.execute().actionGet(ComponentUtil.getFessConfig().getIndexBulkTimeout());
994         if (response.hasFailures()) {
995             if (logger.isDebugEnabled()) {
996                 final List<DocWriteRequest<?>> requests = bulkRequestBuilder.request().requests();
997                 final BulkItemResponse[] items = response.getItems();
998                 if (requests.size() == items.length) {
999                     for (int i = 0; i < requests.size(); i++) {
1000                         final BulkItemResponse resp = items[i];
1001                         if (resp.isFailed() && resp.getFailure() != null) {
1002                             final DocWriteRequest<?> req = requests.get(i);
1003                             final Failure failure = resp.getFailure();
1004                             logger.debug("Failed Request: " + req + "\n=>" + failure.getMessage());
1005                         }
1006                     }
1007                 }
1008             }
1009             throw new FessEsClientException(response.buildFailureMessage());
1010         }
1011     }
1012 
1013     public static class SearchConditionBuilder {
1014         private final SearchRequestBuilder searchRequestBuilder;
1015         private String query;
1016         private String[] responseFields;
1017         private int offset = Constants.DEFAULT_START_COUNT;
1018         private int size = Constants.DEFAULT_PAGE_SIZE;
1019         private GeoInfo geoInfo;
1020         private FacetInfo facetInfo;
1021         private HighlightInfo highlightInfo;
1022         private String similarDocHash;
1023         private SearchRequestType searchRequestType = SearchRequestType.SEARCH;
1024         private boolean isScroll = false;
1025 
1026         public static SearchConditionBuilder builder(final SearchRequestBuilder searchRequestBuilder) {
1027             return new SearchConditionBuilder(searchRequestBuilder);
1028         }
1029 
1030         SearchConditionBuilder(final SearchRequestBuilder searchRequestBuilder) {
1031             this.searchRequestBuilder = searchRequestBuilder;
1032         }
1033 
1034         public Map<String, Object> condition() {
1035             final Map<String, Object> params = new HashMap<>();
1036             params.put("query", query);
1037             params.put("responseFields", responseFields);
1038             params.put("offset", offset);
1039             params.put("size", size);
1040             // TODO support rescorer(convert to map)
1041             // params.put("geoInfo", geoInfo);
1042             // params.put("facetInfo", facetInfo);
1043             params.put("similarDocHash", similarDocHash);
1044             return params;
1045         }
1046 
1047         public SearchConditionBuilder query(final String query) {
1048             this.query = query;
1049             return this;
1050         }
1051 
1052         public SearchConditionBuilder searchRequestType(final SearchRequestType searchRequestType) {
1053             this.searchRequestType = searchRequestType;
1054             return this;
1055         }
1056 
1057         public SearchConditionBuilder responseFields(final String[] responseFields) {
1058             this.responseFields = responseFields;
1059             return this;
1060         }
1061 
1062         public SearchConditionBuilder offset(final int offset) {
1063             this.offset = offset;
1064             return this;
1065         }
1066 
1067         public SearchConditionBuilder size(final int size) {
1068             this.size = size;
1069             return this;
1070         }
1071 
1072         public SearchConditionBuilder geoInfo(final GeoInfo geoInfo) {
1073             this.geoInfo = geoInfo;
1074             return this;
1075         }
1076 
1077         public SearchConditionBuilder highlightInfo(final HighlightInfo highlightInfo) {
1078             this.highlightInfo = highlightInfo;
1079             return this;
1080         }
1081 
1082         public SearchConditionBuilder similarDocHash(final String similarDocHash) {
1083             if (StringUtil.isNotBlank(similarDocHash)) {
1084                 this.similarDocHash = similarDocHash;
1085             }
1086             return this;
1087         }
1088 
1089         public SearchConditionBuilder facetInfo(final FacetInfo facetInfo) {
1090             this.facetInfo = facetInfo;
1091             return this;
1092         }
1093 
1094         public SearchConditionBuilder scroll() {
1095             this.isScroll = true;
1096             return this;
1097         }
1098 
1099         public boolean build() {
1100             if (StringUtil.isBlank(query)) {
1101                 return false;
1102             }
1103 
1104             final QueryHelper queryHelper = ComponentUtil.getQueryHelper();
1105             final FessConfig fessConfig = ComponentUtil.getFessConfig();
1106 
1107             if (offset > fessConfig.getQueryMaxSearchResultOffsetAsInteger()) {
1108                 throw new ResultOffsetExceededException("The number of result size is exceeded.");
1109             }
1110 
1111             final QueryContext queryContext =
1112                     queryHelper.build(searchRequestType, query, context -> {
1113                         if (SearchRequestType.ADMIN_SEARCH.equals(searchRequestType)) {
1114                             context.skipRoleQuery();
1115                         } else if (similarDocHash != null) {
1116                             final DocumentHelper documentHelper = ComponentUtil.getDocumentHelper();
1117                             context.addQuery(boolQuery -> {
1118                                 boolQuery.filter(QueryBuilders.termQuery(fessConfig.getIndexFieldContentMinhashBits(),
1119                                         documentHelper.decodeSimilarDocHash(similarDocHash)));
1120                             });
1121                         }
1122 
1123                         if (geoInfo != null && geoInfo.toQueryBuilder() != null) {
1124                             context.addQuery(boolQuery -> {
1125                                 boolQuery.filter(geoInfo.toQueryBuilder());
1126                             });
1127                         }
1128                     });
1129 
1130             searchRequestBuilder.setFrom(offset).setSize(size);
1131 
1132             final Object trackTotalHitsValue = fessConfig.getQueryTrackTotalHitsValue();
1133             if (trackTotalHitsValue instanceof Boolean) {
1134                 searchRequestBuilder.setTrackTotalHits((Boolean) trackTotalHitsValue);
1135             } else if (trackTotalHitsValue instanceof Number) {
1136                 searchRequestBuilder.setTrackTotalHitsUpTo(((Number) trackTotalHitsValue).intValue());
1137             }
1138 
1139             if (responseFields != null) {
1140                 searchRequestBuilder.setFetchSource(responseFields, null);
1141             }
1142 
1143             // rescorer
1144             stream(queryHelper.getRescorers(condition())).of(stream -> stream.forEach(searchRequestBuilder::addRescorer));
1145 
1146             // sort
1147             queryContext.sortBuilders().forEach(sortBuilder -> searchRequestBuilder.addSort(sortBuilder));
1148 
1149             // highlighting
1150             if (highlightInfo != null) {
1151                 final HighlightBuilder highlightBuilder = new HighlightBuilder();
1152                 queryHelper.highlightedFields(stream -> stream.forEach(hf -> highlightBuilder.field(new HighlightBuilder.Field(hf)
1153                         .highlighterType(highlightInfo.getType()).fragmentSize(highlightInfo.getFragmentSize())
1154                         .numOfFragments(highlightInfo.getNumOfFragments()))));
1155                 searchRequestBuilder.highlighter(highlightBuilder);
1156             }
1157 
1158             // facets
1159             if (facetInfo != null) {
1160                 stream(facetInfo.field).of(
1161                         stream -> stream.forEach(f -> {
1162                             if (queryHelper.isFacetField(f)) {
1163                                 final String encodedField = BaseEncoding.base64().encode(f.getBytes(StandardCharsets.UTF_8));
1164                                 final TermsAggregationBuilder termsBuilder =
1165                                         AggregationBuilders.terms(Constants.FACET_FIELD_PREFIX + encodedField).field(f);
1166                                 termsBuilder.order(facetInfo.getBucketOrder());
1167                                 if (facetInfo.size != null) {
1168                                     termsBuilder.size(facetInfo.size);
1169                                 }
1170                                 if (facetInfo.minDocCount != null) {
1171                                     termsBuilder.minDocCount(facetInfo.minDocCount);
1172                                 }
1173                                 if (facetInfo.missing != null) {
1174                                     termsBuilder.missing(facetInfo.missing);
1175                                 }
1176                                 searchRequestBuilder.addAggregation(termsBuilder);
1177                             } else {
1178                                 throw new SearchQueryException("Invalid facet field: " + f);
1179                             }
1180                         }));
1181                 stream(facetInfo.query).of(
1182                         stream -> stream.forEach(fq -> {
1183                             final QueryContext.html#QueryContext">QueryContext facetContext = new QueryContext(fq, false);
1184                             queryHelper.buildBaseQuery(facetContext, c -> {});
1185                             final String encodedFacetQuery = BaseEncoding.base64().encode(fq.getBytes(StandardCharsets.UTF_8));
1186                             final FilterAggregationBuilder filterBuilder =
1187                                     AggregationBuilders.filter(Constants.FACET_QUERY_PREFIX + encodedFacetQuery,
1188                                             facetContext.getQueryBuilder());
1189                             searchRequestBuilder.addAggregation(filterBuilder);
1190                         }));
1191             }
1192 
1193             if (!SearchRequestType.ADMIN_SEARCH.equals(searchRequestType) && !isScroll && fessConfig.isResultCollapsed()
1194                     && similarDocHash == null) {
1195                 searchRequestBuilder.setCollapse(getCollapseBuilder(fessConfig));
1196             }
1197 
1198             searchRequestBuilder.setQuery(queryContext.getQueryBuilder());
1199             return true;
1200         }
1201 
1202         protected CollapseBuilder getCollapseBuilder(final FessConfig fessConfig) {
1203             final InnerHitBuilder innerHitBuilder =
1204                     new InnerHitBuilder().setName(fessConfig.getQueryCollapseInnerHitsName()).setSize(
1205                             fessConfig.getQueryCollapseInnerHitsSizeAsInteger());
1206             fessConfig.getQueryCollapseInnerHitsSortBuilders().ifPresent(
1207                     builders -> stream(builders).of(stream -> stream.forEach(innerHitBuilder::addSort)));
1208             return new CollapseBuilder(fessConfig.getIndexFieldContentMinhashBits()).setMaxConcurrentGroupRequests(
1209                     fessConfig.getQueryCollapseMaxConcurrentGroupResultsAsInteger()).setInnerHits(innerHitBuilder);
1210         }
1211     }
1212 
1213     public boolean store(final String index, final Object obj) {
1214         final FessConfig fessConfig = ComponentUtil.getFessConfig();
1215         @SuppressWarnings("unchecked")
1216         final Map<String, Object> source = obj instanceof Map ? (Map<String, Object>) obj : BeanUtil.copyBeanToNewMap(obj);
1217         final String id = (String) source.remove(fessConfig.getIndexFieldId());
1218         source.remove(fessConfig.getIndexFieldVersion());
1219         final Number seqNo = (Number) source.remove(fessConfig.getIndexFieldSeqNo());
1220         final Number primaryTerm = (Number) source.remove(fessConfig.getIndexFieldPrimaryTerm());
1221         IndexResponse response;
1222         try {
1223             if (id == null) {
1224                 // TODO throw Exception in next release
1225                 // create
1226                 response =
1227                         client.prepareIndex().setIndex(index).setSource(new DocMap(source)).setRefreshPolicy(RefreshPolicy.IMMEDIATE)
1228                                 .setOpType(OpType.CREATE).execute().actionGet(fessConfig.getIndexIndexTimeout());
1229             } else {
1230                 // create or update
1231                 final IndexRequestBuilder builder =
1232                         client.prepareIndex().setIndex(index).setId(id).setSource(new DocMap(source))
1233                                 .setRefreshPolicy(RefreshPolicy.IMMEDIATE).setOpType(OpType.INDEX);
1234                 if (seqNo != null) {
1235                     builder.setIfSeqNo(seqNo.longValue());
1236                 }
1237                 if (primaryTerm != null) {
1238                     builder.setIfPrimaryTerm(primaryTerm.longValue());
1239                 }
1240                 response = builder.execute().actionGet(fessConfig.getIndexIndexTimeout());
1241             }
1242             final Result result = response.getResult();
1243             return result == Result.CREATED || result == Result.UPDATED;
1244         } catch (final ElasticsearchException e) {
1245             throw new FessEsClientException("Failed to store: " + obj, e);
1246         }
1247     }
1248 
1249     public boolean delete(final String index, final String id) {
1250         return delete(index, id, null, null);
1251     }
1252 
1253     public boolean delete(final String index, final String id, final Number seqNo, final Number primaryTerm) {
1254         try {
1255             final DeleteRequestBuilder builder = client.prepareDelete().setIndex(index).setId(id).setRefreshPolicy(RefreshPolicy.IMMEDIATE);
1256             if (seqNo != null) {
1257                 builder.setIfSeqNo(seqNo.longValue());
1258             }
1259             if (primaryTerm != null) {
1260                 builder.setIfPrimaryTerm(primaryTerm.longValue());
1261             }
1262             final DeleteResponse response = builder.execute().actionGet(ComponentUtil.getFessConfig().getIndexDeleteTimeout());
1263             return response.getResult() == Result.DELETED;
1264         } catch (final ElasticsearchException e) {
1265             throw new FessEsClientException("Failed to delete: " + index + "/" + id + "@" + seqNo + ":" + primaryTerm, e);
1266         }
1267     }
1268 
1269     public void setIndexConfigPath(final String indexConfigPath) {
1270         this.indexConfigPath = indexConfigPath;
1271     }
1272 
1273     public interface SearchCondition<B> {
1274         boolean build(B requestBuilder);
1275     }
1276 
1277     public interface SearchResult<T, B, R> {
1278         T build(B requestBuilder, long execTime, OptionalEntity<R> response);
1279     }
1280 
1281     public interface EntityCreator<T, R, H> {
1282         T build(R response, H hit);
1283     }
1284 
1285     public void setClusterName(final String clusterName) {
1286         this.clusterName = clusterName;
1287     }
1288 
1289     //
1290     // Elasticsearch Client
1291     //
1292 
1293     @Override
1294     public ThreadPool threadPool() {
1295         return client.threadPool();
1296     }
1297 
1298     @Override
1299     public AdminClient admin() {
1300         return client.admin();
1301     }
1302 
1303     @Override
1304     public ActionFuture<IndexResponse> index(final IndexRequest request) {
1305         return client.index(request);
1306     }
1307 
1308     @Override
1309     public void index(final IndexRequest request, final ActionListener<IndexResponse> listener) {
1310         client.index(request, listener);
1311     }
1312 
1313     @Override
1314     public IndexRequestBuilder prepareIndex() {
1315         return client.prepareIndex();
1316     }
1317 
1318     @Override
1319     public ActionFuture<UpdateResponse> update(final UpdateRequest request) {
1320         return client.update(request);
1321     }
1322 
1323     @Override
1324     public void update(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
1325         client.update(request, listener);
1326     }
1327 
1328     @Override
1329     public UpdateRequestBuilder prepareUpdate() {
1330         return client.prepareUpdate();
1331     }
1332 
1333     @Override
1334     public UpdateRequestBuilder prepareUpdate(final String index, final String type, final String id) {
1335         return client.prepareUpdate(index, type, id);
1336     }
1337 
1338     @Override
1339     public IndexRequestBuilder prepareIndex(final String index, final String type) {
1340         return client.prepareIndex(index, type);
1341     }
1342 
1343     @Override
1344     public IndexRequestBuilder prepareIndex(final String index, final String type, final String id) {
1345         return client.prepareIndex(index, type, id);
1346     }
1347 
1348     @Override
1349     public ActionFuture<DeleteResponse> delete(final DeleteRequest request) {
1350         return client.delete(request);
1351     }
1352 
1353     @Override
1354     public void delete(final DeleteRequest request, final ActionListener<DeleteResponse> listener) {
1355         client.delete(request, listener);
1356     }
1357 
1358     @Override
1359     public DeleteRequestBuilder prepareDelete() {
1360         return client.prepareDelete();
1361     }
1362 
1363     @Override
1364     public DeleteRequestBuilder prepareDelete(final String index, final String type, final String id) {
1365         return client.prepareDelete(index, type, id);
1366     }
1367 
1368     @Override
1369     public ActionFuture<BulkResponse> bulk(final BulkRequest request) {
1370         return client.bulk(request);
1371     }
1372 
1373     @Override
1374     public void bulk(final BulkRequest request, final ActionListener<BulkResponse> listener) {
1375         client.bulk(request, listener);
1376     }
1377 
1378     @Override
1379     public BulkRequestBuilder prepareBulk() {
1380         return client.prepareBulk();
1381     }
1382 
1383     @Override
1384     public ActionFuture<GetResponse> get(final GetRequest request) {
1385         return client.get(request);
1386     }
1387 
1388     @Override
1389     public void get(final GetRequest request, final ActionListener<GetResponse> listener) {
1390         client.get(request, listener);
1391     }
1392 
1393     @Override
1394     public GetRequestBuilder prepareGet() {
1395         return client.prepareGet();
1396     }
1397 
1398     @Override
1399     public GetRequestBuilder prepareGet(final String index, final String type, final String id) {
1400         return client.prepareGet(index, type, id);
1401     }
1402 
1403     @Override
1404     public ActionFuture<MultiGetResponse> multiGet(final MultiGetRequest request) {
1405         return client.multiGet(request);
1406     }
1407 
1408     @Override
1409     public void multiGet(final MultiGetRequest request, final ActionListener<MultiGetResponse> listener) {
1410         client.multiGet(request, listener);
1411     }
1412 
1413     @Override
1414     public MultiGetRequestBuilder prepareMultiGet() {
1415         return client.prepareMultiGet();
1416     }
1417 
1418     @Override
1419     public ActionFuture<SearchResponse> search(final SearchRequest request) {
1420         return client.search(request);
1421     }
1422 
1423     @Override
1424     public void search(final SearchRequest request, final ActionListener<SearchResponse> listener) {
1425         client.search(request, listener);
1426     }
1427 
1428     @Override
1429     public SearchRequestBuilder prepareSearch(final String... indices) {
1430         return client.prepareSearch(indices);
1431     }
1432 
1433     @Override
1434     public ActionFuture<SearchResponse> searchScroll(final SearchScrollRequest request) {
1435         return client.searchScroll(request);
1436     }
1437 
1438     @Override
1439     public void searchScroll(final SearchScrollRequest request, final ActionListener<SearchResponse> listener) {
1440         client.searchScroll(request, listener);
1441     }
1442 
1443     @Override
1444     public SearchScrollRequestBuilder prepareSearchScroll(final String scrollId) {
1445         return client.prepareSearchScroll(scrollId);
1446     }
1447 
1448     @Override
1449     public ActionFuture<MultiSearchResponse> multiSearch(final MultiSearchRequest request) {
1450         return client.multiSearch(request);
1451     }
1452 
1453     @Override
1454     public void multiSearch(final MultiSearchRequest request, final ActionListener<MultiSearchResponse> listener) {
1455         client.multiSearch(request, listener);
1456     }
1457 
1458     @Override
1459     public MultiSearchRequestBuilder prepareMultiSearch() {
1460         return client.prepareMultiSearch();
1461     }
1462 
1463     @Override
1464     public ExplainRequestBuilder prepareExplain(final String index, final String type, final String id) {
1465         return client.prepareExplain(index, type, id);
1466     }
1467 
1468     @Override
1469     public ActionFuture<ExplainResponse> explain(final ExplainRequest request) {
1470         return client.explain(request);
1471     }
1472 
1473     @Override
1474     public void explain(final ExplainRequest request, final ActionListener<ExplainResponse> listener) {
1475         client.explain(request, listener);
1476     }
1477 
1478     @Override
1479     public ClearScrollRequestBuilder prepareClearScroll() {
1480         return client.prepareClearScroll();
1481     }
1482 
1483     @Override
1484     public ActionFuture<ClearScrollResponse> clearScroll(final ClearScrollRequest request) {
1485         return client.clearScroll(request);
1486     }
1487 
1488     @Override
1489     public void clearScroll(final ClearScrollRequest request, final ActionListener<ClearScrollResponse> listener) {
1490         client.clearScroll(request, listener);
1491     }
1492 
1493     @Override
1494     public Settings settings() {
1495         return client.settings();
1496     }
1497 
1498     @Override
1499     public ActionFuture<TermVectorsResponse> termVectors(final TermVectorsRequest request) {
1500         return client.termVectors(request);
1501     }
1502 
1503     @Override
1504     public void termVectors(final TermVectorsRequest request, final ActionListener<TermVectorsResponse> listener) {
1505         client.termVectors(request, listener);
1506     }
1507 
1508     @Override
1509     public TermVectorsRequestBuilder prepareTermVectors() {
1510         return client.prepareTermVectors();
1511     }
1512 
1513     @Override
1514     public TermVectorsRequestBuilder prepareTermVectors(final String index, final String type, final String id) {
1515         return client.prepareTermVectors(index, type, id);
1516     }
1517 
1518     @Override
1519     public ActionFuture<MultiTermVectorsResponse> multiTermVectors(final MultiTermVectorsRequest request) {
1520         return client.multiTermVectors(request);
1521     }
1522 
1523     @Override
1524     public void multiTermVectors(final MultiTermVectorsRequest request, final ActionListener<MultiTermVectorsResponse> listener) {
1525         client.multiTermVectors(request, listener);
1526     }
1527 
1528     @Override
1529     public MultiTermVectorsRequestBuilder prepareMultiTermVectors() {
1530         return client.prepareMultiTermVectors();
1531     }
1532 
1533     public void setSizeForUpdate(final int sizeForUpdate) {
1534         this.sizeForUpdate = sizeForUpdate;
1535     }
1536 
1537     public void setScrollForUpdate(final String scrollForUpdate) {
1538         this.scrollForUpdate = scrollForUpdate;
1539     }
1540 
1541     public void setSizeForDelete(final int sizeForDelete) {
1542         this.sizeForDelete = sizeForDelete;
1543     }
1544 
1545     public void setScrollForDelete(final String scrollForDelete) {
1546         this.scrollForDelete = scrollForDelete;
1547     }
1548 
1549     public void setScrollForSearch(final String scrollForSearch) {
1550         this.scrollForSearch = scrollForSearch;
1551     }
1552 
1553     public void setMaxConfigSyncStatusRetry(final int maxConfigSyncStatusRetry) {
1554         this.maxConfigSyncStatusRetry = maxConfigSyncStatusRetry;
1555     }
1556 
1557     public void setMaxEsStatusRetry(final int maxEsStatusRetry) {
1558         this.maxEsStatusRetry = maxEsStatusRetry;
1559     }
1560 
1561     @Override
1562     public Client filterWithHeader(final Map<String, String> headers) {
1563         return client.filterWithHeader(headers);
1564     }
1565 
1566     @Override
1567     public <Request extends ActionRequest, Response extends ActionResponse> ActionFuture<Response> execute(final Action<Response> action,
1568             final Request request) {
1569         return client.execute(action, request);
1570     }
1571 
1572     @Override
1573     public <Request extends ActionRequest, Response extends ActionResponse> void execute(final Action<Response> action,
1574             final Request request, final ActionListener<Response> listener) {
1575         client.execute(action, request, listener);
1576     }
1577 
1578     @Override
1579     public FieldCapabilitiesRequestBuilder prepareFieldCaps(final String... indices) {
1580         return client.prepareFieldCaps(indices);
1581     }
1582 
1583     @Override
1584     public ActionFuture<FieldCapabilitiesResponse> fieldCaps(final FieldCapabilitiesRequest request) {
1585         return client.fieldCaps(request);
1586     }
1587 
1588     @Override
1589     public void fieldCaps(final FieldCapabilitiesRequest request, final ActionListener<FieldCapabilitiesResponse> listener) {
1590         client.fieldCaps(request, listener);
1591     }
1592 
1593     @Override
1594     public BulkRequestBuilder prepareBulk(final String globalIndex, final String globalType) {
1595         return client.prepareBulk(globalIndex, globalType);
1596     }
1597 }