當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot集成Elastic Search
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot集成Elastic Search
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一.導(dǎo)入maven依賴
本機(jī)安裝的是6.5.4版本的Elastic Search,故這里導(dǎo)入6.5.4版本的Elastic Search依賴
? ?<properties><java.version>1.8</java.version><elasticsearch.version>6.5.4</elasticsearch.version></properties> ?<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>transport</artifactId><version>${elasticsearch.version}</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.7</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency> ?<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>二.創(chuàng)建配置類
1.Elastic Search的配置
-
需要在/conf/elasticsearch.yml配置node和cluster.name以及允許跨域訪問
conf/elasticsearch.yml
cluster.name: dayukeji node.name: dayutec ? http.cors.enabled: true http.cors.allow-origin: "*"2.創(chuàng)建配置類
9200作為Http協(xié)議,主要用于外部通訊
9300作為Tcp協(xié)議,jar之間就是通過Tcp協(xié)議通訊
ES集群之間是通過9300進(jìn)行通訊
@Configuration public class MyConfig {@Beanpublic TransportClient client() throws UnknownHostException { ?//配置settingSettings settings = Settings.builder().put("node.name", "dayutec").put("cluster.name", "dayukeji").build(); ?TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300)); ?return client;} ? }三.測試方法
先調(diào)用127.0.0.1:9200/book創(chuàng)建一個index
{"settings":{"number_of_shards":3,"number_of_replicas":1},"mappings":{"novel":{"properties":{"name":{"type":"text"},"price":{"type":"integer"},"word_count":{"type":"integer"}}}} }1.新增
? ?@PostMapping("/book/novel")public ResponseEntity add(@RequestParam("name") String name,@RequestParam("price") Integer price,@RequestParam(value = "word_count") int wordCount) {try {XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().field("name", name).field("price", price).field("word_count", wordCount).endObject();IndexResponse result = this.client.prepareIndex("book", "novel").setSource(xContentBuilder).get();return new ResponseEntity(result.getId(), HttpStatus.OK);} catch (IOException e) {e.printStackTrace();return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);}}2.獲取
? ?/*** 獲取** @param id* @return*/@GetMapping("/book/novel/{id}")public ResponseEntity get(@PathVariable("id") String id) {GetResponse result = this.client.prepareGet("book", "novel", id).get();if (result.isExists()) {return new ResponseEntity(result.getSource(), HttpStatus.OK);} else {return new ResponseEntity(HttpStatus.NOT_FOUND);}}3.修改
? ?@PutMapping("/book/novel/{id}")public ResponseEntity update(@PathVariable("id") String id,@RequestParam(value = "name", required = false) String name,@RequestParam(value = "price", required = false) Integer price) {UpdateRequest update = new UpdateRequest("book", "novel", id);try {XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject();if (name != null) {xContentBuilder.field("name", name);}if (price != null) {xContentBuilder.field("price", price);}xContentBuilder.endObject();update.doc(xContentBuilder);} catch (IOException e) {return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);}try {UpdateResponse result = this.client.update(update).get();return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);} catch (InterruptedException e) {return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);} catch (ExecutionException e) {return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);}}4.刪除
? ?@DeleteMapping("/book/novel/{id}")public ResponseEntity delete(@PathVariable("id") String id) {DeleteResponse result = this.client.prepareDelete("book", "novel", id).get();return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);}5.復(fù)雜查詢
? ?@GetMapping("/book/novel")public ResponseEntity query(@RequestParam(value = "name", required = false) String name,@RequestParam(value = "price", required = false) Integer price,@RequestParam(value = "gt_word_count", defaultValue = "0") Integer gtWordCount,@RequestParam(value = "lt_word_count", required = false) Integer ltWordCount) {BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();if (name != null) {boolQuery.must(QueryBuilders.matchQuery("name", name));}if (price != null) {boolQuery.must(QueryBuilders.matchQuery("price", price));}RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count").from(gtWordCount);if (ltWordCount != null && ltWordCount > 0) {rangeQuery.to(ltWordCount);}SearchResponse result = this.client.prepareSearch("book").setTypes("novel").setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(boolQuery).setFrom(0).setSize(10).get();List<Map<String, Object>> list = new ArrayList<>();for (SearchHit hit : result.getHits()) {list.add(hit.getSourceAsMap());}return new ResponseEntity(list, HttpStatus.OK);}?
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的Spring Boot集成Elastic Search的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Cloud(七) Gate
- 下一篇: java获取pdf的页数、内容和缩略图