Skip to content

Commit 6e57e5b

Browse files
committed
Spring Boot 中使用 java API 方式操作 Elasticsearch
1 parent 1c19fcd commit 6e57e5b

9 files changed

Lines changed: 490 additions & 1 deletion

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>io.ymq.example</groupId>
7+
<artifactId>elasticsearch</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>jar</packaging>
10+
11+
<name>elasticsearch</name>
12+
<description>Demo project for Spring Boot</description>
13+
14+
<parent>
15+
<groupId>org.springframework.boot</groupId>
16+
<artifactId>spring-boot-starter-parent</artifactId>
17+
<version>1.5.8.RELEASE</version>
18+
<relativePath/> <!-- lookup parent from repository -->
19+
</parent>
20+
21+
<properties>
22+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24+
<java.version>1.8</java.version>
25+
26+
<elasticsearch.version>5.5.3</elasticsearch.version>
27+
<log4j2.version>2.6.2</log4j2.version>
28+
</properties>
29+
30+
<dependencies>
31+
<dependency>
32+
<groupId>org.springframework.boot</groupId>
33+
<artifactId>spring-boot-starter</artifactId>
34+
</dependency>
35+
36+
<dependency>
37+
<groupId>org.springframework.boot</groupId>
38+
<artifactId>spring-boot-starter-test</artifactId>
39+
<scope>test</scope>
40+
</dependency>
41+
42+
<dependency>
43+
<groupId>org.elasticsearch</groupId>
44+
<artifactId>elasticsearch</artifactId>
45+
<version>${elasticsearch.version}</version>
46+
</dependency>
47+
48+
<dependency>
49+
<groupId>org.elasticsearch.client</groupId>
50+
<artifactId>transport</artifactId>
51+
<version>${elasticsearch.version}</version>
52+
</dependency>
53+
54+
55+
56+
57+
</dependencies>
58+
59+
<build>
60+
<plugins>
61+
<plugin>
62+
<groupId>org.springframework.boot</groupId>
63+
<artifactId>spring-boot-maven-plugin</artifactId>
64+
</plugin>
65+
</plugins>
66+
</build>
67+
68+
69+
</project>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package io.ymq.example.elasticsearch.run;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.context.annotation.ComponentScan;
6+
7+
/**
8+
*
9+
*/
10+
@SpringBootApplication
11+
@ComponentScan(value = {"io.ymq.example.elasticsearch"})
12+
public class Startup {
13+
14+
public static void main(String[] args) {
15+
SpringApplication.run(Startup.class, args);
16+
}
17+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# elasticsearch
2+
elasticsearch.cluster.name=ymq
3+
elasticsearch.ip=192.168.252.121
4+
elasticsearch.port=9300
5+
elasticsearch.pool=5

‎spring-boot-elasticsearch-demo/src/main/resources/logback-spring.xml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<configuration>
33

44
<!-- 日志根目录-->
5-
<springProperty scope="context" name="LOG_HOME" source="logging.path" defaultValue="/data/logs/spring-boot-logback"/>
5+
<springProperty scope="context" name="LOG_HOME" source="logging.path" defaultValue="/data/logs/spring-boot-elasticsearch-demo"/>
66

77
<!-- 日志级别 -->
88
<springProperty scope="context" name="LOG_ROOT_LEVEL" source="logging.level.root" defaultValue="DEBUG"/>
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
package io.ymq.example.elasticsearch;
2+
3+
4+
import io.ymq.example.elasticsearch.run.Startup;
5+
import org.elasticsearch.action.index.IndexResponse;
6+
import org.elasticsearch.action.search.SearchRequestBuilder;
7+
import org.elasticsearch.action.search.SearchResponse;
8+
import org.elasticsearch.client.transport.TransportClient;
9+
import org.elasticsearch.index.query.QueryBuilders;
10+
import org.elasticsearch.search.SearchHit;
11+
12+
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
13+
import org.junit.Test;
14+
import org.junit.runner.RunWith;
15+
import org.slf4j.Logger;
16+
import org.slf4j.LoggerFactory;
17+
import org.springframework.beans.factory.annotation.Autowired;
18+
import org.springframework.boot.test.context.SpringBootTest;
19+
import org.springframework.test.context.junit4.SpringRunner;
20+
21+
import java.util.HashMap;
22+
import java.util.Map;
23+
import java.util.UUID;
24+
25+
/**
26+
* 单元测试
27+
*/
28+
@RunWith(SpringRunner.class)
29+
@SpringBootTest(classes = Startup.class)
30+
public class BaseTests {
31+
32+
private static final Logger LOGGER = LoggerFactory.getLogger(BaseTests.class);
33+
34+
@Autowired
35+
private TransportClient transportClient;
36+
37+
/**
38+
* ES的基本类型可以去官网查看
39+
* 如果您使用map的方式去写入数据并且创建索引,es会自动根据map的value数据类型来自动转换
40+
* 比如age是int,es里面使用有integer,不赘述
41+
* 使用map有个大缺陷(除非自己封装对象保存),当你保存java.util.Date类型进去的时候ES会全部转成UTC来保存
42+
* 这个只能通过后面的api方式定义索引field的一些属性来指定才行
43+
**/
44+
@Test
45+
public void createData() {
46+
Map<String, Object> map = new HashMap<String, Object>();
47+
48+
map.put("name", "鹏磊");
49+
map.put("age", 24);
50+
map.put("interests", new String[]{"阅读", "学习"});
51+
map.put("about", "我是鹏磊,认识自己的无知是认识世界的最可靠的方法。");
52+
53+
/*
54+
map.put("name", "鹏磊");
55+
map.put("age", 21);
56+
map.put("interests", new String[]{"阅读", "学习"});
57+
map.put("about", "我是鹏磊,世界上没有优秀的理念,只有脚踏实地的结果");
58+
*/
59+
60+
IndexResponse response = transportClient.prepareIndex("about_index", "about", UUID.randomUUID().toString()).setSource(map).get();
61+
62+
System.out.println("写入数据结果=" + response.status().getStatus() + "!id=" + response.getId());
63+
}
64+
65+
66+
/**
67+
* match 使用,会被分词查询
68+
*/
69+
@Test
70+
public void match() {
71+
SearchRequestBuilder requestBuilder = transportClient.prepareSearch("about_index").setTypes("about")
72+
.setQuery(QueryBuilders.matchQuery("about", "鹏磊"));
73+
System.out.println(requestBuilder.toString());
74+
75+
SearchResponse response = requestBuilder.execute().actionGet();
76+
77+
long totalHits = response.getHits().totalHits;
78+
long length = response.getHits().getHits().length;
79+
LOGGER.debug("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
80+
81+
System.out.println(response.status());
82+
if (response.status().getStatus() == 200) {
83+
for (SearchHit hits : response.getHits().getHits()) {
84+
System.out.println(hits.getSourceAsString());
85+
}
86+
}
87+
}
88+
89+
90+
/**
91+
* matchphrase使用,短语精准匹配
92+
* 不使用matchPhraseQuery会导致 rock climbing被拆分查询
93+
*/
94+
@Test
95+
public void matchPhrase() {
96+
SearchRequestBuilder requestBuilder = transportClient.prepareSearch("about_index").setTypes("about")
97+
.setQuery(QueryBuilders.matchPhraseQuery("about", "鹏磊"));
98+
System.out.println(requestBuilder.toString());
99+
100+
SearchResponse response = requestBuilder.execute().actionGet();
101+
102+
long totalHits = response.getHits().totalHits;
103+
long length = response.getHits().getHits().length;
104+
LOGGER.debug("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
105+
106+
System.out.println(response.status());
107+
if (response.status().getStatus() == 200) {
108+
for (SearchHit hits : response.getHits().getHits()) {
109+
System.out.println(hits.getSourceAsString());
110+
}
111+
}
112+
}
113+
114+
/**
115+
* 高亮显示
116+
*/
117+
@Test
118+
public void highlight() {
119+
HighlightBuilder highlightBuilder = new HighlightBuilder();
120+
// highlightBuilder.preTags(FragmentSettings.prefix);//设置前缀
121+
// highlightBuilder.postTags(FragmentSettings.subfix);//设置后缀
122+
highlightBuilder.field("about");
123+
// highlightBuilder.fragmenter(FragmentSettings.SPAN)
124+
// .fragmentSize(FragmentSettings.HIGHLIGHT_MAX_WORDS).numOfFragments(5);
125+
SearchRequestBuilder requestBuilder = transportClient.prepareSearch("about_index").setTypes("about")
126+
.setQuery(QueryBuilders.matchPhraseQuery("about", "鹏磊")).highlighter(highlightBuilder);
127+
System.out.println(requestBuilder.toString());
128+
129+
SearchResponse response = requestBuilder.execute().actionGet();
130+
131+
long totalHits = response.getHits().totalHits;
132+
long length = response.getHits().getHits().length;
133+
LOGGER.debug("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
134+
135+
System.out.println(response.status());
136+
if (response.status().getStatus() == 200) {
137+
for (SearchHit hits : response.getHits().getHits()) {
138+
System.out.println(hits.getSourceAsString());
139+
// 这里使用hight field来覆盖source里面的字段即可
140+
System.out.println(hits.getHighlightFields());
141+
}
142+
}
143+
144+
}
145+
146+
147+
}

‎spring-boot-elasticsearch/pom.xml‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>io.ymq.example</groupId>
7+
<artifactId>spring-boot-elasticsearch</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>jar</packaging>
10+
11+
<name>spring-boot-elasticsearch</name>
12+
<description>Elasticsearch project for Spring Boot</description>
13+
14+
<parent>
15+
<groupId>org.springframework.boot</groupId>
16+
<artifactId>spring-boot-starter-parent</artifactId>
17+
<version>1.5.8.RELEASE</version>
18+
<relativePath/>
19+
</parent>
20+
21+
<properties>
22+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24+
<java.version>1.8</java.version>
25+
</properties>
26+
27+
<dependencies>
28+
<dependency>
29+
<groupId>org.springframework.boot</groupId>
30+
<artifactId>spring-boot-starter</artifactId>
31+
</dependency>
32+
<dependency>
33+
<groupId>org.springframework.boot</groupId>
34+
<artifactId>spring-boot-starter-test</artifactId>
35+
<scope>test</scope>
36+
</dependency>
37+
<!-- Spring Boot Elasticsearch 依赖 -->
38+
<dependency>
39+
<groupId>org.springframework.boot</groupId>
40+
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
41+
</dependency>
42+
43+
44+
45+
</dependencies>
46+
<build>
47+
<plugins>
48+
<plugin>
49+
<groupId>org.springframework.boot</groupId>
50+
<artifactId>spring-boot-maven-plugin</artifactId>
51+
</plugin>
52+
53+
<plugin>
54+
<groupId>org.apache.maven.plugins</groupId>
55+
<artifactId>maven-surefire-plugin</artifactId>
56+
<configuration>
57+
<skip>true</skip>
58+
<testFailureIgnore>true</testFailureIgnore>
59+
</configuration>
60+
</plugin>
61+
</plugins>
62+
</build>
63+
64+
65+
</project>
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package io.ymq.elasticsearch.run;
2+
3+
import io.ymq.elasticsearch.model.Book;
4+
import io.ymq.elasticsearch.service.BookService;
5+
import org.elasticsearch.client.Client;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.boot.CommandLineRunner;
8+
import org.springframework.boot.SpringApplication;
9+
import org.springframework.boot.autoconfigure.SpringBootApplication;
10+
import org.springframework.context.annotation.ComponentScan;
11+
12+
import org.springframework.data.domain.Page;
13+
import org.springframework.data.domain.PageRequest;
14+
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
15+
16+
import java.util.Map;
17+
18+
@SpringBootApplication
19+
@ComponentScan(value = {"io.ymq.elasticsearch"})
20+
public class Startup implements CommandLineRunner {
21+
22+
public static void main(String[] args) {
23+
SpringApplication.run(Startup.class, args);
24+
}
25+
26+
@Autowired
27+
private ElasticsearchOperations es;
28+
29+
@Autowired
30+
private BookService bookService;
31+
32+
@Override
33+
public void run(String... args) throws Exception {
34+
35+
printElasticSearchInfo();
36+
37+
bookService.save(new Book("1001", "Elasticsearch Basics", "Rambabu Posa", "23-FEB-2017"));
38+
bookService.save(new Book("1002", "Apache Lucene Basics", "Rambabu Posa", "13-MAR-2017"));
39+
bookService.save(new Book("1003", "Apache Solr Basics", "Rambabu Posa", "21-MAR-2017"));
40+
41+
//fuzzey search
42+
Page<Book> books = bookService.findByAuthor("Rambabu", new PageRequest(0, 10));
43+
44+
//List<Book> books = bookService.findByTitle("Elasticsearch Basics");
45+
46+
books.forEach(x -> System.out.println(x));
47+
48+
}
49+
50+
//useful for debug
51+
private void printElasticSearchInfo() {
52+
53+
System.out.println("--ElasticSearch-->");
54+
Client client = es.getClient();
55+
Map<String, String> asMap = client.settings().getAsMap();
56+
57+
asMap.forEach((k, v) -> {
58+
System.out.println(k + " = " + v);
59+
});
60+
System.out.println("<--ElasticSearch--");
61+
}
62+
63+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# elasticsearch
2+
elasticsearch.cluster.name=ymq
3+
elasticsearch.ip=192.168.252.121
4+
elasticsearch.port=9300
5+
elasticsearch.pool=5

0 commit comments

Comments
 (0)