1、增加依賴
<!--elasticsearch-rest-high-level-client --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>6.3.2</version> </dependency>
2、編寫接口
@GET @Consumes({ MediaType.APPLICATION_JSON, FastJSONProvider.TEXT_JSON, FastJSONProvider.TEXT_FASTJSON }) @Produces({ MediaType.APPLICATION_JSON, FastJSONProvider.TEXT_JSON, FastJSONProvider.TEXT_FASTJSON }) @Path("/addProduct") public RestResponse addProduct(@QueryParam("id") String id, @QueryParam("name") String name, @QueryParam("detail") String detail) { }
3、引入工具類ElasticUtils,並調整增刪改查方法
/* * @(#)ElasticUtils.java * */ package com.dscomm.elastic.utils; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpHost; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.open.OpenIndexRequest; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.ScoreSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.mx.kernel.StringUtil; import com.alibaba.fastjson.JSON; import com.dscomm.elastic.bean.Product; import com.dscomm.plan.rest.bean.PlanDetailVO; import com.dscomm.plan.rest.bean.PlanFlowNodeVO; /** * Elastic工具類 * * <p> * <b>History:</b> * <table border="1"> * <tr> * <th>Date</th> * <th>Operator</th> * <th>Memo</th> * </tr> * <tr> * <td>2021年10月26日</td> * <td>Mark</td> * <td>Create</td> * </tr> * </table> * * @author Mark * * @version TODO 請輸入ElasticUtils的當前版本 * @since TODO 請輸入ElasticUtils的起始版本 */ public class ElasticUtils { // 相當於數據庫名稱(數據量小)索引名稱 public static String indexName = "indexName"; // 初始化api客戶端 public static RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); // 關鍵字搜索 指定匹配類型 public static List<Map<String, Object>> search(String type, String fieldName, String keyword, int start, int count) throws IOException { SearchRequest searchRequest = new SearchRequest(indexName); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); // 關鍵字匹配對應字段 MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder(fieldName, keyword); // 模糊匹配 matchQueryBuilder.fuzziness(Fuzziness.AUTO); sourceBuilder.query(matchQueryBuilder); // 第幾頁 sourceBuilder.from(start); // 第幾條 sourceBuilder.size(count); searchRequest.source(sourceBuilder); searchRequest.types(type); // 匹配度從高到低 sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC)); SearchResponse searchResponse = client.search(searchRequest); SearchHits hits = searchResponse.getHits(); List<Map<String, Object>> matchRsult = new LinkedList<Map<String, Object>>(); for (SearchHit hit : hits.getHits()) { matchRsult.add(hit.getSourceAsMap()); } return matchRsult; } // 刪除指定類型 public static void deleteDocument(Object object) throws IOException { if (object instanceof Product) { DeleteRequest deleteRequest = new DeleteRequest(indexName, "product", ((Product) object).getId()); System.out.println("已經從ElasticSearch服務器上刪除id=" + ((Product) object).getId() + "的product文檔"); client.delete(deleteRequest); } } // 獲得指定type指定id的數據 json public static Map getDocument(String type, String id) throws IOException { // TODO Auto-generated method stub GetRequest request = new GetRequest(indexName, type, id); GetResponse response = client.get(request); if (!response.isExists()) { System.out.println("檢查到服務器上 " + type + " id=" + id + "的文檔不存在"); return null; } else { String source = response.getSourceAsString(); System.out.print("獲取到服務器上 " + type + " id=" + id + "的文檔內容是:"); System.out.println(source); return response.getSourceAsMap(); } } // 插入指定type,數據 public static void addDocument(Object object) throws IOException { Map<String, Object> jsonMap = new HashMap<>(); if (object instanceof Product) { jsonMap.put("id", ((Product) object).getId()); jsonMap.put("name", ((Product) object).getName()); jsonMap.put("detail", ((Product) object).getDetail()); IndexRequest indexRequest = new IndexRequest(indexName, "publishedEop", ((Product) object).getId()) .source(jsonMap); client.index(indexRequest); System.out.println("已經向ElasticSearch服務器增加Product:" + object); } }// 更新數據,當id相同時,則覆蓋更新文檔 public static void updateDocument(Object object) throws IOException { // if (object instanceof Product) { // UpdateRequest updateRequest = new UpdateRequest(indexName, "product", // ((Product) object).getId()) // .doc("name", ((Product) object).getId()).doc("price", ((Product) // object).getPrice()) // .doc("detail", ((Product) object).getDetail()); // client.update(updateRequest); // System.out.println("已經在ElasticSearch服務器修改產品為:" + object); // } } private static boolean checkExistIndex(String indexName) throws IOException { boolean result = true; try { OpenIndexRequest openIndexRequest = new OpenIndexRequest(indexName); client.indices().open(openIndexRequest).isAcknowledged(); } catch (ElasticsearchStatusException ex) { String m = "Elasticsearch exception [type=index_not_found_exception, reason=no such index]"; if (m.equals(ex.getMessage())) { result = false; } } if (result) System.out.println("索引:" + indexName + " 是存在的"); else System.out.println("索引:" + indexName + " 不存在"); return result; } private static void deleteIndex(String indexName) throws IOException { DeleteIndexRequest request = new DeleteIndexRequest(indexName); client.indices().delete(request); System.out.println("刪除了索引:" + indexName); } private static void createIndex(String indexName) throws IOException { // TODO Auto-generated method stub CreateIndexRequest request = new CreateIndexRequest(indexName); client.indices().create(request); System.out.println("創建了索引:" + indexName); } public static String getIndexName() { return indexName; } public static void setIndexName(String indexName) { ElasticUtils.indexName = indexName; } public static RestHighLevelClient getClient() { return client; } public static void setClient(RestHighLevelClient client) { ElasticUtils.client = client; } }