Using Java to Operate Elasticsearch

Using Java to operate Elasticsearch can be achieved through the Elasticsearch client library provided by Java. The following are the steps to use Java to operate Elasticsearch: 1. Ensure that the Elasticsearch server has been installed and started. 2. Create a Java project and add Maven dependencies for the Elasticsearch client library. The following dependencies can be added to the pom.xml file of the project: <dependencies> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.15.1</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.15.1</version> </dependency> </dependencies> 3. Create an Elasticsearch client instance and specify the host and port number when connecting to the Elasticsearch service: import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); 4. Insert data. You can use the Index API to insert data: import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; IndexRequest request = new IndexRequest("index_name"); request.id("document_id"); request.source("field_name", "field_value"); IndexResponse response = client.index(request); 5. Modify data. You can use the Update API to modify data: import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; UpdateRequest request = new UpdateRequest("index_name", "document_id"); request.doc("field_name", "new_field_value"); UpdateResponse response = client.update(request); 6. Query data. You can use the Search API to query data: import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; SearchRequest request = new SearchRequest("index_name"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchAllQuery()); request.source(searchSourceBuilder); SearchResponse response = client.search(request); 7. Delete data. You can use the Delete API to delete data: import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; DeleteRequest request = new DeleteRequest("index_name", "document_id"); DeleteResponse response = client.delete(request); Finally, remember to close the Elasticsearch client connection at the end of the program: client.close(); The above are the basic steps and sample code for using Java to operate Elasticsearch. According to specific business requirements, other APIs can also be used to achieve more functions.