1、首先生成springboot maven工程
2、pom.xml 配置jar包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.es</groupId> <artifactId>demo</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>demoEs</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <elasticsearch.version>5.5.2</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> <scope>2.7</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
在application的同级目录下,新建myconf类
package com.es.demo; 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; import java.net.UnknownHostException; /** * Created by nicknailo on 2018/5/9. */ @Configuration public class Myconfig { @Bean public TransportClient client() throws UnknownHostException { InetSocketTransportAddress node = new InetSocketTransportAddress( InetAddress.getByName("localhost"),9300); Settings settings = Settings.builder() .put("cluster.name","nicknailo-elasticsearch") .put("client.transport.sniff",true) .build(); TransportClient client = new PreBuiltTransportClient(settings); client.addTransportAddress(node); return client; } }
3、增加配置
在resourse目录下添加配置log4j2.properties
appender.console.type = Console appender.console.name = console appender.console.layout.type = PatternLayout appender.console.layout.pattern = [%t] %-5p %c - %m%n rootLogger.level = info rootLogger.appenderRef.console.ref = console
4、写逻辑
package com.es.demo; import javafx.application.Application; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.search.SearchHit; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; @SpringBootApplication @RestController public class DemoEsApplication { @Autowired private TransportClient client; public static final org.slf4j.Logger logger = LoggerFactory.getLogger(DemoEsApplication.class); private static final String BOOK_INDEX = "book"; private static final String BOOK_TYPE_NOVEL = "novel"; @GetMapping("/get/book/novel") @ResponseBody public ResponseEntity get(@RequestParam(name = "id",defaultValue = "")String id){ if(id.isEmpty()){ return new ResponseEntity(HttpStatus.NOT_FOUND); } GetResponse result = this.client.prepareGet(BOOK_INDEX,BOOK_TYPE_NOVEL,id).get(); if (!result.isExists()){ return new ResponseEntity(HttpStatus.NOT_FOUND); } return new ResponseEntity(result.getSource(), HttpStatus.OK); } @PostMapping("add/book/novel") @ResponseBody 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") 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_INDEX,BOOK_TYPE_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") @ResponseBody public ResponseEntity delete(@RequestParam(name = "id")String id ){ DeleteResponse response = client.prepareDelete(BOOK_INDEX,BOOK_TYPE_NOVEL,id).get(); return new ResponseEntity(response.getResult().toString(),HttpStatus.OK); } @PutMapping("/update/book/novel") @ResponseBody public ResponseEntity update( @RequestParam(name = "id") String id, @RequestParam(name = "title", required = false) String title, @RequestParam(name = "author", required = false) String author, @RequestParam(name = "word_count", required = false) Integer wordCount, @RequestParam(name = "publish_date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date publishDate){ UpdateRequest request = new UpdateRequest(BOOK_INDEX,BOOK_TYPE_NOVEL,id); try { XContentBuilder builder = XContentFactory.jsonBuilder().startObject(); if (title != null){ builder.field("title",title); } if (author != null){ builder.field("author",author); } if (wordCount != null){ builder.field("word_count",wordCount); } if (publishDate != null){ builder.field("publish_date",publishDate.getTime()); } builder.endObject(); request.doc(builder); } catch (IOException e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } try { UpdateResponse response = this.client.update(request).get(); return new ResponseEntity(response.getResult().toString(),HttpStatus.OK); } catch (InterruptedException e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } catch (ExecutionException e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } @PostMapping("query/book/novel") @ResponseBody 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 rangeQuery = QueryBuilders.rangeQuery("word_count").from(gtWordCount); if(ltWordCount != null && ltWordCount > 0){ rangeQuery.to(ltWordCount); } boolQueryBuilder.filter(rangeQuery); SearchRequestBuilder builder = client.prepareSearch(BOOK_INDEX).setTypes(BOOK_TYPE_NOVEL) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(boolQueryBuilder) .setFrom(0) .setSize(10); logger.debug(builder.toString()); SearchResponse response = builder.get(); List result = new ArrayList<Map<String,Object>>(); for (SearchHit hit : response.getHits()){ result.add(hit.getSourceAsMap()); } return new ResponseEntity(result,HttpStatus.OK); } public static void main(String[] args) { SpringApplication.run(DemoEsApplication.class, args); } }
好了,可以测试了。
5、测试