SpringBoot集成ElasticSearch的几种方式

    到目前为止,ES有4种客户端,分别是:Jest client、Rest client、Transport client、Node client,相信大家在项目集成中选择客户端比较纠结,搜索案例的时候一会是这个客户端实现的,一会儿又是别的客户端实现的,自己又不了解每个客户端的优劣势,但又想集成最好的,下面就来说说各个客户端的区别,以及优劣势

ES支持两种协议  

       HTTP协议,支持的客户端有Jest client和Rest client

       Native Elasticsearch binary协议,也就是Transport client和Node client

Jest client和Rest client区别

      Jest client非官方支持,在ES5.0之前官方提供的客户端只有Transport client、Node client。在5.0之后官方发布Rest client,并大力推荐

Transport client和Node client区别

       Transport client(7.0弃用)和Node client(2.3弃用)区别:最早的两个客户端,Transport client是不需要单独一个节点。Node client需要单独建立一个节点,连接该节点进行操作,ES2.3之前有独立的API,ES2.3之后弃用该API,推荐用户创建一个节点,并用Transport client连接进行操作

综合:以上就是各个客户端现在的基本情况,可以看出Rest client目前是官方推荐的,但是springBoot默认支持的依然Transport client,这可能和ES更新速度有关,下面集成中会列出所有客户端的集成方式

源码托管地址:

https://github.com/rancho00/ElasticSearch/tree/master/source/spring-boot-demo-elasticsearch

SpringBoot整合ES

1、Rest client

2、Jest client

3、Spring Data

4、Spring Data Repository

 

1、Rest client

Rest client分为:Java Low Level Rest Client和Java High Level Rest Client

Java Low Level Rest Client

pom.xml


        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.elasticsearch.client
            elasticsearch-rest-client
            6.4.0
        
    

application.properties

spring.elasticsearch.rest.uris=http://127.0.0.1:9200

RestLowTest.java


