ElasticSearch5在Ubuntu系統下的安裝和Java調用


  ElasticSearch是開源搜索平台的新成員,實時數據分析的神器。可以理解為作為搜索的數據庫,可以提供搜索功能。對比關系型數據庫,具有以下的相似關系:

關系型數據庫 數據庫
ElasticSearch 索引 類型 文檔 字段

  一個ES集群可以包含多個索引(數據庫),每個索引又包含了很多類型(表),類型中包含了很多文檔(行),每個文檔又包含了很多字段(列)。

  如果要實現對關系型數據庫數據的搜索功能,需要將關系型數據庫中的數據導入到ElasticSearch中,網上有解決方案。但是好像不支持最新的ElasticSearch5,可以使用我下面的Java代碼實現數據的導入。

Ubuntu系統安裝 Elasticsearch5

升級系統后安裝 Oracle Java 7,既然 Elasticsearch 官方推薦使用 Oracle JDK 7 就不要嘗試 JDK 8 和 OpenJDK 了:

1 $ sudo apt-get update 2 $ sudo apt-get upgrade 3 4 $ sudo apt-get install software-properties-common 5 $ sudo add-apt-repository ppa:webupd8team/java 6 $ sudo apt-get update 7 8 $ sudo apt-get install oracle-java7-installer

加入 Elasticsearch 官方源后安裝 elasticsearch:

1 $ wget -O - http://packages.elasticsearch.org/GPG-KEY-elasticsearch | apt-key add - 2 $ sudo echo "deb http://packages.elasticsearch.org/elasticsearch/1.1/debian stable main" >> /etc/apt/sources.list 3 4 $ sudo apt-get update 5 $ sudo apt-get install elasticsearch

加入到系統啟動文件並啟動 elasticsearch 服務,用 curl 測試一下安裝是否成功:

 1 $ sudo update-rc.d elasticsearch defaults 95 1  2  3 $ sudo /etc/init.d/elasticsearch start  4  5 $ curl -X GET 'http://localhost:9200'  6 {  7 "status" : 200,  8 "name" : "Fer-de-Lance",  9 "version" : { 10 "number" : "1.1.1", 11 "build_hash" : "f1585f096d3f3985e73456debdc1a0745f512bbc", 12 "build_timestamp" : "2014-04-16T14:27:12Z", 13 "build_snapshot" : false, 14 "lucene_version" : "4.7" 15  }, 16 "tagline" : "You Know, for Search" 17 }

Elasticsearch 的集群和數據管理界面 Marvel 非常贊,可惜只對開發環境免費,安裝很簡單,完成后重啟服務訪問 http://192.168.2.172:9200/_plugin/marvel/ 就可以看到界面:

1 $ sudo /usr/share/elasticsearch/bin/plugin -i elasticsearch/marvel/latest 2 3 $ sudo /etc/init.d/elasticsearch restart 4 * Stopping Elasticsearch Server [ OK ] 5 * Starting Elasticsearch Server [ OK ]

另外可以安裝elasticsearch-head作為管理Elasticsearch的web前端插件。

安裝教程:Elasticsearch5中安裝Elasticsearch-head插件

ElasticSearch Java調用

   命令調用的方式不再講述了,網上很多。ElasticSearch最終是要在項目中使用的。官方的API文檔:https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html

 自己寫了助手類,方便大家調用。可以實現索引的增刪改查,查詢提供多種方法,包括or、and查詢,多個關鍵詞查詢,關鍵詞高亮等,適用於不同場合。

