Elasticsearch 6.1.1版本之spring操作api(三)

这个简单的例子我用的是spring-boot来操作的,实际上springmvc也是一样可以实现的,就是注解略微有所不同。为什么是Elasticsearch 6.1.1版本呢?
我觉得Elasticsearch 的兼容性对新手的学习来说不是很友好,2.x版本到5.x的版本有不同的api和依赖,5.x到目前最新的6.1.1又是不同的api,甚至依赖的log4j-core版本都有严格的要求,既然学习就按照最新的学吧,毕竟特性更多,api更灵活。
如果你下载的Elasticsearch是6.1.1,那么maven的依赖最好也是6.1.1,不然容易报org.elasticsearch.client.transport.NoNodeAvailableException: No node available
后面如果es再有更新,请参考官网文档:https://www.elastic.co/guide/en/elasticsearch/client/java-api/6.1/index.html 学习

一 项目结构

Elasticsearch 6.1.1版本之spring操作api(三)_第1张图片

二 依赖


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>cn.comgroupId>
    <artifactId>elasticsearchartifactId>
    <version>1.0-SNAPSHOTversion>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.6.RELEASEversion>
    parent>

    <properties>
      <elasticsearch.version>6.1.1elasticsearch.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>transportartifactId>
            <version>${elasticsearch.version}version>
        dependency>
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-coreartifactId>
            <version>2.9.1version>
        dependency>

        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.44version>
        dependency>
    dependencies>

project>

三 封装elasticsearch client类

package cn.com;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ${DESCRIPTION}
 *
 * @author lightTrace
 * @create 2017-12-26 22:54
 **/
@Configuration
public class MyConfig {

    @Bean
    public TransportClient client() throws UnknownHostException{


        Settings settings = Settings.builder()
                .put("cluster.name","superMan")
                .build();
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
        return client;
    }

}

四 controller类

package cn.com;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * ${DESCRIPTION}
 *
 * @author lightTrace
 * @create 2017-12-26 22:29
 **/

@SpringBootApplication
@RestController
public class Application {
    @Autowired
    private TransportClient client;

    @GetMapping("/")
    public String index(){
        return "index";
    }

    @GetMapping("create")
    @ResponseBody
    public ResponseEntity Index() throws IOException {
        //创建索引
        IndexResponse response = client.prepareIndex("people", "man", "1")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("name", "jack")
                        .field("country", "china")
                        .field("age", "24")
                        .endObject()
                )
                .get();
        return new ResponseEntity(response.getResult(),HttpStatus.OK);
    }
    //根据id查询文档
    @GetMapping("get")
    @ResponseBody
    public ResponseEntity get(@RequestParam(name="id",defaultValue = "")String id){
        if(id.isEmpty()){
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
       GetResponse result = this.client.prepareGet("people","man",id).get();
       if(!result.isExists()){
           return new ResponseEntity(HttpStatus.NOT_FOUND);
       }
        return new ResponseEntity(result.getSource(),HttpStatus.OK);

    }

    //根据id修改文档
    @GetMapping("update")
    @ResponseBody
    public void update(@RequestParam(name="id",defaultValue = "")String id) throws IOException {

        client.prepareUpdate("people", "man", id)
                .setDoc(jsonBuilder()
                        .startObject()
                        .field("name", "zhangs")
                        .endObject())
                .get();

    }

    //根据id删除文档
    @GetMapping("delete")
    @ResponseBody
    public ResponseEntity delete(@RequestParam(name="id",defaultValue = "")String id){
        if(id.isEmpty()){
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        DeleteResponse response = client.prepareDelete("people", "man", id)
                .get();
        return new ResponseEntity(response.getResult(),HttpStatus.OK);

    }

    //根据条件返回list多条数据
    @GetMapping("getList")
    @ResponseBody
    public ResponseEntity getList(){

        MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
                .add("people", "man", "6U-9kmABiFDR7tzAkl_G", "6k-9kmABiFDR7tzAul84")
                .add("water", "river", "1")
                .get();

        for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
            GetResponse response = itemResponse.getResponse();
            if (response.isExists()) {
                String json = response.getSourceAsString();
                System.out.println(json);
            }
        }

        return new ResponseEntity(multiGetItemResponses.getResponses(),HttpStatus.OK);

    }

    //用bulk api在一次请求中同时执行几次操作
    @GetMapping("bulk")
    @ResponseBody
    public ResponseEntity bulk(@RequestParam(name="id",defaultValue = "")String id) throws IOException {
        BulkRequestBuilder bulkRequest = client.prepareBulk();

        // 先创建索引
        bulkRequest.add(client.prepareIndex("people", "man", id)
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("country", "china")
                        .field("age", "18")
                        .endObject()
                )
        );

        bulkRequest.add(client.prepareDelete("people", "man",id)
        );

        BulkResponse bulkResponse = bulkRequest.get();
        return new ResponseEntity(bulkResponse.getItems(),HttpStatus.OK);

    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

然后加个log4j2.properties

appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout

rootLogger.level = info
rootLogger.appenderRef.console.ref = console

五 测试

然后直接启动main方法,或者在终端输入 mvn spring-boot:run 就启动项目了
比如根据创建索引,因为都默认是get请求,直接在浏览器输入:

http://localhost:8080/create 即可创建索引,

http://localhost:8080/get?id=1 即可查看数据,

你可能感兴趣的:(elasticsearch)