spring boot 整合elasticsearch
1.导入jar包
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>6.5.4</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.7</version> </dependency> </dependencies>
2.编写elasticsear远程连接配置文件
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; @Configuration public class ElasticSearchConfig { @Bean public TransportClient transportClient() throws Exception{ //此处需要使用elastic服务的tcp端口默认是9300 InetSocketTransportAddress master = new InetSocketTransportAddress(InetAddress.getByName("192.168.30.242"), 9300); InetSocketTransportAddress node1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.30.108"), 9300); InetSocketTransportAddress node2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.30.82"), 9300); Settings settings = Settings.builder().put("cluster.name", "elasticCluster").build(); TransportClient client = new PreBuiltTransportClient(settings); client.addTransportAddress(master); client.addTransportAddress(node1); client.addTransportAddress(node2); return client; } }
3.实现elasticsearch的基本操作
@RestController public class TestController { @Autowired private TransportClient transportClient; //查询 @GetMapping(value = "/get") public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) { if (id.isEmpty()) { return new ResponseEntity(HttpStatus.NOT_FOUND); } GetResponse result = transportClient.prepareGet("book", "novel", id).get(); if (!result.isExists()) { return new ResponseEntity(HttpStatus.NOT_FOUND); } return new ResponseEntity(result.getSource(), HttpStatus.OK); } //新增 @PostMapping(value = "/add") 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") String publishdate) { try { XContentBuilder content = XContentFactory.jsonBuilder() .startObject() .field("title", title) .field("author", author) .field("word_count", wordCount) .field("publish_date", publishdate).endObject(); IndexResponse result = transportClient.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); } } //删除 @GetMapping(value = "/delete") public ResponseEntity delete(@RequestParam(name = "id") String id) { DeleteResponse result = transportClient.prepareDelete("book", "novel", id).get(); return new ResponseEntity(result.getResult().toString(), HttpStatus.OK); } //修改 @PostMapping(value = "/update") 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 builder = XContentFactory.jsonBuilder().startObject(); if (title != null) { builder.field("title", title); } if (author != null) { builder.field("author", author); } builder.endObject(); updateRequest.doc(builder); UpdateResponse result = transportClient.update(updateRequest).get(); return new ResponseEntity(result.getResult().toString(), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } //复核查询 @PostMapping(value = "/query") public ResponseEntity query(@RequestParam(name = "author", required = false) String author, @RequestParam(name = "title", required = false) String title, @RequestParam(name = "gt_word_count", required = false) Integer 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 builder = transportClient.prepareSearch("book") .setTypes("novel") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(boolQueryBuilder) .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); }