【翻译】Elasticsearch Java API Client 8.13.2 (第二章-设置)
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
public class ElasticsearchJavaApiExample {
public static void main(String[] args) throws IOException {
// 配置Elasticsearch客户端
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
// 创建Elasticsearch客户端
try (RestClient restClient = builder.build()) {
ElasticsearchClient client = new ElasticsearchClient(restClient);
// 执行搜索请求
SearchRequest searchRequest = SearchRequest.of(sr ->
sr.index("kibana_sample_data_ecommerce"));
SearchResponse<JsonData> searchResponse = client.search(searchRequest, JsonData.class);
// 输出搜索结果
System.out.println(searchResponse.hits());
}
}
}
这段代码展示了如何使用Elasticsearch Java API Client库来配置和连接到Elasticsearch实例,并执行一个简单的搜索请求。它使用了Java的try-with-resources结构来确保资源得到正确释放。
评论已关闭