SpringBoot整合Elasticsearch并實(shí)現(xiàn)CRUD操作
配置準(zhǔn)備
在build.gradle文件中添加如下依賴:
compile "org.elasticsearch.client:transport:5.5.2" compile "org.elasticsearch:elasticsearch:5.5.2" //es 5.x的內(nèi)部使用的 apache log4日志 compile "org.apache.logging.log4j:log4j-core:2.7" compile "org.apache.logging.log4j:log4j-api:2.7"
這里spring boot使用的是1.5.4版,前些天spring boot 2正式版已經(jīng)發(fā)布,spring boot 2新特性中有一條是支持kotlin,spring boot 2基于spring 5,spring 5也支持了koltin,所以spring也開(kāi)始支持函數(shù)式編程。
關(guān)于版本兼容
配置訪問(wèn)Elasticsearch的客戶端,這里都使用原生es JavaAPI。
@Configuration public 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; } }
SocketTransport端口可以使用http://ip:9200/_nodes方式查看,這里默認(rèn)使用的是9300端口。
CRUD操作
新建一個(gè)控制器ElasticSearchController,使用原生的es JavaAPI。
@RestController public class ElasticSearchController { @Autowired TransportClient client; }
在控制器中添加增刪查改方法
增加操作
@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); } }
刪除操作
@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); }
查找操作
@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); }
更新操作
@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); } }
復(fù)合查找
@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); //調(diào)試用 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); }
上面的代碼組織的復(fù)合查詢類似下面的Query DSL:
{ "query":{ "bool":{ "must":[ {"match":{"author":"張三"}}, {"match":{"title":"Elasticsearch"}} ], "filter":[ {"range": {"word_count":{ "gt":"0", "lt":"3000" } } } ] } } }
總結(jié)
以上所述是小編給大家介紹的SpringBoot整合Elasticsearch并實(shí)現(xiàn)CRUD操作,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- 解決SpringBoot整合ElasticSearch遇到的連接問(wèn)題
- SpringBoot整合Elasticsearch游標(biāo)查詢的示例代碼(scroll)
- es(elasticsearch)整合SpringCloud(SpringBoot)搭建教程詳解
- SpringBoot整合Spring Data Elasticsearch的過(guò)程詳解
- SpringBoot整合Elasticsearch7.2.0的實(shí)現(xiàn)方法
- 解決springboot無(wú)法注入JpaRepository的問(wèn)題
- SpringBoot3整合 Elasticsearch 8.x 使用Repository構(gòu)建增刪改查示例應(yīng)用
相關(guān)文章
基于Javamail實(shí)現(xiàn)發(fā)送郵件(QQ/網(wǎng)易郵件服務(wù)器)
這篇文章主要介紹了基于Javamail實(shí)現(xiàn)發(fā)送郵件,分別使用QQ郵箱作為smtp郵件服務(wù)器發(fā)送郵件,使用網(wǎng)易郵箱作為smtp郵件服務(wù)器發(fā)送郵件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08java中String、StringBuffer與StringBuilder的區(qū)別
這篇文章主要介紹了java 中String和StringBuffer與StringBuilder的區(qū)別,在開(kāi)發(fā)過(guò)程中經(jīng)常會(huì)用到String這個(gè)類進(jìn)行操作。需要的朋友可以收藏下,方便下次瀏覽觀看2021-12-12解決CentOS7中運(yùn)行jar包報(bào)錯(cuò):xxx(Permission?denied)
在實(shí)際工作我們經(jīng)常會(huì)在linux上運(yùn)行Spring boot編寫(xiě)的微服務(wù)程序,下面這篇文章主要給大家介紹了關(guān)于如何解決CentOS7中運(yùn)行jar包報(bào)錯(cuò):xxx(Permission?denied)的相關(guān)資料,需要的朋友可以參考下2024-02-02Java常用類庫(kù)Apache Commons工具類說(shuō)明及使用實(shí)例詳解
這篇文章主要介紹了Java常用類庫(kù)Apache Commons工具類說(shuō)明及使用實(shí)例詳解,需要的朋友可以參考下2020-02-02Feign 集成 Hystrix實(shí)現(xiàn)不同的調(diào)用接口不同的設(shè)置方式
這篇文章主要介紹了Feign 集成 Hystrix實(shí)現(xiàn)不同的調(diào)用接口不同的設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06