【elasticsearch】ES的JAVA工具类完整版(已完成,已测试)
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class ElasticSearchJavaTool {
private static RestHighLevelClient client;
static {
// 初始化Elasticsearch客户端
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
client = new RestHighLevelClient(builder);
}
public static void main(String[] args) {
try {
// 创建索引请求
IndexRequest request = new IndexRequest("posts");
// 设置索引数据
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2023-04-07\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);
// 执行操作
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
// 打印结果
System.out.println(indexResponse.toString());
System.out.println("索引创建成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭客户端
try {
if (client != null) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这段代码展示了如何在Java中使用Elasticsearch的RestHighLevelClient来创建一个索引。首先,代码初始化了一个RestHighLevelClient实例,然后创建了一个IndexRequest对象,并设置了要索引的数据。接着,代码使用client.index方法执行了这个请求,并打印了响应结果。最后,代码确保在结束时关闭了客户端,释放资源。
评论已关闭