(ES4)SpringBoot集成ElasticSearch

这里写了个使用es客户端RestHighLevelClient写的工具类,供大家参考.

1.pom.xml文件



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.6.4
		 
	
	com.figo
	ElasticSearchTest
	0.0.1-SNAPSHOT
	war
	ElasticSearchTest
	Demo project for Spring Boot
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-data-elasticsearch
		
		
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-devtools
			runtime
			true
		
		
			org.projectlombok
			lombok
			true
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
		
			org.springframework.boot
			spring-boot-starter-tomcat
			provided
		
		
		
			org.apache.tomcat.embed
			tomcat-embed-jasper
			provided
		
		
		
			javax.servlet
			javax.servlet-api
			provided
		
		
		
			javax.servlet
			jstl
		
		
		
			com.alibaba
			fastjson
			1.2.72
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
				
					
						
							org.projectlombok
							lombok
						
					
				
			
		
	


2.RestHighLevelClientUtil工具类

/**
 * 
 */
package com.figo.es.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.GetAliasesResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.figo.es.mode.Message;

/**
 * @author figo
 *
 */
public class RestHighLevelClientUtil {
	public static final String host = "";
	public static final String port = "";
	public static final String indexName = "";
	public static final String tableName = "";
	private static RestHighLevelClient client = null;
	private static final String HOST = "118.118.10.101";
	private static final int PORT = 9200;
	private static final String HOST1 = "118.118.10.102";
	private static final int PORT1 = 9201;
	private static final String HOST2 = "118.118.10.103";
	private static final int PORT2 = 9202;
	public static final String DEFAULT_SCHEME_NAME = "http";
	private static final String USERNAME = "elastic";
	private static final String PASSWORD = "123456";