package com.rancho.demo.elasticsearch;

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.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestLowTest {

    @Resource
    private RestClient client;

    @Test
    public void add() {
        try {
            Request request = new Request("PUT", "/content/doc/20190909");
            String jsonString = "{\"id\":\"20190909\",\"name\":\"测试\",\"age\":22}";
            HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
            request.setEntity(entity);
            Response response = client.performRequest(request);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        } catch (Exception e) {

        }
    }

    @Test
    public void search() {
        try {
            Request request = new Request("GET", "/content/_search");
            String jsonString = "{\"query\":{\"match\":{\"name\":\"测试\"}}}";
            HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
            request.setEntity(entity);
            Response response = client.performRequest(request);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Test
    public void update() {
        try {
            Request request = new Request("PUT", "/content/doc/20190909");
            String jsonString = "{\"id\":\"20190909\",\"name\":\"测试-update\",\"age\":22}";
            HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
            request.setEntity(entity);
            Response response = client.performRequest(request);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        } catch (Exception e) {

        }
    }

    @Test
    public void get() {
        try {
            Request request = new Request("GET", "/content/doc/20190909");
            Response response = client.performRequest(request);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        } catch (Exception e) {

        }
    }

    @Test
    public void delete() {
        try {
            Request request = new Request("DELETE", "/content/doc/20190909");
            Response response = client.performRequest(request);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        } catch (Exception e) {

        }
    }
}

Java High Level Rest Client

pom.xml


        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.elasticsearch.client
            elasticsearch-rest-client
            6.4.0
        
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            6.4.0
        

    

application.properties

spring.elasticsearch.rest.uris=http://127.0.0.1:9200

RestHighTest.java


package com.rancho.demo.elasticsearch;

import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
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.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestHighTest {

    @Resource
    private RestHighLevelClient restHighLevelClient;


    @Test
    public void add() {
        Map map = new HashMap();
        map.put("id", "20190909");
        map.put("name", "测试");
        map.put("age", 22);
        try {
            IndexRequest indexRequest = new IndexRequest("content", "doc", map.get("id").toString()).source(map);
            IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            System.out.println(indexResponse.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void search() {
        SearchRequest searchRequest = new SearchRequest().indices("content").types("doc");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        MatchPhrasePrefixQueryBuilder mppqb = QueryBuilders.matchPhrasePrefixQuery("name", "测试");
        sourceBuilder.query(mppqb);
        try {
            SearchResponse sr = this.restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            String result = sr.toString();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Test
    public void update() {
        Map map = new HashMap();
        map.put("id", "20190909");
        map.put("name", "测试-update");
        map.put("age", 22);
        try {
            UpdateRequest request = new UpdateRequest("content", "doc", map.get("id").toString()).doc(map);
            UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
            System.out.println(updateResponse.toString());
        } catch (Exception e) {

        }
    }

    @Test
    public void get() {
        try {
            GetRequest request = new GetRequest("content", "doc", "20190909");
            GetResponse getResponse = this.restHighLevelClient.get(request, RequestOptions.DEFAULT);
            System.out.println(getResponse.toString());
        } catch (Exception e) {

        }
    }

    @Test
    public void delete() {
        try {
            DeleteRequest request = new DeleteRequest("content", "doc", "20190909");
            DeleteResponse deleteResponse = this.restHighLevelClient.delete(request, RequestOptions.DEFAULT);
            System.out.println(deleteResponse.toString());
        } catch (Exception e) {

        }
    }
}

2、Jest client

pom.xml        


        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.elasticsearch
            elasticsearch
            6.5.4
        
        
            io.searchbox
            jest
            5.3.3
        
    

application.properties

spring.elasticsearch.jest.uris=http://127.0.0.1:9200

JestTest.java

package com.rancho.demo.elasticsearch;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class JestTest {

    @Resource
    private JestClient jestClient;

    @Test
    public void add() {
        Map map = new HashMap();
        map.put("id", "20190909");
        map.put("name", "测试");
        map.put("age", 22);
        Index index = new Index.Builder(map).id("20190909").index("content").type("doc").build();
        try {
            JestResult jestResult = jestClient.execute(index);
            System.out.println(jestResult.getJsonString());
        } catch (Exception e) {

        }
    }

    @Test
    public void search() {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchPhrasePrefixQuery("name", "测试"));
        Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex("content").addType("doc").build();
        try {
            JestResult jestResult = jestClient.execute(search);
            System.out.println(jestResult.getJsonString());
        } catch (Exception e) {

        }
    }

    /**
     * Index也可以修改
     */
    @Test
    public void update() {
        String script = "{" +
                "    \"doc\" : {" +
                "        \"id\" : \"20190909\"," +
                "        \"name\" : \"测试-update\"," +
                "        \"age\" : \"22\"" +
                "    }" +
                "}";
        Update update = new Update.Builder(script).index("content").type("doc").id("20190909").build();
        try {
            JestResult jestResult = jestClient.execute(update);
            System.out.println(jestResult.getJsonString());
        } catch (Exception e) {

        }
    }

    @Test
    public void get() {
        Get build = new Get.Builder("content", "20190909")
                .type("doc")
                .build();
        try {
            JestResult jestResult = jestClient.execute(build);
            System.out.println(jestResult.getJsonString());
        } catch (Exception e) {

        }
    }


    @Test
    public void delete() {
        Delete delete = new Delete.Builder("20190909").index("content").type("doc").build();
        try {
            JestResult jestResult = jestClient.execute(delete);
            System.out.println(jestResult.getJsonString());
        } catch (Exception e) {

        }
    }
}

3、Spring Data

pom.xml

 
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
    

application.properties

spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.cluster-name=elasticsearch

ElasticsearchTemplateTest.java

package com.rancho.demo.elasticsearch;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchTemplateTest {

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void add(){
        try{
            Map map=new HashMap();
            map.put("id","20190909");
            map.put("name","测试");
            map.put("age",22);
            IndexQuery indexQuery=new IndexQueryBuilder().withIndexName("content").withType("doc").withId(map.get("id").toString()).withObject(map).build();
            String result=elasticsearchTemplate.index(indexQuery);
            System.out.println(result);
        }catch (Exception e){

        }
    }

    @Test
    public void search(){
        MatchPhraseQueryBuilder mpqb= QueryBuilders.matchPhraseQuery("name","测试");
        try{
            SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(mpqb).build();
            elasticsearchTemplate.query(searchQuery,searchResponse ->{
                if (searchResponse.getHits().getTotalHits() > 0) {
                    SearchHit[] searchHits = searchResponse.getHits().getHits();
                    for(SearchHit searchHit:searchHits){
                        System.out.println(searchHit.getSourceAsString());
                    }
                }
                return null;
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void update(){
        try{
            Map map=new HashMap();
            map.put("id","20190909");
            map.put("name","测试-update");
            map.put("age",22);
            IndexQuery indexQuery=new IndexQueryBuilder().withIndexName("content").withType("doc").withId(map.get("id").toString()).withObject(map).build();
            String result=elasticsearchTemplate.index(indexQuery);
            System.out.println(result);
        }catch (Exception e){

        }
    }

    @Test
    public void delete(){
        try{
            elasticsearchTemplate.delete("content","doc","20190909");
        }catch (Exception e){

        }
    }
}

4、Spring Data Repository

pom.xml



            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        


        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        

application.properties

spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.cluster-name=elasticsearch

定义一个User实体

package com.rancho.demo.elasticsearch.repository.entity;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "content", type = "doc")public class User {
    private String id;
    private String name;
    private Integer age;
    public String getId() {        return id;    }
    public void setId(String id) {        this.id = id;    }
    public String getName() {        return name;    }
    public void setName(String name) {        this.name = name;    }
    public Integer getAge() {        return age;    }
    public void setAge(Integer age) {        this.age = age;    }
    @Override    public String toString() {        return "User{" +                "id='" + id + '\'' +                ", name='" + name + '\'' +                ", age=" + age +                '}';    }}

自定义UserRepository并集成ElasticsearchRepository

package com.rancho.demo.elasticsearch.repository.repository;

import com.rancho.demo.elasticsearch.repository.entity.User;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface UserRepository extends ElasticsearchRepository {

    User findByName(String name);
}

定义UserService.java


package com.rancho.demo.elasticsearch.repository.service;

import com.rancho.demo.elasticsearch.repository.entity.User;

public interface UserService {

    void save(User user);

    void update(User user);

    User getById(String id);

    User getByName(String name);

    void delete(String id);
}

定义UserService实现类UserServiceImp.java


package com.rancho.demo.elasticsearch.repository.service.impl;

import com.rancho.demo.elasticsearch.repository.entity.User;
import com.rancho.demo.elasticsearch.repository.repository.UserRepository;
import com.rancho.demo.elasticsearch.repository.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    @Override
    public User getById(String id) {
        return userRepository.findById(id).get();
    }

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public User getByName(String name) {
        return userRepository.findByName(name);
    }

    @Override
    public void delete(String id) {
        userRepository.deleteById(id);
    }

    @Override
    public void update(User user) {
        userRepository.delete(user);
        userRepository.save(user);
    }
}

测试RepositoryTest.java

package com.rancho.demo.elasticsearch;

import com.rancho.demo.elasticsearch.repository.entity.User;
import com.rancho.demo.elasticsearch.repository.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RepositoryTest {

    @Resource
    private UserService userService;

    @Test
    public void add(){
        try{
            User user=new User();
            user.setId("20190909");
            user.setName("测试");
            user.setAge(22);
            userService.save(user);
            System.out.println("添加成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void get(){
        try{
            User user=userService.getById("20190909");
            System.out.println(user.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void update(){
        try{
            User user=new User();
            user.setId("20190909");
            user.setName("测试-update");
            user.setAge(22);
            userService.update(user);
            System.out.println("修改成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void getByName(){
        try{
            User user=userService.getByName("测试-update");
            System.out.println(user.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void delete(){
        try{
            userService.delete("20190909");
            System.out.println("删除成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

获取最新动态http://www.rancho.io

 

 

 

 

 

 

 

 

 

 

 

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