文章目录
  1. 1. Spring Boot集成ES
  2. 2. 环境
    1. 2.1. Spring Boot集成ElasticSearch
    2. 2.2. 查询接口开发
    3. 2.3. 增加接口开发
    4. 2.4. 删除接口开发
    5. 2.5. 更新接口开发
    6. 2.6. 复合接口查询开发

Spring Boot集成ES

包含Spring Boot集成ElasticSearch、查询接口开发、增加接口开发、删除接口开发、更新接口开发、复合查询接口开发

环境

1
2
3
idea:Intellij IDEA
jdk.version:1.8
es.version:5.5.2

Spring Boot集成ElasticSearch

https://start.spring.io/创建一个spring boot项目,具体依赖如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?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.knight</groupId>
<artifactId>es-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>es-demo</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>
<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</artifactId>
</dependency>
<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>
<!--idea需要添加lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

log4j的配置如下:

1
2
3
4
5
6
7
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatterLayout
appender.console.layout.patter = [%t] %-5p %c - %m%n
rootLogger.level = info
rootLogger.appenderRef.console.ref = console

新建一个Config类配置ES:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.knight.esdemo;
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;
/**
* @author knight
*/
@Configuration
public class MyConfig {
@Bean
public TransportClient client() throws UnknownHostException {
// 这里是TCP端口
InetSocketTransportAddress node = new InetSocketTransportAddress(
InetAddress.getByName("192.168.137.8"),
9300);
Settings settings = Settings.builder().put("cluster.name", "wali").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(node);
return client;
}
}

整体项目结构如下:

springboot集成es-项目结构

查询接口开发

添加一个查询接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.knight.esdemo;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class EsDemoApplication {
@Autowired
private TransportClient client;
@GetMapping("/book/novel")
@ResponseBody
public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) {
if (id.isEmpty()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
GetResponse result = client.prepareGet("book", "novel", id).get();
if (!result.isExists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
return new ResponseEntity(result.getSource(), HttpStatus.OK);
}
@GetMapping("/")
public String index() {
return "index";
}
public static void main(String[] args) {
SpringApplication.run(EsDemoApplication.class, args);
}
}

增加接口开发

添加增加接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 增加接口
* @param title 标题
* @param author 作者
* @param wordCount 字数
* @param publishDate 出版日期
* @return
*/
@PostMapping("/add/book/novel")
@ResponseBody
public ResponseEntity add(@RequestParam(name = "title") String title,
@RequestParam(name = "author") String author,
@RequestParam(name = "wordcount") int wordCount,
@RequestParam(name = "publish_date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date publishDate) {
try {
XContentBuilder content = XContentFactory.jsonBuilder()
.startObject()
.field("title", title)
.field("author", author)
.field("wordcount", wordCount)
.field("publish_date", publishDate.getTime())
.endObject();
IndexResponse response = client.prepareIndex("book", "novel").setSource(content).get();
return new ResponseEntity(response, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}

删除接口开发

1
2
3
4
5
6
7
8
9
10
11
/**
* 删除接口
* @param id 文档id
* @return
*/
@DeleteMapping("delete/book/novel")
@ResponseBody
public ResponseEntity delete(@RequestParam(name = "id") String id) {
DeleteResponse result = client.prepareDelete("book", "novel", id).get();
return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
}

更新接口开发

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 更新接口
*
* @param id 更新的文档id
* @param title 更新文档的title
* @param author 更新文档的author
* @return
*/
@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
) {
// 构建更新请求对象
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);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
try {
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);
}
}

下面这种方式也能更新:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 更新接口
*
* @param id 更新的文档id
* @param title 更新文档的title
* @param author 更新文档的author
* @return
*/
@PutMapping("other/update/book/novel")
@ResponseBody
public ResponseEntity otherUpdate(
@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();
UpdateResponse result = client.prepareUpdate("book", "novel", id).setDoc(builder).get();
return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}

复合接口查询开发

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* 复合查询接口
* @param author 作者
* @param title 标题
* @param gtwordCount 字数范围查询
* @param ltwordCount 字数范围查询
* @return
*/
@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 boolQuery = QueryBuilders.boolQuery();
if (author != null) {
boolQuery.must(QueryBuilders.matchQuery("author", author));
}
if (title != null) {
boolQuery.must(QueryBuilders.matchQuery("title", title));
}
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("wordcount").gt(gtwordCount);
if (ltwordCount != null && ltwordCount > 0) {
rangeQuery.lt(ltwordCount);
}
boolQuery.filter(rangeQuery);
SearchRequestBuilder builder = client.prepareSearch("book").setTypes("novel").
setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(boolQuery).setFrom(0).setSize(20);
System.out.println(builder);
SearchResponse searchResponse = builder.get();
ArrayList<Map<String, Object>> results = new ArrayList<>();
for (SearchHit hit : searchResponse.getHits()) {
results.add(hit.getSource());
}
return new ResponseEntity(results, HttpStatus.OK);
}
文章目录
  1. 1. Spring Boot集成ES
  2. 2. 环境
    1. 2.1. Spring Boot集成ElasticSearch
    2. 2.2. 查询接口开发
    3. 2.3. 增加接口开发
    4. 2.4. 删除接口开发
    5. 2.5. 更新接口开发
    6. 2.6. 复合接口查询开发