下面是一个简单的 Spring Boot 示例,演示如何使用 Elasticsearch Java High Level REST Client 操作 Elasticsearch:
- 添加依赖
在 pom.xml 中添加以下依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.0</version>
</dependency>
- 配置连接
在 application.properties 文件中配置 Elasticsearch 连接信息:
spring.elasticsearch.rest.uris=http://localhost:9200
- 创建索引
创建一个索引,并向其中添加一些文档:
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class IndexService {
@Autowired
private RestHighLevelClient client;
public void createIndex() throws Exception {
// 创建索引请求对象
CreateIndexRequest request = new CreateIndexRequest("my_index");
// 设置索引的映射关系
request.mapping("{\n" +
" \"properties\": {\n" +
" \"title\": {\n" +
" \"type\": \"text\"\n" +
" },\n" +
" \"content\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}", XContentType.JSON);
// 发送请求并获取响应结果
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
// 处理响应结果
boolean acknowledged = response.isAcknowledged();
if (acknowledged) {
System.out.println("Index created successfully!");
} else {
System.out.println("Failed to create index.");
}
}
}
- 添加文档
向索引中添加一些文档:
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class DocumentService {
@Autowired
private RestHighLevelClient client;
public void addDocument() throws Exception {
// 创建 IndexRequest 对象,指定要添加的索引和文档 ID
IndexRequest request = new IndexRequest("my_index", "1");
// 创建文档数据
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("title", "Title 1")
.field("content", "This is the content of document 1.")
.endObject();
// 将文档数据添加到请求对象中
request.source(builder);
// 发送请求并获取响应结果
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
// 处理响应结果
String id = response.getId();
System.out.println("Document added successfully: " + id);
}
}
- 查询文档
查询索引中的文档:
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SearchService {
@Autowired
private RestHighLevelClient client;
public void searchDocuments() throws Exception {
// 创建 SearchRequest 对象,指定要搜索的索引
SearchRequest request = new SearchRequest("my_index");
// 构建查询条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchQuery("title", "Title 1"));
// 将查询条件添加到请求对象中
request.source(sourceBuilder);
// 发送请求并获取响应结果
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 处理响应结果
for (SearchHit hit : response.getHits().getHits()) {
System.out.println(hit.getSourceAsString());
}
}
}
- 在控制器中使用服务
将服务注入到控制器中,并在其中调用服务方法:
@RestController
@RequestMapping("/demo")
public class DemoController {
@Autowired
private IndexService indexService;
@Autowired
private DocumentService documentService;
@Autowired
private SearchService searchService;
@GetMapping("/createIndex")
public String createIndex() throws Exception {
indexService.createIndex();
return "Index created successfully!";
}
@GetMapping("/addDocument")
public String addDocument() throws Exception {
documentService.addDocument();
return "Document added successfully!";
}
@GetMapping("/searchDocuments")
public List<String> searchDocuments() throws Exception {
searchService.searchDocuments();
return "Search finished successfully!";
}
}
在这个示例中,我们创建了一个 Spring Boot 应用程序,并使用 Elasticsearch Java High Level REST Client 执行一些基本操作。你可以将这个示例作为起点,进一步扩展和定制它以适应你的实际需求。