springboot整合elasticsearch4.3.6
时间: 2023-09-19 07:11:11 浏览: 129
最新版本springboot集成elasticsearch
1. 添加依赖
在pom.xml文件中添加elasticsearch依赖:
```xml
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>4.3.6</version>
</dependency>
```
2. 配置Elasticsearch
在application.properties中添加以下配置:
```properties
# Elasticsearch
elasticsearch.host=localhost
elasticsearch.port=9200
```
3. 创建Elasticsearch客户端
通过Elasticsearch客户端与Elasticsearch进行交互,创建一个Elasticsearch客户端:
```java
@Configuration
public class ElasticsearchConfig {
@Value("${elasticsearch.host}")
private String esHost;
@Value("${elasticsearch.port}")
private int esPort;
@Bean
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(
RestClient.builder(new HttpHost(esHost, esPort, "http")));
}
}
```
4. 创建Elasticsearch索引
创建一个Elasticsearch索引:
```java
@Service
public class ElasticsearchService {
private final String INDEX = "example";
private final String TYPE = "_doc";
private final RestHighLevelClient restHighLevelClient;
public ElasticsearchService(RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
public void createIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest(INDEX);
restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
}
public void deleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest(INDEX);
restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
}
}
```
5. 添加文档
添加一个文档到Elasticsearch:
```java
@Service
public class ElasticsearchService {
// ...
public void addDocument(String id, String content) throws IOException {
IndexRequest request = new IndexRequest(INDEX, TYPE, id)
.source(Collections.singletonMap("content", content));
restHighLevelClient.index(request, RequestOptions.DEFAULT);
}
}
```
6. 搜索文档
搜索文档:
```java
@Service
public class ElasticsearchService {
// ...
public SearchHits searchDocument(String keyword) throws IOException {
SearchRequest request = new SearchRequest(INDEX);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchQuery("content", keyword));
request.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
return response.getHits();
}
}
```
7. 测试
在测试类中测试以上方法:
```java
@SpringBootTest
class ElasticsearchApplicationTests {
@Autowired
private ElasticsearchService elasticsearchService;
@Test
void testCreateIndex() throws IOException {
elasticsearchService.createIndex();
}
@Test
void testAddDocument() throws IOException {
elasticsearchService.addDocument("1", "hello world");
}
@Test
void testSearchDocument() throws IOException {
SearchHits hits = elasticsearchService.searchDocument("hello");
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
}
```
以上是springboot整合elasticsearch的基本流程。
阅读全文