Spring Boot集成ElasticSearch
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
</dependencies>
@Configuration
public class ESConfig {
public TransportClient client() throws UnknownHostException {
// 9300是es的tcp服务端口
InetSocketTransportAddress node = new InetSocketTransportAddress(
InetAddress.getByName("192.168.190.129"),
9300);
// 设置es节点的配置信息
Settings settings = Settings.builder()
.put("cluster.name", "es")
.build();
// 实例化es的客户端对象
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(node);
return client;
}
}
@RestController
@RequestMapping( )
public class BookCrudController {
private TransportClient client;
/**
* 按id查询
* @param id
* @return
*/
public ResponseEntity searchById( String id) {
if (id.isEmpty()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
// 通过索引、类型、id向es进行查询数据
GetResponse response = client.prepareGet("book", "novel", id).get();
if (!response.isExists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
// 返回查询到的数据
return new ResponseEntity(response.getSource(), HttpStatus.OK);
}
}
@PostMapping( )
public ResponseEntity add( String title,
String author,
int wordCount,
Date publishDate) {
try {
// 将参数build成一个json对象
XContentBuilder content = XContentFactory.jsonBuilder()
.startObject()
.field("title", title)
.field("author", author)
.field("word_count", wordCount)
.field("publish_date", publishDate.getTime())
.endObject();
IndexResponse response = client.prepareIndex("book", "novel")
.setSource(content)
.get();
return new ResponseEntity(response.getId(), HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping( )
public ResponseEntity delete( String id) {
DeleteResponse response = client.prepareDelete("book", "novel", id).get();
return new ResponseEntity(response.getResult(), HttpStatus.OK);
}
"/update/book/novel") (
public ResponseEntity update( ("id") String id,
"title", required = false) String title, (value =
"author", required = false) String author, (value =
"word_count", required = false) Integer wordCount, (value =
"publish_date", required = false) (value =
"yyy-MM-dd HH:mm:ss") (pattern =
Date publishDate) {
UpdateRequest update = 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);
}
if (wordCount != null) {
builder.field("word_count", wordCount);
}
if (publishDate != null) {
builder.field("publish_date", publishDate.getTime());
}
builder.endObject();
update.doc(builder);
UpdateResponse response = client.update(update).get();
return new ResponseEntity(response.getResult().toString(), HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
"/query/book/novel") (
public ResponseEntity query( (value = "title", required = false) String title,
"author", required = false) String author, (value =
"word_count", required = false) Integer wordCount, (value =
"publish_date", required = false) (value =
"yyy-MM-dd HH:mm:ss") (pattern =
Date publishDate,
"gt_word_count", defaultValue = "0") Integer gtWordCount, (value =
"lt_word_count", required = false) Integer ltWordCount) { (value =
// 组装查询条件
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
if (title != null) {
boolQuery.must(QueryBuilders.matchQuery("title", title));
}
if (author != null) {
boolQuery.must(QueryBuilders.matchQuery("author", author));
}
if (wordCount != null) {
boolQuery.must(QueryBuilders.matchQuery("word_count", wordCount));
}
if (publishDate != null) {
boolQuery.must(QueryBuilders.matchQuery("publish_date", publishDate));
}
// 以word_count作为条件范围
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
if (ltWordCount != null && ltWordCount > 0) {
rangeQuery.to(ltWordCount);
}
boolQuery.filter(rangeQuery);
// 组装查询请求
SearchRequestBuilder requestBuilder = client.prepareSearch("book")
.setTypes("novel")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(boolQuery)
.setFrom(0)
.setSize(10);
// 发送查询请求
SearchResponse response = requestBuilder.get();
// 组装查询到的数据集
List<Map<String, Object>> result = new ArrayList<>();
for (SearchHit searchHitFields : response.getHits()) {
result.add(searchHitFields.getSource());
}
return new ResponseEntity(result, HttpStatus.OK);
}
如果喜欢本篇文章,欢迎转发、点赞。关注订阅号「Web项目聚集地」,回复「进群」即可进入无广告技术交流。
推荐阅读
1. 基于 Spring Boot 的 Restful 风格实现增删改查
在看
本文分享自微信公众号 - Java后端(web_resource)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
相关文章
暂无评论...