【elastic search】JAVA操作elastic search
以下是一个使用Java High Level REST Client操作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.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.common.xcontent.XContentType;
public class ElasticSearchExample {
public static void main(String[] args) throws IOException {
// 初始化RestHighLevelClient
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
// 创建索引
createIndex(client);
// 添加文档
indexDocument(client, "1", "{\"name\":\"John Doe\"}");
// 搜索文档
searchDocument(client, "John");
// 关闭客户端
client.close();
}
private static void createIndex(RestHighLevelClient client) throws IOException {
// 使用High Level REST Client创建索引
CreateIndexRequest request = new CreateIndexRequest("my_index");
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println("索引创建状态: " + createIndexResponse.isAcknowledged());
}
private static void indexDocument(RestHighLevelClient client, String id, String jsonString) throws IOException {
// 使用High Level REST Client索引文档
IndexRequest indexRequest = new IndexRequest("my_index");
indexRequest.id(id);
indexRequest.source(jsonString, XContentType.JSON);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println("文档索引状态: " + indexResponse.status());
}
private static void searchDocument(RestHighLevelClient client, String searchText) throws IOException {
// 使用High Level REST Client搜索文档
SearchRequest searchRequest = new SearchRequest("my_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder
评论已关闭