Spring Boot集成Elastic Search

一.导入maven依赖

本机安装的是6.5.4版本的Elastic Search,故这里导入6.5.4版本的Elastic Search依赖

    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>6.5.4</elasticsearch.version>
    </properties>
​
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
​
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

二.创建配置类

1.Elastic Search的配置

  • 需要在/conf/elasticsearch.yml配置node和cluster.name以及允许跨域访问

conf/elasticsearch.yml

cluster.name: dayukeji
node.name: dayutec
​
http.cors.enabled: true
http.cors.allow-origin: "*"

2.创建配置类

9200作为Http协议,主要用于外部通讯

9300作为Tcp协议,jar之间就是通过Tcp协议通讯

ES集群之间是通过9300进行通讯

@Configuration
public class MyConfig {
    @Bean
    public TransportClient client() throws UnknownHostException {
​
        //配置setting
        Settings settings = Settings.builder()
                .put("node.name", "dayutec")
                .put("cluster.name", "dayukeji")
                .build();
​
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
​
        return client;
    }
​
}

三.测试方法

先调用127.0.0.1:9200/book创建一个index

{
    "settings":{
        "number_of_shards":3,
        "number_of_replicas":1
    },
    "mappings":{
        "novel":{
            "properties":{
                "name":{
                    "type":"text"
                },
                "price":{
                    "type":"integer"
                },
                "word_count":{
                    "type":"integer"
                }
            }
        }
    }
}

1.新增

    @PostMapping("/book/novel")
    public ResponseEntity add(@RequestParam("name") String name,
                              @RequestParam("price") Integer price,
                              @RequestParam(value = "word_count") int wordCount) {
        try {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("name", name)
                    .field("price", price)
                    .field("word_count", wordCount)
                    .endObject();
            IndexResponse result = this.client.prepareIndex("book", "novel")
                    .setSource(xContentBuilder)
                    .get();
            return new ResponseEntity(result.getId(), HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

2.获取

   /**
     * 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/book/novel/{id}")
    public ResponseEntity get(@PathVariable("id") String id) {
        GetResponse result = this.client.prepareGet("book", "novel", id).get();
        if (result.isExists()) {
            return new ResponseEntity(result.getSource(), HttpStatus.OK);
        } else {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
    }

3.修改

    @PutMapping("/book/novel/{id}")
    public ResponseEntity update(@PathVariable("id") String id,
                                 @RequestParam(value = "name", required = false) String name,
                                 @RequestParam(value = "price", required = false) Integer price) {
        UpdateRequest update = new UpdateRequest("book", "novel", id);
        try {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                    .startObject();
            if (name != null) {
                xContentBuilder.field("name", name);
            }
            if (price != null) {
                xContentBuilder.field("price", price);
            }
            xContentBuilder.endObject();
            update.doc(xContentBuilder);
        } catch (IOException e) {
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        try {
            UpdateResponse result = this.client.update(update).get();
            return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
        } catch (InterruptedException e) {
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (ExecutionException e) {
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

4.删除

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

5.复杂查询

    @GetMapping("/book/novel")
    public ResponseEntity query(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "price", required = false) Integer price,
            @RequestParam(value = "gt_word_count", defaultValue = "0") Integer gtWordCount,
            @RequestParam(value = "lt_word_count", required = false) Integer ltWordCount) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (name != null) {
            boolQuery.must(QueryBuilders.matchQuery("name", name));
        }
        if (price != null) {
            boolQuery.must(QueryBuilders.matchQuery("price", price));
        }
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
        if (ltWordCount != null && ltWordCount > 0) {
            rangeQuery.to(ltWordCount);
        }
        SearchResponse result = this.client.prepareSearch("book")
                .setTypes("novel")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQuery)
                .setFrom(0)
                .setSize(10)
                .get();
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : result.getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return new ResponseEntity(list, HttpStatus.OK);
    }

 

上一篇:setCookie


下一篇:Spring AOP环绕异常影响的报错