	/**
	 * 创建elasticsearch客户端RestHighLevelClient .
	 * 
	 * @return
	 */
	public static RestHighLevelClient getClient() {
//		TransportClient transportClient=null;
		if (client == null) {
			CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USERNAME, PASSWORD));
			// 无需认证
			RestClientBuilder builder = RestClient.builder(new HttpHost(HOST, PORT, DEFAULT_SCHEME_NAME),
					new HttpHost(HOST1, PORT1, DEFAULT_SCHEME_NAME), new HttpHost(HOST2, PORT2, DEFAULT_SCHEME_NAME))
					.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
						@Override
						public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
							return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
						}
					});

			client = new RestHighLevelClient(builder);
		}
		return client;
	}

	/**
	 * 关闭客户端 .
	 */
	public static void closeClient() {
		if (client != null) {
			try {
				client.close();
				client = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.12/java-rest-high-create-index.html
	/**
	 * 创建索引,index是索引名称 . 索引相当于关系数据库的数据库名称 .
	 * 
	 * @param index
	 * @return
	 */
	public static boolean create(String index) {
		try {
			CreateIndexRequest request = new CreateIndexRequest(index);
			request.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 0));
			// 可以多种方式
//			request.mapping(
//					"{\n" + "  \"properties\": {\n" + "    \"name\": {\n" + "      \"type\": \"text\"\n" + "    },\n"
//							+ "    \"postDate\": {\n" + "      \"type\": \"text\"\n" + "    },\n"
//							+ "    \"message\": {\n" + "      \"type\": \"text\"\n" + "    }\n" + "  }\n" + "}",
//					XContentType.JSON);
			// 20220327也可以用下面这种方式写改成下面
			XContentBuilder builder = XContentFactory.jsonBuilder();
			builder.startObject();
			{
				builder.startObject("properties");
				{
					builder.startObject("name");
					{
						builder.field("type", "text").field("analyzer", "ik_smart")// 设置分词器
								.field("search_analyzer", "ik_max_word");// 设置查询分词器
					}
					builder.endObject();
					builder.startObject("postDate");
					{
						builder.field("type", "text");
					}
					builder.endObject();
					builder.startObject("message");
					{
						builder.field("type", "text").field("analyzer", "ik_smart").field("search_analyzer",
								"ik_max_word");
					}

					builder.endObject();
				}
				builder.endObject();
			}

			builder.endObject();
			request.mapping(builder);

			request.alias(new Alias("es_alias_" + index));

			request.setTimeout(TimeValue.timeValueMinutes(2));
			CreateIndexResponse createIndexResponse = getClient().indices().create(request, RequestOptions.DEFAULT);
			return createIndexResponse.isAcknowledged();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 删除索引 .
	 * 
	 * @param index
	 * @return
	 */
	public static boolean delete(String index) {
		try {
			DeleteIndexRequest request = new DeleteIndexRequest(index);
			request.timeout(TimeValue.timeValueMinutes(2));
			request.timeout("2m");
			AcknowledgedResponse deleteIndexResponse = getClient().indices().delete(request, RequestOptions.DEFAULT);
			return deleteIndexResponse.isAcknowledged();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 查询索引 .
	 * 
	 * @param index
	 * @return
	 */
	public static String[] getIndex(String index) {
		try {
			GetIndexRequest request = new GetIndexRequest(index);
			// request.indices("test_index");
			request.includeDefaults(true);
			GetIndexResponse getIndexResponse = getClient().indices().get(request, RequestOptions.DEFAULT);

			return getIndexResponse.getIndices();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new String[0];
	}

	/**
	 * 获取所有索引 .
	 */
	public static void getAll() {
		try {
			GetAliasesRequest request = new GetAliasesRequest();
			GetAliasesResponse getAliasesResponse = client.indices().getAlias(request, RequestOptions.DEFAULT);
			Map> map = getAliasesResponse.getAliases();
			Set indices = map.keySet();
			System.out.println("all index begin");
			for (String key : indices) {
				System.out.println(key);
			}
			System.out.println("all index end");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断索引是否存在 .
	 * 
	 * @param index
	 * @return
	 */
	public static boolean exist(String index) {
		try {
			GetIndexRequest request = new GetIndexRequest(index);
			boolean result = getClient().indices().exists(request, RequestOptions.DEFAULT);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 功能描述:创建文档
	 */

	public static String addDocument() {
		// 1. 创建对象
		Message message = new Message("tester", "20220326", "hello,world");

		// 2. 创建请求并指定索引
		IndexRequest indexRequest = new IndexRequest("001");

		// 3. 创建的规则:put /xununan_index/_doc/1
		indexRequest.id("1"); // 设置ID

		indexRequest.timeout("1s"); // 设置超时时间

		// 4. 将数据放入到请求中
		indexRequest.source(JSON.toJSONString(message), XContentType.JSON);

		// 5. 使用客户端发送请求
		IndexResponse index = null;
		try {
			index = getClient().index(indexRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(JSON.toJSONString(index));

		return JSON.toJSONString(index);
	}

	/**
	 * 功能描述:updateDocmentTest 更新文档信息
	 */
	public static String updateDocment() {
		// 1. 创建一个更新请求的信息,绑定索引名称和需要更新的文档ID
		UpdateRequest updateRequest = new UpdateRequest("001", "1");
		updateRequest.timeout("1s"); // 设置超时时间
		Message message = new Message("tester", "20220326", "hello,world! update successfully!");
		// 2. 封装需要更新的文档信息
		updateRequest.doc(JSON.toJSONString(message), XContentType.JSON);

		// 3. 使用update更新文档
		UpdateResponse updateResponse = null;
		try {
			updateResponse = getClient().update(updateRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println(JSON.toJSONString(updateResponse));
		return JSON.toJSONString(updateResponse);
	}

	/**
	 * 删除文档 .
	 * 
	 * @return
	 */
	public static String deleteDocment() {
		// 1. 创建一个删除的请求,绑定索引名和需要删除的文档ID
		DeleteRequest deleteRequest = new DeleteRequest("001", "1");
		// 2. 发起删除请求
		DeleteResponse response = null;
		try {
			response = getClient().delete(deleteRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(JSON.toJSONString(response));
		return JSON.toJSONString(response);
	}

	/**
	 * 批量创建文档 .
	 * 
	 * @return
	 */
	public static String addDocmentByBatch() {
		// 1. 创建批量的请求
		BulkRequest bulkRequest = new BulkRequest();
		bulkRequest.timeout("60s"); // 设置超时时间
		List list = new ArrayList<>();
		for (int a = 1; a <= 100; a++) {
			if (a % 2 == 0) {
				if (a % 6 == 0) {
					Message message = new Message("tester" + a, "20220326", "手机" + a);
					list.add(message);
				}
				if (a % 8 == 0) {
					Message message = new Message("tester" + a, "20220326", "华为手机" + a);
					list.add(message);
				}
			} else {
				Message message = new Message("tester" + a, "20220326", "华为" + a);
				list.add(message);
				Message message1 = new Message("tester" + a, "20220326", "hello,world" + a);
				list.add(message1);
			}
		}

		// 2. 将多条数据批量的放入bulkRequest中
		for (int i = 0; i < list.size(); i++) {
			// 批量更新和批量删除在这里修改对应的请求即可
			bulkRequest
					.add(new IndexRequest("001").id("" + i).source(JSON.toJSONString(list.get(i)), XContentType.JSON));
		}
		// 3. 执行批量创建文档
		BulkResponse responses = null;
		try {
			responses = getClient().bulk(bulkRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(responses.hasFailures()); // 是否失败,如果false则表示全部成功
		System.out.println(JSON.toJSONString(responses));
		return JSON.toJSONString(responses);
	}

	/**
	 * 功能描述:searchTest 批量搜索,可以设置高亮等信息
	 */
	public static String search() {

		// 1. 创建批量搜索请求,并绑定索引
		SearchRequest searchRequest = new SearchRequest("001");

		// 2. 构建搜索条件
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

//	    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword", "tester"); // 设置精确查询
//	        QueryBuilders.matchAllQuery();
		// 添加基本分词查询
		// 会查询出tester1,tester2,tester99
//	    QueryBuilder queryBuilder =QueryBuilders.matchQuery("name", "tester1 tester2 tester99").analyzer("ik_smart");
		// 会查询出message中含有华为,手机,华为手机的文档
		QueryBuilder queryBuilder = QueryBuilders.matchQuery("message", "华为手机").analyzer("ik_max_word");
		sourceBuilder.query(queryBuilder).timeout(new TimeValue(60, TimeUnit.SECONDS));
		// 3. 将查询条件放入搜索请求request中
		sourceBuilder.from(0);// 从0开始
		sourceBuilder.size(100);// 每页数据100条
		HighlightBuilder highlightBuilder = new HighlightBuilder(); // 创建一个新的HighlightBuilder。
		HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("message"); // 为title字段创建字段高光色。
		highlightTitle.highlighterType("unified"); // 设置字段高光色类型。
		highlightBuilder.field(highlightTitle); // 将字段高光色添加到高亮构建器。
//		HighlightBuilder.Field highlightUser = new HighlightBuilder.Field("name");
//		highlightBuilder.field(highlightUser);
//		sourceBuilder.highlighter(highlightBuilder);
		searchRequest.source(sourceBuilder);

		// 4. 发起查询请求获取数据
		SearchResponse response = null;
		try {
			response = getClient().search(searchRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(JSON.toJSONString(response));
		System.out.println(JSON.toJSONString(response.getHits().getHits()));
		return JSON.toJSONString(response);

	}

	/**
	 * 将text内容进行中文分词 .
	 * 
	 * @param text
	 * @return
	 */
	public static String getAnalyze(String text) {
		StringBuffer buffer = new StringBuffer();
		String[] texts = null;
		List list = new ArrayList();
		Request request = new Request("GET", "_analyze");
		JSONObject entity = new JSONObject();
		entity.put("analyzer", "ik_max_word");
		// entity.put("analyzer", "ik_smart");
		entity.put("text", text);
		request.setJsonEntity(entity.toJSONString());
		Response response;
		try {
			response = getClient().getLowLevelClient().performRequest(request);
			JSONObject tokens = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
			JSONArray arrays = tokens.getJSONArray("tokens");
			System.out.println("获取到的分词=" + arrays.toJSONString());
//			texts=new String[arrays.size()];

			for (int i = 0; i < arrays.size(); i++) {
				JSONObject obj = JSON.parseObject(arrays.getString(i));
//				list.add(obj.getString("token"));
//				texts[i]=obj.getString("token");
				buffer.append(obj.getString("token"));
				buffer.append(",");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("分词结果=" + buffer.toString());
		return buffer.toString();
	}

	public static void main(String[] args) {
		try {
			System.out.println(getAnalyze("我是中国人"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

你可能感兴趣的