查看: 179|回复: 0

[Java学习] SpringBoot整合Elasticsearch并实现CRUD操作

发表于 5 天前

配置准备

在build.gradle文件中添加如下依赖:

  1. compile "org.elasticsearch.client:transport:5.5.2"
  2. compile "org.elasticsearch:elasticsearch:5.5.2"
  3. //es 5.x的内部使用的 apache log4日志
  4. compile "org.apache.logging.log4j:log4j-core:2.7"
  5. compile "org.apache.logging.log4j:log4j-api:2.7"
复制代码

这里spring boot使用的是1.5.4版,前些天spring boot 2正式版已经发布,spring boot 2新特性中有一条是支持kotlin,spring boot 2基于spring 5,spring 5也支持了koltin,所以spring也开始支持函数式编程。

关于版本兼容

这里写图片描述

配置访问Elasticsearch的客户端,这里都使用原生es JavaAPI。

  1. @Configuration
  2. public class ElasticSearchConfig {
  3. @Bean(name = "client")
  4. public TransportClient getClient() {
  5. InetSocketTransportAddress node = null;
  6. try {
  7. node = new InetSocketTransportAddress(InetAddress.getByName("192.168.124.128"), 9300);
  8. } catch (UnknownHostException e) {
  9. e.printStackTrace();
  10. }
  11. Settings settings = Settings.builder().put("cluster.name", "my-es").build();
  12. TransportClient client = new PreBuiltTransportClient(settings);
  13. client.addTransportAddress(node);
  14. return client;
  15. }
  16. }
复制代码

SocketTransport端口可以使用http://ip:9200/_nodes方式查看,这里默认使用的是9300端口。

CRUD操作

新建一个控制器ElasticSearchController,使用原生的es JavaAPI。

  1. @RestController
  2. public class ElasticSearchController {
  3. @Autowired
  4. TransportClient client;
  5. }
复制代码

在控制器中添加增删查改方法

增加操作

  1. @PostMapping("add/book/novel")
  2. public ResponseEntity add(
  3. @RequestParam(name = "title") String title, @RequestParam(name = "authro") String author,
  4. @RequestParam(name = "word_count") int wordCount,
  5. @RequestParam(name = "publish_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date publishDate
  6. )
  7. {
  8. try {
  9. XContentBuilder content = XContentFactory.jsonBuilder().startObject()
  10. .field("title", title)
  11. .field("author", author)
  12. .field("word_count", wordCount)
  13. .field("publish_date", publishDate.getTime())
  14. .endObject();
  15. IndexResponse result = this.client.prepareIndex("book", "novel").setSource(content).get();
  16. return new ResponseEntity(result.getId(), HttpStatus.OK);
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
  20. }
  21. }
复制代码

删除操作

  1. @DeleteMapping("/delete/book/novel")
  2. public ResponseEntity delete(@RequestParam(name = "id") String id)
  3. {
  4. DeleteResponse result = client.prepareDelete("book", "novel", id).get();
  5. return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
  6. }
复制代码

查找操作

  1. @GetMapping("/get/book/novel")
  2. public ResponseEntity get(@RequestParam(name = "id", defaultValue="") String id)
  3. {
  4. if (id.isEmpty())
  5. {
  6. return new ResponseEntity(HttpStatus.NOT_FOUND);
  7. }
  8. GetResponse result = this.client.prepareGet("book", "novel", id).get();
  9. if (!result.isExists())
  10. {
  11. return new ResponseEntity(HttpStatus.NOT_FOUND);
  12. }
  13. return new ResponseEntity(result.getSource(), HttpStatus.OK);
  14. }
复制代码

更新操作

  1. @PutMapping("/put/book/novel")
  2. public ResponseEntity update(@RequestParam(name = "id") String id, @RequestParam(name = "title", required = false) String title,
  3. @RequestParam(name = "author", required = false) String author
  4. )
  5. {
  6. try {
  7. XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
  8. if (title!= null)
  9. {
  10. builder.field("title", title);
  11. }
  12. if (author != null)
  13. {
  14. builder.field("author", author);
  15. }
  16. builder.endObject();
  17. UpdateRequest updateRequest = new UpdateRequest("book", "novel", id);
  18. updateRequest.doc(builder);
  19. UpdateResponse result = client.update(updateRequest).get();
  20. return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
  24. }
  25. }
复制代码

复合查找

  1. @GetMapping("/query/book/novel")
  2. public ResponseEntity query(@RequestParam(name = "author", required = false) String author,
  3. @RequestParam(name = "title", required = false) String title,
  4. @RequestParam(name = "gt_word_count", defaultValue = "0") int gtWordCount,
  5. @RequestParam(name = "lt_word_count", required = false) Integer ltWordCount)
  6. {
  7. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  8. if (author != null)
  9. {
  10. boolQueryBuilder.must(QueryBuilders.matchQuery("author",author));
  11. }
  12. if (title != null)
  13. {
  14. boolQueryBuilder.must(QueryBuilders.matchQuery("title", title));
  15. }
  16. RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
  17. if (ltWordCount != null && ltWordCount > 0)
  18. {
  19. rangeQueryBuilder.to(ltWordCount);
  20. }
  21. boolQueryBuilder.filter(rangeQueryBuilder);
  22. SearchRequestBuilder searchRequestBuilder = this.client.prepareSearch("book")
  23. .setTypes("novel")
  24. .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
  25. .setQuery(boolQueryBuilder)
  26. .setFrom(0)
  27. .setSize(10);
  28. System.out.println(searchRequestBuilder); //调试用
  29. SearchResponse response = searchRequestBuilder.get();
  30. List<Map<String, Object>> result = new ArrayList<>();
  31. for (SearchHit hit : response.getHits())
  32. {
  33. result.add(hit.getSource());
  34. }
  35. return new ResponseEntity(result, HttpStatus.OK);
  36. }
复制代码

上面的代码组织的复合查询类似下面的Query DSL:

  1. {
  2. "query":{
  3. "bool":{
  4. "must":[
  5. {"match":{"author":"张三"}},
  6. {"match":{"title":"Elasticsearch"}}
  7. ],
  8. "filter":[
  9. {"range":
  10. {"word_count":{
  11. "gt":"0",
  12. "lt":"3000"
  13. }
  14. }
  15. }
  16. ]
  17. }
  18. }
  19. }
复制代码

总结

以上所述是小编给大家介绍的SpringBoot整合Elasticsearch并实现CRUD操作,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对程序员之家网站的支持!



回复

使用道具 举报