elasticsearch · 2021-08-13 0

RestHighLevelClient操作ES

一、pom引入

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.13.0</version>
</dependency>

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.13.0</version>
</dependency>

引用到的类:

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
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.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

二、操作索引

1.是否存在索引

/**
 * 判断index是否存在
 */
@Test
public void testExistsIndex() throws IOException {
    String ip = "127.0.0.1:9200" ;
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";

    GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
    getIndexRequest.humanReadable(true);

    boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    System.out.println(exists);
}

2.新增索引

/**
 * 创建index和mapping
 */
@Test
public void testcreateIndex() throws IOException {
    String ip = "127.0.0.1:9200";
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";

    // 创建mappings
    Map<String,Object> name = new HashMap<>();
    name.put("type","text");
    Map<String,Object> age = new HashMap<>();
    age.put("type","integer");
    Map<String,Object> sex = new HashMap<>();
    sex.put("type","text");
    Map<String,Object> properties = new HashMap<>();
    properties.put("name",name);
    properties.put("age",age);
    properties.put("sex",sex);
    Map<String, Object> mapping = new HashMap<>();
    mapping.put("properties", properties);

    Map<String, Object> settings = new HashMap<>();
    settings.put("index.number_of_shards", 1);
    settings.put("index.number_of_replicas", 0);

    // 创建新建索引的请求对象
    CreateIndexRequest request = new CreateIndexRequest(indexName);
    // 通过CreateIndexRequest对象设置分片,副本和映射
    request.settings(settings);
    request.mapping(mapping);

    CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
    boolean acknowledged = createIndexResponse.isAcknowledged();
    boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();
    if(acknowledged && shardsAcknowledged){
        System.out.println("success");
    } else {
        System.out.println("failed");
    }
}

3.删除索引

/**
 * 删除index
 */
@Test
public void testDeleteIndex() throws IOException {
    String ip = "127.0.0.1:9200";
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";

    // 删除索引的请求对象
    DeleteIndexRequest request = new DeleteIndexRequest(indexName);

    AcknowledgedResponse acknowledgedResponse = client.indices().delete(request, RequestOptions.DEFAULT);
    boolean acknowledged = acknowledgedResponse.isAcknowledged();
    if(acknowledged){
        System.out.println("success");
    } else {
        System.out.println("failed");
    }
}

三、操作文档

1.是否存在文档

/**
 * 是否存在document
 */
@Test
public void testExistsData() throws IOException {
    String ip = "127.0.0.1:9200" ;
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";
    String id = "1";

    GetRequest getRequest = new GetRequest(indexName, id);
    boolean flag = client.exists(getRequest, RequestOptions.DEFAULT);

    System.out.println(flag);
}

2.新增文档

/**
 * 插入document
 */
@Test
public void testInsertData() throws IOException {
    String ip = "127.0.0.1:9200" ;
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";
    String id = "4";

    Map<String, Object> param = new HashMap<>();
    param.put("name", "zhangsan lisi");
    param.put("age", 44);
    param.put("sex", "female");

    IndexRequest indexRequest = new IndexRequest(indexName);
    indexRequest.id(id);
    indexRequest.source(param);

    IndexResponse indexResponse =  client.index(indexRequest, RequestOptions.DEFAULT);

    if (IndexResponse.Result.CREATED.equals(indexResponse.getResult())) {
        System.out.println("save");
    } else if (IndexResponse.Result.UPDATED.equals(indexResponse.getResult())) {
        System.out.println("update");
    } else {
        System.out.println("else");
    }
}

3.更新文档

/**
 * 更新document
 */
@Test
public void testUpdateData() throws IOException {
    String ip = "127.0.0.1:9200" ;
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";
    String id = "4";

    Map<String, Object> param = new HashMap<>();
    param.put("name", "zhangsan lisi");
    param.put("age", 55);
    param.put("sex", "female");

    UpdateRequest updateRequest = new UpdateRequest(indexName, id);
    // 如果修改索引中不存在则新增
    updateRequest.docAsUpsert(true);
    updateRequest.doc(param);

    UpdateResponse updateResponse =  client.update(updateRequest, RequestOptions.DEFAULT);

    if (UpdateResponse.Result.CREATED.equals(updateResponse.getResult())) {
        System.out.println("save");
    } else if (UpdateResponse.Result.UPDATED.equals(updateResponse.getResult())) {
        System.out.println("update");
    } else if (UpdateResponse.Result.NOOP.equals(updateResponse.getResult())) {
        System.out.println("noop");
    } else {
        System.out.println("else");
    }
}

4.查询文档

/**
 * 查询document
 */
@Test
public void testSelectData() throws IOException {
    String ip = "127.0.0.1:9200" ;
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";
    String id = "1";

    GetRequest getRequest = new GetRequest(indexName, id);
    GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
    String resultJson = getResponse.getSourceAsString();

    System.out.println(resultJson);
}

5.删除文档

/**
 * 删除document
 */
@Test
public void testDeleteData() throws IOException {
    String ip = "127.0.0.1:9200" ;
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";
    String id = "1";

    DeleteRequest deleteRequest = new DeleteRequest(indexName);
    deleteRequest.id(id);

    DeleteResponse updateResponse =  client.delete(deleteRequest, RequestOptions.DEFAULT);

    if (DeleteResponse.Result.DELETED.equals(updateResponse.getResult())) {
        System.out.println("deleted");
    } else if (DeleteResponse.Result.NOT_FOUND.equals(updateResponse.getResult())) {
        System.out.println("not_found");
    } else {
        System.out.println("else");
    }
}

四、索引文档

@Test
public void testQueryData1() throws IOException {
    String ip = "127.0.0.1:9200" ;
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";

    SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();;
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());

    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.source(searchSourceBuilder);

    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

    System.out.println(searchResponse);

    System.out.println("- - - - - - - - - - - -");

    SearchHits searchHits = searchResponse.getHits();
    SearchHit[] searchHit = searchHits.getHits();
    Arrays.stream(searchHit).map(SearchHit::getSourceAsString).forEach(System.out::println);
}
@Test
public void testQueryData2() throws IOException {
    String ip = "127.0.0.1:9200" ;
    HttpHost httpHost = HttpHost.create(ip);

    RestClientBuilder builder = RestClient.builder(httpHost);
    RestHighLevelClient client = new RestHighLevelClient(builder);

    String indexName = "student";

    TermQueryBuilder termQueryBuilder = new TermQueryBuilder("name", "zhangsan");

    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.preTags("<span style='color:red;'>");
    highlightBuilder.postTags("</span>");
    highlightBuilder.field("name");

    SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();;
    searchSourceBuilder
            // 设置查询关键词
            .query(termQueryBuilder)
            // 设置查询数据的位置,分页用
            .from(0)
            // 设置查询结果集的最大条数
            .size(10)
            // 不展示分析逻辑
            .explain(false)
            // 配置高亮
            .highlighter(highlightBuilder);

    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.source(searchSourceBuilder);

    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

    System.out.println(searchResponse);

    System.out.println("- - - - - - - - - - - -");

    SearchHits searchHits = searchResponse.getHits();
    SearchHit[] searchHit = searchHits.getHits();
    Arrays.stream(searchHit).map(SearchHit::getSourceAsString).forEach(System.out::println);
}