Elasticsearch8.x版本Java客户端Elasticsearch Java API Client中常用API练习
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.SearchHit;
public class ElasticsearchAPIExercize {
public static void main(String[] args) throws IOException {
// 初始化Elasticsearch客户端
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
// 创建一个SearchRequest对象
SearchRequest searchRequest = new SearchRequest("index_name"); // 替换为你的索引名
// 构建查询条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(/* 构建查询 */);
searchSourceBuilder.aggregation(/* 构建聚合 */);
searchSourceBuilder.size(10); // 设置返回结果数量
searchRequest.source(searchSourceBuilder);
// 执行搜索
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理搜索结果
for (SearchHit hit : searchResponse.getHits().getHits()) {
System.out.println(hit.getSourceAsString());
}
// 关闭客户端
client.close();
}
}
这个代码示例展示了如何在Elasticsearch 8.x版本中使用Java API Client进行基本的搜索操作。你需要替换index_name
为你的目标索引名,并且提供具体的查询条件。这个简单的例子演示了如何构建一个搜索请求,如何执行这个请求,并处理返回的结果。在实际应用中,你需要根据具体的查询需求来构建查询条件。
评论已关闭