JAVA API调用elasticsearch实现基本增删改查
以下是使用Java High Level REST Client API调用Elasticsearch实现基本增删改查操作的示例代码:
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.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
// 初始化Elasticsearch客户端
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
// 创建索引
IndexRequest indexRequest = new IndexRequest("index_name", "doc", "1");
indexRequest.source("field1", "value1");
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
// 获取文档
GetRequest getRequest = new GetRequest("index_name", "doc", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
// 更新文档
UpdateRequest updateRequest = new UpdateRequest("index_name", "doc", "1");
updateRequest.doc("field1", "value2");
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
// 删除文档
DeleteRequest deleteRequest = new DeleteRequest("index_name", "doc", "1");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
// 关闭客户端
client.close();
确保在运行代码前已经安装了Elasticsearch并且运行在本地的9200端口。以上代码仅为示例,实际使用时需要根据实际情况调整,比如索引名称、文档ID、字段名称和值等。
评论已关闭