0%

SpringBoot集成elasticsearch

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!--实体工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
spring:
data:
elasticsearch:
cluster-name: es-cluster
#配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode(9200端口是http查询使用的。9300集群使用。这里使用9300.)
cluster-nodes: 127.0.0.1:9300
properties:
path:
#elasticsearch日志存储目录
logs: ./elasticsearch/log
#elasticsearch数据存储目录
data: ./elasticsearch/data

Country.java

1
2
3
4
5
6
7
8
9
@Data
public class Country implements Serializable {
@Id
private Integer id;

@Field(searchAnalyzer = "ik_max_word",analyzer = "ik_smart")
private String name;

}

CountrySearchRepository.java

1
2
public interface CountrySearchRepository extends ElasticsearchRepository<Country, Long> {
}

单元测试 EsDemoApplicationTests.java

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
@SpringBootTest
public class EsDemoApplicationTests {
@Autowired
private CountrySearchRepository countrySearchRepository;

@Test
public void testSaveCountryIndex() {
Country country = new Country();
country.setId(1);
country.setName("China");
Country country2 = new Country();
country2.setId(2);
country2.setName("America");
List<Country> countryList = new ArrayList<>(2);
countryList.add(country);
countryList.add(country2);
countrySearchRepository.saveAll(countryList);
}

@Test
public void testSearch() {
//搜索关键字
String queryString = "china";
QueryStringQueryBuilder builder=new QueryStringQueryBuilder(queryString);
Iterable<Country> searchResult = countrySearchRepository.search(builder);
Iterator<Country> iterator = searchResult.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}

}