Elasticsearch 实战:Elasticsearch Java API 文档增删改查操作
使用 Elasticsearch Java API 进行文档的增删改查操作,主要包括索引文档、获取文档、更新文档、删除文档等。以下是一些常见文档操作的示例:
**1. **索引文档(Index)
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
public class DocumentIndexExample {
public String indexDocument(RestHighLevelClient client, String indexName, String documentId, String jsonContent) throws IOException {
IndexRequest request = new IndexRequest(indexName)
.id(documentId)
.source(jsonContent, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
return response.getResult().toString(); // 返回索引操作结果(created、updated 或 noop)
}
}
**2. **获取文档(Get)
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
public class DocumentGetExample {
public String getDocument(RestHighLevelClient client, String indexName, String documentId) throws IOException {
GetRequest request = new GetRequest(indexName, documentId);
GetResponse response = client.get(request, RequestOptions.DEFAULT);
return response.getSourceAsString(); // 返回文档源 JSON 字符串
}
}
**3. **更新文档(Update)
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
public class DocumentUpdateExample {
public String updateDocument(RestHighLevelClient client, String indexName, String documentId, String jsonPatch) throws IOException {
UpdateRequest request = new UpdateRequest(indexName, documentId)
.doc(jsonPatch, XContentType.JSON);
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
return response.getResult().toString(); // 返回更新操作结果(updated 或noop)
}
}
**4. **删除文档(Delete)
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
public class DocumentDeleteExample {
public boolean deleteDocument(RestHighLevelClient client, String indexName, String documentId) throws IOException {
DeleteRequest request = new DeleteRequest(indexName, documentId);
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
return response.getResult().equals(DocWriteResponse.Result.DELETED); // 返回是否成功删除文档
}
}
以上示例展示了如何使用 Elasticsearch Java API 进行文档的索引、获取、更新和删除操作。在实际应用中,根据业务需求调用相应的方法进行文档管理。记得处理可能出现的异常,并确保客户端在使用完毕后正确关闭。对于复杂的文档更新,可以使用 script
或 upsert
等高级选项。