Java开发 - Elasticsearch初体验
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
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;
public class ElasticSearchExample {
public static void main(String[] args) {
// 初始化Elasticsearch客户端
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
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.getResult());
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭客户端
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这段代码展示了如何在Java中使用Elasticsearch的RestHighLevelClient来创建一个索引并索引一些数据。首先,它初始化了一个Elasticsearch客户端,然后创建了一个IndexRequest对象,并设置了要索引的数据。接着,它发送请求到Elasticsearch并打印了结果。最后,在完成操作后关闭了客户端。
评论已关闭