Spring boot集成ES

Java API

Maven

<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->

<dependency>

    <groupId>org.elasticsearch.client</groupId>

    <artifactId>transport</artifactId>

    <version>5.5.2</version>

</dependency>


Config

@Configuration

public class MyConfig {

    @Bean

    public TransportClient client() throws UnknownHostException {

        InetSocketTransportAddress node = new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300);

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

        TransportClient client = new PreBuiltTransportClient(settings);

        client.addTransportAddress(node);

        return client;

    }

}


简单查询

@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 = this.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 content = XContentFactory.jsonBuilder().startObject().field("title", title).field("author", author).field("word_count", wordCount).field("publish_date", publishDate.getTime()).endObject();

        IndexResponse result = this.client.prepareIndex("book", "novel").setSource(content).get();

        return new ResponseEntity(result.getId(), HttpStatus.OK);

    }catch (IOException 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.client.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 (IOException e) {

        e.printStackTrace();

        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);

    }

    try {

        UpdateResponse result = this.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 = this.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<>();

    for (SearchHit hit : response.getHits()) {

        result.add(hit.getSource());

    }

    return new ResponseEntity(result, HttpStatus.OK);

}

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,418评论 19赞 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 23,217评论 1赞 92
  • 前几天跟着四姑去散步 放眼望去 到处都是春天的甜蜜 杨柳青浅地微笑 腊梅真的是晶莹透剔嫩黄甜香 那些冬天的枯枝都在...
    随心的爱阅读 328评论 0赞 0
  • 我现在很不快乐,而快乐的回忆越来越模糊,抑郁症多发的时代,我害怕自己成为其中的一员。所以我想将美好的回忆从记忆里提...
    小犬鸣周阅读 315评论 0赞 0
  • 首先看一下一张图(图片来自 sql查询是如何执行的?) 和查询类似,也会走同样的逻辑。 创建连接。 清除缓存。 分...
    swoft_阅读 492评论 0赞 0

友情链接更多精彩内容