首先是引用需要的jar包。使用maven管理jar包,需要的jar包有:

 1         <dependency>  2 <groupId>org.elasticsearch</groupId>  3 <artifactId>elasticsearch</artifactId>  4 <version>5.3.1</version>  5 </dependency>  6 <dependency>  7 <groupId>org.elasticsearch.client</groupId>  8 <artifactId>transport</artifactId>  9 <version>5.3.1</version> 10 </dependency> 11 <dependency> 12 <groupId>org.apache.logging.log4j</groupId> 13 <artifactId>log4j-api</artifactId> 14 <version>2.7</version> 15 </dependency> 16 <dependency> 17 <groupId>org.apache.logging.log4j</groupId> 18 <artifactId>log4j-core</artifactId> 19 <version>2.7</version> 20 </dependency>

 

然后是ElasticSearch配置文件,存儲集群名稱、集群IP、索引名稱。配置文件命名為:elasticsearch.properties

cluster_name=elasticsearch
cluster_serverip=127.0.0.1
indexname=blogsystem

 

還需要配置日志配置文件,命名為:log4j2.properties

appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout

rootLogger.level = info
rootLogger.appenderRef.console.ref = console

 

最后是java的實現ElasticSearch助手類。為了方便使用,助手類分為具體實現和調用兩個類。

