ElasticSearch与Java集成:掌握REST API和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;
public class ElasticSearchExample {
public static void main(String[] args) {
// 初始化RestHighLevelClient
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 with Java High Level REST Client\"" +
"}";
request.source(jsonString, XContentType.JSON);
// 执行索引请求
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
// 打印索引响应
System.out.println("Index Response Status:" + indexResponse.getResult());
System.out.println("Index Response Index:" + indexResponse.getIndex());
System.out.println("Index Response Type:" + indexResponse.getType());
System.out.println("Index Response ID:" + indexResponse.getId());
System.out.println("Index Response Version:" + indexResponse.getVersion());
System.out.println("Index Response Result:" + indexResponse.getResult());
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭RestHighLevelClient
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这段代码展示了如何使用Elasticsearch Java High Level REST Client来索引一个JSON文档。首先,它创建了一个RestHighLevelClient
实例,然后构建了一个IndexRequest
,设置了文档的索引名、ID和内容,并执行了请求。最后,它打印了响应结果,并在完成后关闭了客户端。这是一个简单的例子,展示了如何将Java与Elasticsearch集成,并通过REST API进行交互。
评论已关闭