elasticsearch 集成springboot 配置
时间: 2023-09-16 08:08:00 浏览: 96
详解Elastic Search搜索引擎在SpringBoot中的实践
1. 添加依赖
在 `pom.xml` 文件中添加 elasticsearch 和 spring-boot-starter-data-elasticsearch 依赖:
```
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 配置连接信息
在 `application.properties` 文件中配置连接信息:
```
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.cluster-name=my-application
```
3. 创建 Elasticsearch 配置类
创建一个 Elasticsearch 配置类,用于配置 ElasticsearchTemplate:
```
@Configuration
public class ElasticsearchConfig {
@Bean
public ElasticsearchTemplate elasticsearchTemplate() throws UnknownHostException {
return new ElasticsearchTemplate(client());
}
@Bean
public Client client() throws UnknownHostException {
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
return client;
}
}
```
4. 创建实体类
创建一个实体类,用于映射 Elasticsearch 中的索引:
```
@Document(indexName = "myindex", type = "mytype")
public class MyEntity {
@Id
private String id;
private String name;
private String description;
// getters and setters
}
```
5. 创建 Elasticsearch Repository
创建一个 Elasticsearch Repository,用于操作 Elasticsearch 中的索引:
```
public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> {
}
```
6. 使用 Elasticsearch Repository
在需要使用 Elasticsearch 的地方注入 MyEntityRepository,并使用其中的方法对 Elasticsearch 进行操作:
```
@Autowired
private MyEntityRepository myEntityRepository;
public void search() {
String query = "test";
List<MyEntity> result = myEntityRepository.findByNameOrDescription(query, query);
}
```
阅读全文