springboot整合elasticSearch
时间: 2023-10-08 13:11:11 浏览: 98
Spring Boot可以很方便地与Elasticsearch进行集成。下面是一个简单的示例:
1. 添加Elasticsearch客户端依赖
在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.0</version>
</dependency>
```
2. 配置Elasticsearch客户端
在application.properties中添加以下配置:
```properties
spring.elasticsearch.rest.uris=http://localhost:9200
```
3. 创建Elasticsearch客户端Bean
```java
@Configuration
public class ElasticsearchConfig {
@Value("${spring.elasticsearch.rest.uris}")
private String elasticsearchUrls;
@Bean
public RestHighLevelClient restHighLevelClient() {
String[] urls = elasticsearchUrls.split(",");
HttpHost[] httpHosts = new HttpHost[urls.length];
for (int i = 0; i < urls.length; i++) {
String url = urls[i];
httpHosts[i] = new HttpHost(url.split(":")[0], Integer.parseInt(url.split(":")[1]), "http");
}
RestClientBuilder builder = RestClient.builder(httpHosts);
return new RestHighLevelClient(builder);
}
}
```
4. 创建Elasticsearch操作类
```java
@Component
public class ElasticsearchTemplate {
@Autowired
private RestHighLevelClient restHighLevelClient;
public void index(String index, String id, String json) throws IOException {
IndexRequest request = new IndexRequest(index);
request.id(id);
request.source(json, XContentType.JSON);
restHighLevelClient.index(request, RequestOptions.DEFAULT);
}
public SearchHits search(String index, String keyword) throws IOException {
SearchRequest request = new SearchRequest(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchQuery("name", keyword));
request.source(builder);
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
return response.getHits();
}
}
```
5. 使用Elasticsearch操作类
```java
@RestController
public class ElasticsearchController {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@PostMapping("/index")
public void index(String index, String id, String json) throws IOException {
elasticsearchTemplate.index(index, id, json);
}
@GetMapping("/search")
public SearchHits search(String index, String keyword) throws IOException {
return elasticsearchTemplate.search(index, keyword);
}
}
```
这就是一个简单的Spring Boot整合Elasticsearch的示例。你可以根据自己的需求进行修改和扩展。
阅读全文