SpringBoot集成ElasticSearch小Demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hundan_520520/article/details/81537165

代码参考慕课网《ElasticSearch入门》

索引创建

"mappings": {
    "novel": {
        "properties": {
            "word_count": {
                "type": "integer"
            },
            "author": {
                "type": "keyword"
            },
            "title": {
                "type": "text"
            },
            "publish_date": {
                "format": "yyyy-MM-dd HH-mm-ss||yyyy-MM-dd||epoch_millis",
                "type": "date"
            }
        }
    }
}

项目包层次
这里写图片描述

POM文件

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zhihua</groupId>
  <artifactId>ElasticSearch_Study</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ElasticSearch_Study Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
  </parent>

  <properties>
    <elasticsearch.version>5.4.3</elasticsearch.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <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>
  </dependencies>
  <build>
    <finalName>ElasticSearch_Study</finalName>
  </build>
</project>

log4j.properties

appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
appender.console.layout.patten = [%t] %-5p %c - %m%n

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

启动类

package com.zhihua;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *   启动类
 * @author caizh
 *
 */
@SpringBootApplication
@RestController
public class Application {

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

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

ElasticSearch配置

package com.zhihua;

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

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

/**
 ** 配置elasticsearch
 * @author caizh
 * @throws UnknownHostException 
 *
 */
@Configuration
public class MyConfig {

    //配置elasticsearch
    @Bean
    public TransportClient client() throws UnknownHostException {

        // elasticsearch tcp端口是9300
        InetSocketTransportAddress node = 
                new InetSocketTransportAddress(
                        InetAddress.getByName("localhost"),
                        9300
                        );
        Settings setting = Settings.builder()
                .put("cluster.name","caizh")
                .build();
        TransportClient client = 
                new PreBuiltTransportClient(setting);
        // 添加节点
        client.addTransportAddress(node);
        //client.addTransportAddress(node1);
        return client;
    }
}

Controller类

package com.zhihua.book;

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

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.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@SuppressWarnings({ "rawtypes", "unchecked" })
@RestController
public class BookController {

    @Autowired
    private TransportClient client;

    // 根据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 = client.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 contentBuilder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("title",title)
                    .field("author",author)
                    .field("word_count",wordCount)
                    .field("publish_date", publishDate.getTime())
                    .endObject();
            IndexResponse result = client.prepareIndex("book","novel")
                    .setSource(contentBuilder)
                    .get();
            return new ResponseEntity(result.getId(),HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    // 修改
    @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 (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

        try {
            UpdateResponse result = client.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 = client.prepareSearch("book")
                .setTypes("novel")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQuery)
                .setFrom(0)
                .setSize(10);
        System.out.println(builder);
        SearchResponse response = builder.get();
        List<Map<String , Object>> result = 
                new ArrayList<Map<String,Object>>();
        for(SearchHit hit:response.getHits()) {
            result.add(hit.getSource());
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

    // 删除
    @DeleteMapping("delete/book/novel")
    @ResponseBody
    public ResponseEntity delete(@RequestParam(name="id")String id) {

        DeleteResponse result = client.prepareDelete("book","novel",id)
                .get();
        return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
    }
}






猜你喜欢

转载自blog.csdn.net/hundan_520520/article/details/81537165