ElasticSearch-2 ES6 TransportClient + SpringBoot2 增删改查

ElasticSearch-1 ES基础概念及命令操作

ElasticSearch-2 ES6 TransportClient + SpringBoot2 增删改查

ElasticSearch-3 ES6 TransportClient 实现全文检索

ElasticSearch-4 ES7 RestHighLevelClient + SpringBoot2 增删改查

ElasticSearch-5 ES7 RestHighLevelClient 实现仿京东搜索


一、springboot2集成ES6的依赖配置

1、默认ES起步依赖:默认安装ES6.4.3的版本,JNA默认安装4.5.1的版本,集成es需要这个依赖,用来访问操作系统原生的应用,不然会报classNotfound的错误,

Maven依赖:

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

Gradle依赖:

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-elasticsearch')
}

2、也可以全部手动指定版本的Maven依赖:

        
            org.elasticsearch
            elasticsearch
            6.4.2
        

        
            org.elasticsearch.client
            transport
            6.4.2
            
                
                    org.elasticsearch
                    elasticsearch
                
            
        

        
            net.java.dev.jna
            jna
            
        

        // 不知道下面这两个依赖有什么用
        
            org.elasticsearch.plugin
            transport-netty4-client
            6.4.2
        

3、配置文件:application.properties

# Elasticsearch
# 9200端口是用来让HTTP REST API来访问ElasticSearch,而9300端口是传输层监听的默认端口
elasticsearch.ip=127.0.0.1
elasticsearch.port=9300
elasticsearch.pool=5
#注意cluster.name需要与config/elasticsearch.yml中的cluster.name一致
elasticsearch.cluster.name=elasticsearch

二、ES配置类:ElasticSearchConfig

package com.example.springboot;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;

/**
 * @author xieyabo
 */
@Configuration
public class ElasticSearchConfig{

    private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchConfig.class);

    @Value("${elasticsearch.ip}")
    private String hostName;

    @Value("${elasticsearch.port}")
    private String port;

    @Value("${elasticsearch.cluster.name}")
    private String clusterName;

    @Value("${elasticsearch.pool}")
    private String poolSize;

    @Bean(name = "transportClient")
    public TransportClient transportClient() {
        LOGGER.info("Elasticsearch初始化开始。。。。。");
        TransportClient transportClient = null;
        try {
            // 配置信息
            Settings esSetting = Settings.builder()
                    //集群名字
                    .put("cluster.name", clusterName)
                    //增加嗅探机制,找到ES集群
                    .put("client.transport.sniff", true)
                    //增加线程池个数,暂时设为5
                    .put("thread_pool.search.size", Integer.parseInt(poolSize))
                    .build();
            //配置信息Settings自定义
            transportClient = new PreBuiltTransportClient(esSetting);
            TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
            transportClient.addTransportAddresses(transportAddress);
        } catch (Exception e) {
            LOGGER.error("elasticsearch TransportClient create error!!", e);
        }
        return transportClient;
    }
}

三、进行增删改查:

package com.example.springboot;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@SpringBootApplication
@RestController
public class SpringbootApplication {
    @Autowired
    private TransportClient transportClient;

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

    //  查询:根据id
    @GetMapping("/get/book/novel")
    @ResponseBody
    public ResponseEntity get(@RequestParam(name = "id",defaultValue = "")String id){
        if (id.isEmpty()){
            return new ResponseEntity((HttpStatus.NOT_FOUND));
        }
        GetResponse result = transportClient.prepareGet("book", "novel", id).get();

        if (!result.isExists()){
            return new ResponseEntity((HttpStatus.NOT_FOUND));
        }
        return new ResponseEntity(result.getSource(), HttpStatus.OK);
    }

    @PostMapping("add/book/novel")
    @ResponseBody
    public ResponseEntity add(
            @RequestParam(name = "title") String title,
            @RequestParam(name = "author") String author,
            @RequestParam(name = "word_count")int wordcount,
            @RequestParam(name = "publish_date")
                    @DateTimeFormat(pattern = "yyyy--MM--dd HH:mm:ss")
                    Date publishDate
    ){
        try {
            XContentBuilder content = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("title", title)
                    .field("author", author)
                    .field("word_count", wordcount)
                    .field("publish_date", publishDate.getTime())
                    .endObject();
            IndexResponse resoult = this.transportClient.prepareIndex("book", "novel").setSource(content).get();
            return new ResponseEntity(resoult.getId(), HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();;
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("delete/book/novel")
    @ResponseBody
    public ResponseEntity delete(@RequestParam(name = "id") String id){
        DeleteResponse result = this.transportClient.prepareDelete("book","novel",id).get();
        return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
    }

    @PutMapping("update/book/novel")
    @ResponseBody
    public ResponseEntity update(
            @RequestParam(name = "id")String id,
            @RequestParam(name = "title",required = false)String title,
            @RequestParam(name = "author",required = false)String author
    ){
        UpdateRequest update = new UpdateRequest("book", "novel", id);
        try {
            XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
            if (title != null){
                builder.field("title",title);
            }
            if (author!= null){
                builder.field("author",author);
            }

            builder.endObject();
            update.doc(builder);
        }catch (Exception e){
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        try {
            UpdateResponse result = this.transportClient.update(update).get();
            return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("query/book/novel")
    @ResponseBody
    public ResponseEntity query(
            @RequestParam(name = "author",required=false)String author,
            @RequestParam(name = "title",required = false)String title,
            @RequestParam(name = "gt_word_count",defaultValue = "0")int gtWordCount,
            @RequestParam(name = "lt_word_count",required = false)Integer ltWordCount
    ){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (author != null){
            boolQuery.must(QueryBuilders.matchQuery("author",author));
        }
        if (title != null){
            boolQuery.must(QueryBuilders.matchQuery("title",title));
        }
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
        if (ltWordCount != null && ltWordCount>0){
            rangeQuery.to(ltWordCount);
        }
        boolQuery.filter(rangeQuery);

        SearchRequestBuilder builder = this.transportClient.prepareSearch("book")
                .setTypes("novel")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQuery)
                .setFrom(0)
                .setSize(10);
        System.out.println(builder);

        SearchResponse respon = builder.get();
        List> result = new ArrayList>();

        for (SearchHit hit : respon.getHits()){
            result.add(hit.getSourceAsMap());
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }



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

}

你可能感兴趣的:(ElasticSearch-2 ES6 TransportClient + SpringBoot2 增删改查)