1. 程式人生 > >springboot+elasticsearch (elasticsearch-rest-high-level-client)

springboot+elasticsearch (elasticsearch-rest-high-level-client)

1,準備條件

     es服務:127.0.0.1

2,pom.xml

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.5.3</version>
        </dependency>

3,application.yml

spring:
    data:
      elasticsearch:
          host: 127.0.0.1
          port: 9200 # http請求使用9200,老版本的客戶端transport使用的是9300

4,elasticsearchConfig.java

package com.equaker.es;

import org.apache.http.HttpHost;
import org.elasticsearch.client.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfiguration {
    // 讀取自定義配置
    @Value("${spring.data.elasticsearch.host}")
    private String HOST;
    @Value("${spring.data.elasticsearch.port}")
    private String PORT;

    注入RestHighLevelClient 
    @Bean
    public RestHighLevelClient getClient(){

        RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(HOST, 
                            Integer.valueOf(PORT), "http"));
        RestHighLevelClient client = new RestHighLevelClient(clientBuilder);
        return  client;
    }

}

5,測試使用(demoController.java)

package com.equaker.controller;

import com.alibaba.fastjson.JSON;
import com.equaker.mapper.cluster.UserMapper;
import com.equaker.mapper.master.EQMapper;
import com.equaker.model.EQ;
import com.equaker.model.ESUserInfo;
import com.equaker.model.User;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

@Controller
@RequestMapping("demo")
public class DemoController {

    private static Logger log = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private EQMapper eqMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private RestHighLevelClient client;


    
    @RequestMapping("/esSave")
    @ResponseBody
    public ESUserInfo esSave(){

        ESUserInfo esUserInfo = new ESUserInfo(1,"es-sdq",23,new Date(),new Date());

        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("people");
        indexRequest.type("user");
        indexRequest.id("5");
        indexRequest.source(JSON.toJSONString(esUserInfo), XContentType.JSON);
        client.indexAsync(indexRequest, RequestOptions.DEFAULT, new ActionListener<IndexResponse>() {
            @Override
            public void onResponse(IndexResponse indexResponse) {
                log.info("total: "+indexResponse.getShardInfo().getTotal());
                log.info("success: "+indexResponse.getShardInfo().getSuccessful());
                log.info("failed: "+indexResponse.getShardInfo().getFailed());
            }

            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
            }
        });
        return esUserInfo;
    }
    @RequestMapping("/esGet")
    @ResponseBody
    public ESUserInfo esGet(){

        GetRequest getRequest = new GetRequest();
        getRequest.index("people");
        getRequest.type("user");
        getRequest.id("5");
        client.getAsync(getRequest, RequestOptions.DEFAULT, new ActionListener<GetResponse>() {
            @Override
            public void onResponse(GetResponse documentFields) {
                System.out.println(documentFields.getSource());
            }

            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
            }
        });

        return null;
    }
}

6,其他簡單 resthigh-level-elasticsearch-client api

public static void save(RestHighLevelClient client) {
		IndexRequest indexRequest = new IndexRequest("people");
		indexRequest.type("user");
		
		ESUserInfo esUserInfo = new ESUserInfo(2,"es-sdq2",23,new Date(),new Date());	
		indexRequest.id(esUserInfo.getId()+"");
		indexRequest.source(JSON.toJSONString(esUserInfo), XContentType.JSON);
		
		client.indexAsync(indexRequest, RequestOptions.DEFAULT,new ActionListener<IndexResponse>() {
			
			public void onResponse(IndexResponse response) {
				System.out.println(response.getResult());
			}
			
			public void onFailure(Exception e) {
				e.printStackTrace();
				
			}
		});
	}
	
	public static void delete(RestHighLevelClient client) {
		
		DeleteRequest deleteRequest = new DeleteRequest("people", "user", "1");
		
		client.deleteAsync(deleteRequest, RequestOptions.DEFAULT, new ActionListener<DeleteResponse>() {

			public void onResponse(DeleteResponse response) {
				System.out.println("請求http返回碼: "+response.status().getStatus());
				System.out.println("請求返回結果: "+response.getResult());
				
				if(response.getResult().equals(DocWriteResponse.Result.NOT_FOUND)) {
					// NOT FOUNT
				}else if(response.getResult().equals(DocWriteResponse.Result.DELETED)){
					//delete success
				}
				
				ReplicationResponse.ShardInfo shardInfo = response.getShardInfo();
				
				//the total number of shards the write should go to (replicas and primaries).
				//This includes relocating shards, so this
		        //number can be higher than the number of shards.
				System.out.println(shardInfo.getTotal());
				
				//the total number of shards the write succeeded on (replicas and primaries).
				//This includes relocating shards, so this
		        //number can be higher than the number of shards.
				System.out.println(shardInfo.getSuccessful());
				//The total number of replication failures
				System.out.println(shardInfo.getFailed());
				for(Failure failure : shardInfo.getFailures()) {
					System.out.println("失敗原因: "+failure.getCause());
				}
			}

			public void onFailure(Exception e) {
				e.printStackTrace();
				
			}
		});

	}
	
	public static void update(RestHighLevelClient client) {
		
		Map<String, Object> paras = new HashMap<String, Object>();
		paras.put("grade", 23);
		
		
		IndexRequest indexRequest = new IndexRequest("people", "user", "4");
		indexRequest.source(paras);
		UpdateRequest updateRequest = new UpdateRequest("people", "user", "4").upsert(indexRequest);
		
		
		
		updateRequest.upsert(indexRequest); //update or insert
		updateRequest.doc(indexRequest);  //only update
		try {
			UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
			System.out.println(updateResponse.getResult());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void get(RestHighLevelClient client) {
		
		GetRequest getRequest = new GetRequest("people", "user", "1");
		String[] includes = new String[]{"name", "age","id"};//返回包含欄位
		String[] excludes = Strings.EMPTY_ARRAY;
       //表示不返回 _source 即查詢到的資料,使用exist查詢時強烈開啟此欄位
       //FetchSourceContext fetchSourceContext = new FetchSourceContext(false);
		FetchSourceContext fetchSourceContext = new FetchSourceContext(true,includes,excludes);
		getRequest.fetchSourceContext(fetchSourceContext);
		getRequest.storedFields("_source");
		try {
			GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
			System.out.println(getResponse.getField("_source").getValue());
			ESUserInfo userInfo = JSON.parseObject(getResponse.getSourceAsString(), ESUserInfo.class);
			
			System.out.println("user: "+userInfo);
			Map<String, DocumentField> map = getResponse.getFields();
			System.err.println("fields: "+map);
			System.out.println("version: "+getResponse.getVersion());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

7,官方api文件

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-document-exists.html