Configuration preparation
Add the following dependencies in the build.gradle file:
compile "org.elasticsearch.client:transport:5.5.2" compile "org.elasticsearch:elasticsearch:5.5.2" // es 5.x's internal use apache log4 log compile "org.apache.logging.log4j:log4j-core:2.7" compile "org.apache.logging.log4j:log4j-api:2.7"
Here, spring boot uses version 1.5.4. The official version of spring boot 2 has been released a few days ago. One of the new features of spring boot 2 is to support kotlin. Spring boot 2 is based on spring 5. Spring 5 also supports koltin, so spring has also begun to support functional programming.
About version compatibility
Configure the client that accesses Elasticsearch, and all use the native es JavaAPI here.
@Configurationpublic class ElasticSearchConfig { @Bean(name = "client") public TransportClient getClient() { InetSocketTransportAddress node = null; try { node = new InetSocketTransportAddress(InetAddress.getByName("192.168.124.128"), 9300); } catch (UnknownHostException e) { e.printStackTrace(); } Settings settings = Settings.builder().put("cluster.name", "my-es").build(); TransportClient client = new PreBuiltTransportClient(settings); client.addTransportAddress(node); return client; }}The SocketTransport port can be viewed using http://ip:9200/_nodes, and the default is to use port 9300.
CRUD operation
Create a new controller, ElasticSearchController, using the native es JavaAPI.
@RestControllerpublic class ElasticSearchController { @Autowired TransportClient client;}Adding methods for adding, deleting, searching and modifying in the controller
Add operations
@PostMapping("add/book/novel") public ResponseEntity add( @RequestParam(name = "title") String title, @RequestParam(name = "authro") 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); } }Delete operation
@DeleteMapping("/delete/book/novel") public ResponseEntity delete(@RequestParam(name = "id") String id) { DeleteResponse result = client.prepareDelete("book", "novel", id).get(); return new ResponseEntity(result.getResult().toString(), HttpStatus.OK); }Search operations
@GetMapping("/get/book/novel") 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); }Update operation
@PutMapping("/put/book/novel") public ResponseEntity update(@RequestParam(name = "id") String id, @RequestParam(name = "title", required = false) String title, @RequestParam(name = "author", required = false) String author ) { try { XContentBuilder builder = XContentFactory.jsonBuilder().startObject(); if (title!= null) { builder.field("title", title); } if (author != null) { builder.field("author", author); } builder.endObject(); UpdateRequest updateRequest = new UpdateRequest("book", "novel", id); updateRequest.doc(builder); UpdateResponse result = client.update(updateRequest).get(); return new ResponseEntity(result.getResult().toString(), HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } }Compound search
@GetMapping("/query/book/novel") 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 boolQueryBuilder = QueryBuilders.boolQuery(); if (author != null) { boolQueryBuilder.must(QueryBuilders.matchQuery("author",author)); } if (title != null) { boolQueryBuilder.must(QueryBuilders.matchQuery("title", title)); } RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("word_count").from(gtWordCount); if (ltWordCount != null && 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); //Debug SearchResponse response = searchRequestBuilder.get(); List<Map<String, Object>> result = new ArrayList<>(); for (SearchHit hit : response.getHits()) { result.add(hit.getSource()); } return new ResponseEntity(result, HttpStatus.OK); }The above code organizes compound queries similar to the following Query DSL:
{ "query":{ "bool":{ "must":[ {"match":{"author":"Zhang San"}}, {"match":{"title":"Elasticsearch"}} ], "filter":[ {"range": {"word_count":{ "gt":"0", "lt":"3000" } } } ] } }}Summarize
The above is what the editor introduced to SpringBoot integrates Elasticsearch and implements CRUD operations. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!