ElasticSearch具體實現類:ElasticSearchUtilsImp.java

  1 package com.blog.utils;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.lang.reflect.Method;
  6 import java.net.InetAddress;
  7 import java.net.UnknownHostException;
  8 import java.util.ArrayList;
  9 import java.util.HashMap;
 10 import java.util.List;
 11 import java.util.Map;
 12 import java.util.Properties;
 13 import java.util.concurrent.ExecutionException;
 14 
 15 import org.elasticsearch.action.delete.DeleteResponse;
 16 import org.elasticsearch.action.index.IndexResponse;
 17 import org.elasticsearch.action.search.SearchRequestBuilder;
 18 import org.elasticsearch.action.search.SearchResponse;
 19 import org.elasticsearch.action.update.UpdateRequest;
 20 import org.elasticsearch.client.transport.TransportClient;
 21 import org.elasticsearch.common.settings.Settings;
 22 import org.elasticsearch.common.text.Text;
 23 import org.elasticsearch.common.transport.InetSocketTransportAddress;
 24 import org.elasticsearch.common.xcontent.XContentBuilder;
 25 import org.elasticsearch.common.xcontent.XContentFactory;
 26 import org.elasticsearch.index.query.BoolQueryBuilder;
 27 import org.elasticsearch.index.query.QueryBuilder;
 28 import org.elasticsearch.index.query.QueryBuilders;
 29 import org.elasticsearch.rest.RestStatus;
 30 import org.elasticsearch.search.SearchHits;
 31 import org.elasticsearch.search.aggregations.AggregationBuilders;
 32 import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
 33 import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
 34 import org.elasticsearch.transport.client.PreBuiltTransportClient;
 35 
 36 /**
 37  * @author:Tim
 38  * @date:2017年5月3日 下午8:24:22
 39  * @description:ElasticSearch助手類具體實現
 40  */
 41 public class ElasticSearchUtilsImp {
 42 
 43     private static String cluster_name = null;// 實例名稱
 44     private static String cluster_serverip = null;// elasticSearch服務器ip
 45     private static String indexname = null;// 索引名稱
 46 
 47     static {
 48         try {
 49             // 讀取db.properties文件
 50             Properties props = new Properties();
 51             InputStream in = ElasticSearchUtilsImp.class.getResourceAsStream("/elasticsearch.properties");
 52             props.load(in);// 加載文件
 53 
 54             // 讀取信息
 55             cluster_name = props.getProperty("cluster_name");
 56             cluster_serverip = props.getProperty("cluster_serverip");
 57             indexname = props.getProperty("indexname");
 58         } catch (IOException e) {
 59             e.printStackTrace();
 60             System.out.println("加載數據庫配置文件出錯!");
 61         }
 62     }
 63 
 64     /**
 65      * 返回一個到ElasticSearch的連接客戶端
 66      * 
 67      * @return
 68      */
 69     private static TransportClient getClient() {
 70         Settings settings = Settings.builder().put("cluster.name", cluster_name).build();// 設置集群名稱
 71         @SuppressWarnings("unchecked")
 72         TransportClient client = new PreBuiltTransportClient(settings);// 創建client
 73         try {
 74             client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(cluster_serverip), 9300));// 增加地址和端口
 75         } catch (UnknownHostException e) {
 76             e.printStackTrace();
 77             System.out.println("ElasticSearch連接失敗!");
 78         }
 79 
 80         return client;
 81     }
 82 
 83     /**
 84      * 將Map轉換成builder
 85      * 
 86      * @param mapParam
 87      * @return
 88      * @throws Exception
 89      */
 90     private static XContentBuilder createMapJson(Map<String, String> mapParam) throws Exception {
 91         XContentBuilder source = XContentFactory.jsonBuilder().startObject();
 92 
 93         for (Map.Entry<String, String> entry : mapParam.entrySet()) {
 94             source.field(entry.getKey(), entry.getValue());
 95         }
 96 
 97         source.endObject();
 98 
 99         return source;
100     }
101 
102     /**
103      * 將實體轉換成json
104      * 
105      * @param entity 實體
106      * @param fieldNameParm 實體中待轉換成json的字段
107      * @return 返回json
108      * @throws Exception
109      */
110     private static XContentBuilder createEntityJson(Object entity, String... methodNameParm) throws Exception {
111         // 創建json對象, 其中一個創建json的方式
112         XContentBuilder source = XContentFactory.jsonBuilder().startObject();
113 
114         try {
115             for (String methodName : methodNameParm) {
116 
117                 if (!methodName.startsWith("get")) {
118                     throw new Exception("不是有效的屬性!");
119                 }
120 
121                 Method method = entity.getClass().getMethod(methodName, null);
122                 String fieldValue = (String) method.invoke(entity, null);
123                 String fieldName = StringUtils.toLowerCaseFirstOne(methodName.replace("get", ""));// 去掉“get”,並將首字母小寫
124 
125                 // 避免和elasticSearch中id字段重復
126                 if (fieldName == "_id") {
127                     fieldName = "id";
128                 }
129 
130                 source.field(fieldName, fieldValue);
131             }
132         } catch (NoSuchMethodException e) {
133             e.printStackTrace();
134             System.out.println("未找到方法!");
135         }
136 
137         source.endObject();
138 
139         return source;
140     }
141 
142     /**
143      * 將一個Map格式的數據(key,value)插入索引 (私有方法)
144      * 
145      * @param type 類型(對應數據庫表)
146      * @param docId id,對應elasticSearch中的_id字段
147      * @param mapParam Map格式的數據
148      * @return
149      */
150     public static boolean addMapDocToIndex(String type, String docId, Map<String, String> mapParam) {
151         boolean result = false;
152 
153         TransportClient client = getClient();
154         XContentBuilder source = null;
155         try {
156             source = createMapJson(mapParam);
157         } catch (Exception e) {
158             e.printStackTrace();
159         }
160 
161         // 存json入索引中
162         IndexResponse response = null;
163         if (docId == null) {
164             // 使用默認的id
165             response = client.prepareIndex(indexname, type).setSource(source).get();
166         } else {
167             response = client.prepareIndex(indexname, type, docId).setSource(source).get();
168         }
169 
170         // 插入結果獲取
171         String index = response.getIndex();
172         String gettype = response.getType();
173         String id = response.getId();
174         long version = response.getVersion();
175         RestStatus status = response.status();
176 
177         String strResult = "新增文檔成功:" + index + " : " + gettype + ": " + id + ": " + version + ": " + status.getStatus();
178         System.out.println(strResult);
179 
180         if (status.getStatus() == 201) {
181             result = true;
182         }
183 
184         // 關閉client
185         client.close();
186 
187         return result;
188     }
189 
190     /**
191      * 將一個實體存入到默認索引的類型中(指定_id,一般是業務數據的id,及elasticSearch和關系型數據使用同一個id,方便同關系型數據庫互動)
192      * (私有方法)
193      * 
194      * @param type 類型(對應數據庫表)
195      * @param docId id,對應elasticSearch中的_id字段
196      * @param entity 要插入的實體
197      * @param methodNameParm 需要將實體中哪些屬性作為字段
198      * @return
199      */
200     public static boolean addEntityDoc(String type, String docId, Object entity, String... methodNameParm) {
201         boolean result = false;
202 
203         TransportClient client = getClient();
204         XContentBuilder source = null;
205         try {
206             source = createEntityJson(entity, methodNameParm);
207         } catch (Exception e) {
208             e.printStackTrace();
209         }
210 
211         // 存json入索引中
212         IndexResponse response = null;
213         if (docId == null) {
214             // 使用默認的id
215             response = client.prepareIndex(indexname, type).setSource(source).get();
216         } else {
217             response = client.prepareIndex(indexname, type, docId).setSource(source).get();
218         }
219 
220         // 插入結果獲取
221         String index = response.getIndex();
222         String gettype = response.getType();
223         String id = response.getId();
224         long version = response.getVersion();
225         RestStatus status = response.status();
226 
227         String strResult = "新增文檔成功:" + index + " : " + gettype + ": " + id + ": " + version + ": " + status.getStatus();
228         System.out.println(strResult);
229 
230         if (status.getStatus() == 201) {
231             result = true;
232         }
233 
234         // 關閉client
235         client.close();
236 
237         return result;
238     }
239 
240     /**
241      * 刪除文檔
242      * 
243      * @param type 類型(對應數據庫表)
244      * @param docId 類型中id
245      * @return
246      */
247     public static boolean deleteDoc(String type, String docId) {
248         boolean result = false;
249 
250         TransportClient client = getClient();
251         DeleteResponse deleteresponse = client.prepareDelete(indexname, type, docId).get();
252 
253         System.out.println("刪除結果:" + deleteresponse.getResult().toString());
254         if (deleteresponse.getResult().toString() == "DELETED") {
255             result = true;
256         }
257 
258         // 關閉client
259         client.close();
260 
261         return result;
262     }
263 
264     /**
265      * 修改文檔
266      * 
267      * @param type 類型
268      * @param docId 文檔id
269      * @param updateParam 需要修改的字段和值
270      * @return
271      */
272     public static boolean updateDoc(String type, String docId, Map<String, String> updateParam) {
273         String strResult = "";
274         boolean result = false;
275 
276         TransportClient client = getClient();
277 
278         UpdateRequest updateRequest = new UpdateRequest();
279         updateRequest.index(indexname);
280         updateRequest.type(type);
281         updateRequest.id(docId);
282         try {
283             updateRequest.doc(createMapJson(updateParam));
284         } catch (Exception e) {
285             e.printStackTrace();
286         }
287         try {
288             strResult = client.update(updateRequest).get().getResult().toString();
289         } catch (InterruptedException e) {
290             e.printStackTrace();
291         } catch (ExecutionException e) {
292             e.printStackTrace();
293         }
294         System.out.println(strResult);
295 
296         if (strResult == "UPDATED") {
297             result = true;
298         }
299 
300         return result;
301     }
302 
303     /**
304      * TODO or查詢命中條數
305      * @param type 類型
306      * @param shouldMap 查詢條件
307      * @return
308      */
309     public static int multiOrSearchDocCount(String type, Map<String, String> shouldMap) {
310         TransportClient client = getClient();
311 
312         return 0;
313     }
314 
315     /**
316      * 高亮搜索
317      * 
318      * @param type 類型
319      * @param fieldName 段
320      * @param keyword 關鍵詞
321      * @param from 開始行數
322      * @param size 每頁大小
323      * @return
324      */
325     public static Map<String, Object> searchDocHighlight(String type, String fieldName, String keyword, int from,
326             int size) {
327         TransportClient client = getClient();
328 
329         // 高亮
330         HighlightBuilder hiBuilder = new HighlightBuilder();
331         hiBuilder.preTags("<span style=\"color:red\">");
332         hiBuilder.postTags("</span>");
333         hiBuilder.field(fieldName);
334 
335         QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(fieldName, keyword);
336 
337         SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
338         responsebuilder.setQuery(queryBuilder);
339         responsebuilder.highlighter(hiBuilder);
340         responsebuilder.setFrom(from);
341         responsebuilder.setSize(size);
342         responsebuilder.setExplain(true);
343 
344         SearchResponse myresponse = responsebuilder.execute().actionGet();
345         SearchHits searchHits = myresponse.getHits();
346 
347         // 總命中數
348         long total = searchHits.getTotalHits();
349         Map<String, Object> map = new HashMap<String, Object>();
350         map.put("total", total);
351         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
352         for (int i = 0; i < searchHits.getHits().length; i++) {
353             Map<String, HighlightField> highlightFields = searchHits.getHits()[i].getHighlightFields();
354 
355             // 段高亮
356             HighlightField titleField = highlightFields.get(fieldName);
357             Map<String, Object> source = searchHits.getHits()[i].getSource();
358             if (titleField != null) {
359                 Text[] fragments = titleField.fragments();
360                 String name = "";
361                 for (Text text : fragments) {
362                     name += text;
363                 }
364                 source.put(fieldName, name);
365             }
366 
367             list.add(source);
368         }
369         map.put("rows", list);
370 
371         return map;
372     }
373 
374     /**
375      * or條件查詢高亮
376      * 
377      * @param type 類型
378      * @param shouldMap or條件和值
379      * @param from 開始行數
380      * @param size 每頁大小
381      * @return
382      */
383     public static Map<String, Object> multiOrSearchDocHigh(String type, Map<String, String> shouldMap, int from,
384             int size) {
385         TransportClient client = getClient();
386 
387         SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
388         responsebuilder.setFrom(from);
389         responsebuilder.setSize(size);
390         responsebuilder.setExplain(true);
391 
392         // 高亮
393         HighlightBuilder hiBuilder = new HighlightBuilder();
394         hiBuilder.preTags("<span style=\"color:red\">");
395         hiBuilder.postTags("</span>");
396 
397         // 高亮每個字段
398         for (String key : shouldMap.keySet()) {
399             hiBuilder.field(key);
400         }
401 
402         responsebuilder.highlighter(hiBuilder);
403 
404         if (null != shouldMap && shouldMap.size() > 0) {
405             // 創建一個查詢
406             BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
407 
408             // 這里查詢的條件用map傳遞
409             for (String key : shouldMap.keySet()) {
410                 queryBuilder.should(QueryBuilders.matchPhraseQuery(key, shouldMap.get(key)));// or連接條件
411             }
412             // 查詢
413             responsebuilder.setQuery(queryBuilder);
414         }
415 
416         SearchResponse myresponse = responsebuilder.execute().actionGet();
417         SearchHits searchHits = myresponse.getHits();
418 
419         // 總命中數
420         long total = searchHits.getTotalHits();
421         Map<String, Object> map = new HashMap<String, Object>();
422         map.put("total", total);
423         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
424         for (int i = 0; i < searchHits.getHits().length; i++) {
425             Map<String, HighlightField> highlightFields = searchHits.getHits()[i].getHighlightFields();
426             Map<String, Object> source = searchHits.getHits()[i].getSource();
427 
428             for (String key : shouldMap.keySet()) {
429                 // 各個段進行高亮
430                 HighlightField titleField = highlightFields.get(key);
431                 if (titleField != null) {
432                     Text[] fragments = titleField.fragments();
433                     String name = "";
434                     for (Text text : fragments) {
435                         name += text;
436                     }
437                     source.put(key, name);
438                 }
439             }
440 
441             list.add(source);
442         }
443         map.put("rows", list);
444 
445         return map;
446     }
447 
448     /**
449      * 搜索
450      * 
451      * @param type 類型
452      * @param fieldName 待搜索的字段
453      * @param keyword 待搜索的關鍵詞
454      * @param from 開始行數
455      * @param size 每頁大小
456      * @return
457      */
458     public static Map<String, Object> searchDoc(String type, String fieldName, String keyword, int from, int size) {
459         List<String> hitResult = new ArrayList<String>();
460 
461         TransportClient client = getClient();
462 
463         QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(fieldName, keyword);
464 
465         SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
466         responsebuilder.setQuery(queryBuilder);
467         responsebuilder.setFrom(from);
468         responsebuilder.setSize(size);
469         responsebuilder.setExplain(true);
470 
471         SearchResponse myresponse = responsebuilder.execute().actionGet();
472         SearchHits hits = myresponse.getHits();
473         for (int i = 0; i < hits.getHits().length; i++) {
474             hitResult.add(hits.getHits()[i].getSourceAsString());
475         }
476 
477         // 將命中結果轉換成Map輸出
478         Map<String, Object> modelMap = new HashMap<String, Object>(2);
479         modelMap.put("total", hitResult.size());
480         modelMap.put("rows", hitResult);
481 
482         return modelMap;
483     }
484 
485     /**
486      * 多個條件進行or查詢
487      * 
488      * @param type 類型
489      * @param shouldMap 進行or查詢的段和值
490      * @param from 開始行數
491      * @param size 每頁大小
492      * @return
493      */
494     public static Map<String, Object> multiOrSearchDoc(String type, Map<String, String> shouldMap, int from, int size) {
495         List<String> hitResult = new ArrayList<String>();
496 
497         TransportClient client = getClient();
498 
499         SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
500         responsebuilder.setFrom(from);
501         responsebuilder.setSize(size);
502         responsebuilder.setExplain(true);
503 
504         if (null != shouldMap && shouldMap.size() > 0) {
505             // 創建一個查詢
506             BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
507 
508             // 這里查詢的條件用map傳遞
509             for (String key : shouldMap.keySet()) {
510                 queryBuilder.should(QueryBuilders.matchPhraseQuery(key, shouldMap.get(key)));// or連接條件
511             }
512             // 查詢
513             responsebuilder.setQuery(queryBuilder);
514         }
515 
516         SearchResponse myresponse = responsebuilder.execute().actionGet();
517         SearchHits hits = myresponse.getHits();
518         for (int i = 0; i < hits.getHits().length; i++) {
519             hitResult.add(hits.getHits()[i].getSourceAsString());
520         }
521 
522         // 將命中結果轉換成Map輸出
523         Map<String, Object> modelMap = new HashMap<String, Object>(2);
524         modelMap.put("total", hitResult.size());
525         modelMap.put("rows", hitResult);
526 
527         return modelMap;
528     }
529 
530     /**
531      * 多個條件進行and查詢
532      * 
533      * @param type 類型
534      * @param mustMap 進行and查詢的段和值
535      * @param from 開始行數
536      * @param size 每頁大小
537      * @return
538      */
539     public static Map<String, Object> multiAndSearchDoc(String type, Map<String, String> mustMap, int from, int size) {
540         List<String> hitResult = new ArrayList<String>();
541 
542         TransportClient client = getClient();
543 
544         SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
545         responsebuilder.setFrom(from);
546         responsebuilder.setSize(size);
547         responsebuilder.setExplain(true);
548 
549         if (null != mustMap && mustMap.size() > 0) {
550             // 創建一個查詢
551             BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
552 
553             // 這里查詢的條件用map傳遞
554             for (String key : mustMap.keySet()) {
555                 queryBuilder.must(QueryBuilders.matchPhraseQuery(key, mustMap.get(key)));// and查詢
556             }
557             // 查詢
558             responsebuilder.setQuery(queryBuilder);
559         }
560 
561         SearchResponse myresponse = responsebuilder.execute().actionGet();
562         SearchHits hits = myresponse.getHits();
563         for (int i = 0; i < hits.getHits().length; i++) {
564             hitResult.add(hits.getHits()[i].getSourceAsString());
565         }
566 
567         // 將命中結果轉換成Map輸出
568         Map<String, Object> modelMap = new HashMap<String, Object>(2);
569         modelMap.put("total", hitResult.size());
570         modelMap.put("rows", hitResult);
571 
572         return modelMap;
573     }
574 }
ElasticSearchUtilsImp.java

 

