elasticsearch接口开发(新)

此文在上一篇文章的基础上稍做了些许修改,主要在springboot整合ES后的包路径上,如下是新的目录结构

下面贴出代码

MyConfig.java

package com.ylht.config;

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;

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

@Configuration
public class MyConfig {

    @Bean
    public TransportClient client() throws UnknownHostException {
        InetSocketTransportAddress es1 = new InetSocketTransportAddress(
                InetAddress.getByName("192.168.100.101"), 9300
        );
        InetSocketTransportAddress es2 = new InetSocketTransportAddress(
                InetAddress.getByName("192.168.100.102"), 9300
        );
        InetSocketTransportAddress es3 = new InetSocketTransportAddress(
                InetAddress.getByName("192.168.100.103"), 9300
        );

        Settings settings = Settings.builder()
                .put("cluster.name", "aubin-cluster")
                .build();

        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddresses(es1, es2, es3);
        return client;
    }
}

APICcontroller.java

package com.ylht.controller;

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.QueryBuilder;
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.*;

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

@RestController
public class APIController {

    @Autowired
    private TransportClient client;

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

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/get/book/novel")
    public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) {
        try {

            if (id.isEmpty()) {
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            }
            GetResponse response = this.client.prepareGet("book", "novel", id)
                    .get();
            if (!response.isExists()) {
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity(response.getSource(), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/get/book/novel/{id}")
    public ResponseEntity get1(@PathVariable(required = false) String id) {
        try {

            if (id.isEmpty()) {
                return this.get(id);
            }
            GetResponse response = this.client.prepareGet("book", "novel", id)
                    .get();
            if (!response.isExists()) {
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity(response.getSource(), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 添加
     *
     * @param title
     * @param author
     * @param wordCount
     * @param publishDate
     * @return
     */
    @PostMapping(value = "/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 xContentBuilder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("title", title)
                    .field("author", author)
                    .field("word_count", wordCount)
                    .field("publish_date", new SimpleDateFormat("yyyy-MM-dd").format(publishDate.getTime()))
                    .endObject();

            IndexResponse indexResponse = this.client.prepareIndex("book", "novel")
                    .setSource(xContentBuilder)
                    .get();
            return new ResponseEntity(indexResponse.getId(), HttpStatus.OK);

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete/book/novel")
    @ResponseBody
    public ResponseEntity delete(@RequestParam(name = "id") String id) {
        DeleteResponse deleteResponse = this.client.prepareDelete("book", "novel", id).get();

        return new ResponseEntity(deleteResponse.getResult().toString(), HttpStatus.OK);
    }

    /**
     * 修改
     *
     * @param id
     * @param title
     * @param author
     * @return
     */
    @PutMapping(value = "/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 updateRequest = new UpdateRequest("book", "novel", id);

        try {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject();
            if (null != title) {
                xContentBuilder.field("title", title);
            }
            if (null != author) {
                xContentBuilder.field("author", author);
            }
            xContentBuilder.endObject();
            updateRequest.doc(xContentBuilder);

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        try {
            UpdateResponse updateResponse = this.client.update(updateRequest).get();
            return new ResponseEntity(updateResponse.getResult().toString(), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 复合查询
     *
     * @param title
     * @param author
     * @param gtWordCount
     * @param ltWordCount
     * @return
     */
    @PostMapping(value = "/query/book/bovel")
    @ResponseBody
    public ResponseEntity query(@RequestParam(name = "title", required = false) String title,
                                @RequestParam(name = "author", required = false) String author,
                                @RequestParam(name = "gt_word_count", defaultValue = "0") int gtWordCount,
                                @RequestParam(name = "lt_word_count", required = false) Integer ltWordCount) {

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (null != title) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", title));
        }

        if (null != author) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("author", author));
        }

        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("word_count").from(gtWordCount);

        if (null != ltWordCount && ltWordCount > 0) {
            rangeQueryBuilder.to(ltWordCount);
        }

        boolQueryBuilder.filter(rangeQueryBuilder);


        SearchRequestBuilder searchRequestBuilder = this.client.prepareSearch("book").setTypes("novel")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQueryBuilder)
                .setFrom(0)
                .setSize(10);

        System.out.println(searchRequestBuilder);

        SearchResponse searchResponse = searchRequestBuilder.get();

        List<Map<String, Object>> result = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits()) {
            result.add(hit.getSource());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }
}

EsDemoApplication.java

package com.ylht.esdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@ComponentScan(basePackages = {"com.ylht"})
public class EsDemoApplication {

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


}

DateUtils.java

package com.ylht.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
}

log4j.properties

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

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

接口都写在APIConfig.java中,启动项目,然后就可以测试了

我使用的是postman测试

测试过程就不说了

猜你喜欢

转载自www.cnblogs.com/ylht/p/10207849.html