ES客户端RestHighLevelClient的使用
RestHighLevelClient
是 Elasticsearch 的一个高级客户端,它提供了基于Elasticsearch的REST API的高级API。以下是一个使用 RestHighLevelClient
的示例,它创建了一个索引,添加了一些文档,并执行了一个简单的搜索。
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
public class ElasticsearchExample {
public static void main(String[] args) throws IOException {
// 创建RestHighLevelClient客户端
try (RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")))) {
// 创建索引
CreateIndexRequest request = new CreateIndexRequest("my_index");
client.indices().create(request, RequestOptions.DEFAULT);
// 添加文档
IndexRequest indexRequest = new IndexRequest("my_index");
indexRequest.id("1");
indexRequest.source(XContentType.JSON, "title", "Some title");
client.index(indexRequest, RequestOptions.DEFAULT);
// 确保文档被索引
client.flush(new FlushRequest("my_index"), RequestOptions.DEFAULT);
// 搜索请求
SearchRequest searchRequest = new SearchRequest("my_index");
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchQuery("title", "title")));
// 执行搜索
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse.toString());
}
}
}
在这个例子中,我们首先创建了一个 RestHighLevelClient
实例,然后创建了一个名为 "my\_index" 的索引。接着,我们向该索引添加了一个文档,并使用 flush
方法确保文档被立即索引。最后,我们执行了一个基本的搜索,搜索索引中所有标题包
评论已关闭