ElasticSearch調用類,是對實現類的各種組合,供外部調用。調用類名稱:ElasticSearchUtils.java

  1 package com.blog.utils;
  2 
  3 import java.util.Map;
  4 
  5 /**
  6  * @author:Tim
  7  * @date:2017年5月3日 下午8:24:22
  8  * @description:ElasticSearch助手類
  9  */
 10 public class ElasticSearchUtils {
 11 
 12     /**
 13      * 將一個Map格式的數據(key,value)插入索引(指定_id,一般是業務數據的id,及elasticSearch和關系型數據使用同一個id,方便同關系型數據庫互動)
 14      * 
 15      * @param type 類型(對應數據庫表)
 16      * @param docId id,對應elasticSearch中的_id字段
 17      * @param mapParam Map格式的數據
 18      * @return
 19      */
 20     public static boolean addDoc(String type, String docId, Map<String, String> mapParam) {
 21         return ElasticSearchUtilsImp.addMapDocToIndex(type, docId, mapParam);
 22     }
 23 
 24     /**
 25      * 將一個Map格式的數據(key,value)插入索引 (使用默認_id)
 26      * 
 27      * @param type 類型(對應數據庫表)
 28      * @param mapParam Map格式的數據
 29      * @return
 30      */
 31     public static boolean addDoc(String type, Map<String, String> mapParam) {
 32         return ElasticSearchUtilsImp.addMapDocToIndex(type, null, mapParam);
 33     }
 34 
 35     /**
 36      * 將一個實體存入到默認索引的類型中(默認_id)
 37      * 
 38      * @param type 類型(對應數據庫表)
 39      * @param entity 要插入的實體
 40      * @param methodNameParm 需要將實體中哪些屬性作為字段
 41      * @return
 42      */
 43     public static boolean addDoc(String type, Object entity, String... methodNameParm) {
 44         return ElasticSearchUtilsImp.addEntityDoc(type, null, entity, methodNameParm);
 45     }
 46 
 47     /**
 48      * 將一個實體存入到默認索引的類型中(指定_id,一般是業務數據的id,及elasticSearch和關系型數據使用同一個id,方便同關系型數據庫互動)
 49      * 
 50      * @param type 類型(對應數據庫表)
 51      * @param docId id,對應elasticSearch中的_id字段
 52      * @param entity 要插入的實體
 53      * @param methodNameParm 需要將實體中哪些屬性作為字段
 54      * @return
 55      */
 56     public static boolean addDoc(String type, String docId, Object entity, String... methodNameParm) {
 57         return ElasticSearchUtilsImp.addEntityDoc(type, docId, entity, methodNameParm);
 58     }
 59 
 60     /**
 61      * 刪除文檔
 62      * 
 63      * @param type 類型(對應數據庫表)
 64      * @param docId 類型中id
 65      * @return
 66      */
 67     public static boolean deleteDoc(String type, String docId) {
 68         return ElasticSearchUtilsImp.deleteDoc(type, docId);
 69     }
 70 
 71     /**
 72      * 修改文檔
 73      * 
 74      * @param type 類型
 75      * @param docId 文檔id
 76      * @param updateParam 需要修改的字段和值
 77      * @return
 78      */
 79     public static boolean updateDoc(String type, String docId, Map<String, String> updateParam) {
 80         return ElasticSearchUtilsImp.updateDoc(type, docId, updateParam);
 81     }
 82 
 83     // --------------------以下是各種搜索方法--------------------------
 84 
 85     /**
 86      * 高亮搜索
 87      * 
 88      * @param type 類型
 89      * @param fieldName 段
 90      * @param keyword 段值
 91      * @return
 92      */
 93     public static Map<String, Object> searchDocHighlight(String type, String fieldName, String keyword) {
 94         return ElasticSearchUtilsImp.searchDocHighlight(type, fieldName, keyword, 0, 10);
 95     }
 96 
 97     /**
 98      * 高亮搜索
 99      * 
100      * @param type 類型
101      * @param fieldName 段
102      * @param keyword 關鍵詞
103      * @param from 開始行數
104      * @param size 每頁大小
105      * @return
106      */
107     public static Map<String, Object> searchDocHighlight(String type, String fieldName, String keyword, int from,
108             int size) {
109         return ElasticSearchUtilsImp.searchDocHighlight(type, fieldName, keyword, from, size);
110     }
111 
112     /**
113      * or條件查詢高亮
114      * 
115      * @param type 類型
116      * @param shouldMap or條件和值
117      * @return
118      */
119     public static Map<String, Object> multiOrSearchDocHigh(String type, Map<String, String> shouldMap, int from,
120             int size) {
121         return ElasticSearchUtilsImp.multiOrSearchDocHigh(type, shouldMap, from, size);
122     }
123 
124     /**
125      * 搜索
126      * 
127      * @param type 類型
128      * @param fieldName 待搜索的字段
129      * @param keyword 待搜索的關鍵詞
130      */
131     public static Map<String, Object> searchDoc(String type, String fieldName, String keyword) {
132         return ElasticSearchUtilsImp.searchDoc(type, fieldName, keyword, 0, 10);
133     }
134 
135     /**
136      * 多個條件進行or查詢
137      * 
138      * @param type 類型
139      * @param shouldMap 進行or查詢的段和值
140      * @return
141      */
142     public static Map<String, Object> multiOrSearchDoc(String type, Map<String, String> shouldMap) {
143         return ElasticSearchUtilsImp.multiOrSearchDoc(type, shouldMap, 0, 10);
144     }
145 
146     /**
147      * 多個條件進行and查詢
148      * 
149      * @param type 類型
150      * @param mustMap 進行and查詢的段和值
151      * @return
152      */
153     public static Map<String, Object> multiAndSearchDoc(String type, Map<String, String> mustMap) {
154         return ElasticSearchUtilsImp.multiAndSearchDoc(type, mustMap, 0, 10);
155     }
156 }
ElasticSearchUtils.java

 

會使用到的其他助手類:StringUtils.java

 1 package com.blog.utils;
 2 
 3 import java.util.Map;
 4 
 5 import net.sf.json.JSONObject;
 6 
 7 /**
 8  * @author:Tim
 9  * @date:2017年5月6日 上午11:56:37
10  * @description:字符串助手類
11  */
12 public class StringUtils {
13 
14     /**
15      * 將Map轉換成json字符串
16      * 
17      * @param map Map<String, Object>格式數據
18      * @return json數據
19      */
20     public static String map2String(Map<String, Object> map) {
21         return JSONObject.fromObject(map).toString();
22     }
23 
24     /**
25      * 首字母轉小寫
26      * 
27      * @param s 待轉換的字符串
28      * @return
29      */
30     public static String toLowerCaseFirstOne(String s) {
31         if (Character.isLowerCase(s.charAt(0)))
32             return s;
33         else
34             return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
35     }
36 }
StringUtils.java

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM