org.elasticsearch.client.RestClient + springboot实现elasticsearch基本CURD

第一:包结构

org.elasticsearch.client.RestClient + springboot实现elasticsearch基本CURD_第1张图片

第二:pom文件


	org.elasticsearch.client
		elasticsearch-rest-client
	
	
	
		org.springframework.boot
	spring-boot-configuration-processor

第三:RestClientConfig内容

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "elasticsearch-props") //prefix 和application.yml一致
public class RestClientConfig {

	private String clusterName;

	private List> clusterNodes = new ArrayList<>();
	private String scheme;

	public String getScheme() {
		return scheme;
	}

	public void setScheme(String scheme) {
		this.scheme = scheme;
	}

	private RestClient restClient;

	public String getClusterName() {
		return clusterName;
	}

	public void setClusterName(String clusterName) {
		this.clusterName = clusterName;
	}



	public List> getClusterNodes() {
		return clusterNodes;
	}

	public void setClusterNodes(List> clusterNodes) {
		this.clusterNodes = clusterNodes;
	}

	public RestClient getRestClient() {
		if(restClient==null) {
			init();
		}
		return restClient;
	}

	public void setRestClient(RestClient restClient) {
		this.restClient = restClient;
	}

	private void init() {
		List httpHosts = new ArrayList();

		for (Map cns : clusterNodes) {
			for (Map.Entry entry : cns.entrySet()) {
				httpHosts.add(new HttpHost(entry.getKey(), entry.getValue(), scheme));
			}
		}

		HttpHost[] hh=(HttpHost[])httpHosts.toArray(new HttpHost[0]);//list to array
		this.setRestClient(RestClient.builder(hh).build());
		System.out.println("init elasticsearch RestClient clusterName "+clusterName+" clusterNodes "+clusterNodes.toString());
	}

}

第四:EsDemo内容

import java.io.IOException;
import java.util.Collections;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import xxx.config.RestClientConfig;
import xxx.service.EsBasicServiceImpl;

import io.swagger.annotations.ApiOperation;

@RequestMapping("/demo")
@RestController
public class EsDemo {
	@Autowired
	private RestClientConfig restClientConfig;
	@Autowired
	private EsBasicServiceImpl esBasicServiceImpl;
	
	@ApiOperation(value = "查询demo", notes = "查询demo")//无封装直接调用
	@GetMapping("/find")
	public String fulltext(@RequestParam(name = "index", defaultValue = "默认索引名称")String index) {

		try {
			
			//System.out.println("根据关键字查询互联网内容["+indexs+keywords+"] ES DSL:"+requestData.toString());
			//1.定义查询的DSL语句
			String dsl="{\"query\":{\"match_all\":{}}}";
			System.out.println("dsl="+dsl);
			//2.格式化DSL语句
			HttpEntity entity = new NStringEntity(dsl.toString(), ContentType.APPLICATION_JSON);

			//3.请求
			Response response = restClientConfig.getRestClient().performRequest("GET", index +"/_search",
					Collections.singletonMap("pretty", "true"), entity);

			//4.处理结果返回给前端
			return EntityUtils.toString(response.getEntity());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
	
	@ApiOperation(value = "查询demo", notes = "查询demo")//esBasicServiceImpl封装查询
	@GetMapping("/find2")
	public String fulltext2(@RequestParam(name = "index", defaultValue = "默认索引名称")String index) {
		String query="{\"query\":{\"match_all\":{}}}";
		try {
			return esBasicServiceImpl.performGet(index, null, query);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}

第五:EsBasicServiceImpl


import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import xxx.RestClientConfig;

@Component
public class EsBasicServiceImpl {
	private static final String PUT = "PUT";
	private static final String POST = "POST";
	private static final String GET = "GET";
	private static final String HEAD = "HEAD";
	private static final String DELETE = "DELETE";
	private RestClient rsc;
	@Autowired
	private RestClientConfig restClientConfig;
	
	public String performGet(String index,String type,String query) throws IOException {
		HttpEntity entity = new NStringEntity(query, ContentType.APPLICATION_JSON);
		String endpoint ="/"+ index +"/" + type + "/_search";
		if(StringUtils.isBlank(type)) {
			endpoint = "/" + index + "/_search";
		}
		Response response = rsc.performRequest(POST, endpoint, Collections.singletonMap("pretty", "true"),entity);
		return EntityUtils.toString(response.getEntity());
	}
	
	public String performPost(List indexs,List types,String query) throws IOException {
		String index = StringUtils.join(indexs, ",");
		String type = "/";
		if(Objects.nonNull(types) && !types.isEmpty()) {
			type += StringUtils.join(types, "/") + "/";
		}
		HttpEntity entity = new NStringEntity(query, ContentType.APPLICATION_JSON);
		String endpoint = "/" + index + type + "_search";
		Response response = rsc.performRequest(POST, endpoint, Collections.singletonMap("pretty", "true"), entity);
		return EntityUtils.toString(response.getEntity());
	}
	
	public String performPut(String index,String type,String id,String data) throws IOException {
		HttpEntity entity = new NStringEntity(data, ContentType.APPLICATION_JSON);
		String requestType = POST;
		String endpoint = "/" + index + "/" + type;
		if (StringUtils.isNoneBlank(id)) {
			 requestType = PUT;
	         endpoint = "/"+index+"/"+type+"/"+id;
		}
		Response response = rsc.performRequest(requestType, endpoint, Collections.singletonMap("pretty", "true"),entity);
		return EntityUtils.toString(response.getEntity());
	}
	
	public String performDelete(String index) throws IOException {
		return performDelete(index, null, null);
	}
	
	public String performDelete(String index,String type) throws IOException {
		return performDelete(index, type, null);
	}
	
	public String performDelete(String index,String type,String id) throws IOException {
		String endpoint = "/"+index+"/"+type+"/"+id;
		 if(StringUtils.isBlank(id)){
	            endpoint = "/"+index+"/"+type;
	       }else if(StringUtils.isBlank(type)){
	            endpoint = "/"+index;
	       }
		 Response response = rsc.performRequest(DELETE, endpoint);
		return  EntityUtils.toString(response.getEntity());
	}
	
	public boolean performHead(String index,String type) throws IOException {
		int code = 200;
		String endpoint = "/" + index + "/" + type;
		if (StringUtils.isBlank(type)) {
			endpoint = "/" + index;
		}
		Response response = rsc.performRequest(HEAD, endpoint);
		code = response.getStatusLine().getStatusCode();
		return code == 200 ? true : false;
	}
	
	@PostConstruct
	public void init() {
		System.out.println("初始化restClient..");
		rsc = restClientConfig.getRestClient();
		System.out.println("初始化restClient完成..");
		System.out.println(rsc.hashCode());
	}
}

第六:application.yml

server:
  port: port #swagger端口
#自定义配置项
elasticsearch-props:
  cluster-name: es #系群名称,最好和服务器配置一样
  scheme: http
  cluster-nodes: #es集群地址
    - ip: port
    - ip: port
    - ip: port
      

 

你可能感兴趣的:(elasticsearch,springboot)