敖胤

绳锯木断,水滴石穿;聚沙成塔,集腋成裘。

导航

Java操作ES(一)—增删改

连接ES

创建maven工程

导入依赖的jar

需要导入ES依赖、ES高阶API依赖

<dependencies>
    <!--ES 依赖,版本需要与安装的ES一致-->
    <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>6.8.11</version>
    </dependency>

    <!--ES rest 高阶API-->
    <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>6.8.11</version>
    </dependency>

    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <!--lombok-->
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.20</version>
        <scope>provided</scope>
    </dependency>

    <!--fastjson-->
    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.75</version>
    </dependency>

</dependencies>

创建连接类

public static RestHighLevelClient getHighLevelClient() {
    //创建HttpHost
    HttpHost httpHost = new HttpHost("127.0.0.1", 9200);

    //构建clientBuilder
    RestClientBuilder clientBuilder = RestClient.builder(httpHost);

    //创建RestHighLevelClient
    RestHighLevelClient highLevelClient = new RestHighLevelClient(clientBuilder);

    return highLevelClient;
}

测试

import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Test;

public class ESClientTest {
    @Test
    public void getESClient() {
        RestHighLevelClient highLevelClient = ESClient.getHighLevelClient();
        System.out.println("OK");
    }
}

操作索引

创建索引

方式一

通过JsonXContent.contentBuilder()获取XContentBuilder对象,在构建CreateIndexRequest对象。

public class Index {
    public static RestHighLevelClient highLevelClient = ESClient.getHighLevelClient();
    public static String index ="nation";

    public static String type = "China";

    public static void createIndex() {
        //创建索引的settings
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 5)
                .put("number_of_replicas", 1);

        //准备索引的mappings结构
        XContentBuilder contentBuilder = null;
        CreateIndexRequest indexRequest = null;
        try {
            contentBuilder = JsonXContent.contentBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("name").field("type", "text").endObject()
                    .startObject("territory").field("type", "double").endObject()
                    .startObject("population").field("type", "long").endObject()
                    .startObject("liberation")
                    .field("type", "date")
                    .field("format", "yyyy-MM-dd")
                    .endObject()
                    .endObject()
                    .endObject();

            //将settings和mappings封装到一个IndexClient对象中
            indexRequest = new CreateIndexRequest(index)
                    .settings(settings)
                    .mapping(type, contentBuilder);

            //通过ESClient对象连接ES并创建索引
            highLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
方式二

通过字符串方式直接构建CreateIndexRequest对象。

public static void createIndex2() {
    //创建索引的settings
    Settings.Builder settings = Settings.builder()
            .put("number_of_shards", 5)
            .put("number_of_replicas", 1);

    //准备索引的mappings结构
    org.elasticsearch.client.indices.CreateIndexRequest indexRequest = null;

    String properties = "{\n" +
            "      \"properties\": {\n" +
            "        \"liberation\": {\n" +
            "          \"type\": \"date\",\n" +
            "          \"format\": \"yyyy-MM-dd\"\n" +
            "        },\n" +
            "        \"name\": {\n" +
            "          \"type\": \"text\"\n" +
            "        },\n" +
            "        \"population\": {\n" +
            "          \"type\": \"long\"\n" +
            "        },\n" +
            "        \"territory\": {\n" +
            "          \"type\": \"double\"\n" +
            "        }\n" +
            "      }\n" +
            "    }";
    //将settings和mappings封装到一个IndexClient对象中
    indexRequest = new org.elasticsearch.client.indices.CreateIndexRequest(index)
            .settings(settings)
            .mapping(properties, XContentType.JSON);

    //通过ESClient对象连接ES并创建索引
    CreateIndexResponse response = null;
    try {
        response = highLevelClient.indices().create(indexRequest,
                RequestOptions.DEFAULT);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(response.toString());

}
测试
@Test
public void createIndex() {
    Index.createIndex();
}

@Test
public void createIndex2() {
    Index.createIndex2();
}

在kibana中查看

判断索引是否存在

public static void isExistIndex() {
    GetIndexRequest request = new GetIndexRequest();
    request.indices(index);
    try {
        boolean exists = highLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

查询索引

public static void getIndex() {
    GetIndexRequest request = new GetIndexRequest();
    request.indices(index);
    try {
        GetIndexResponse indexResponse = highLevelClient.indices().get(request, RequestOptions.DEFAULT);
        for (ObjectObjectCursor<String, Settings> setting : indexResponse.getSettings()) {
            System.out.println(setting.index + "\t" + setting.key + "\t" + setting.value);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

返回结果如下:

7    nation
{
  "index.creation_date": "1626708168423",
  "index.number_of_replicas": "1",
  "index.number_of_shards": "5",
  "index.provided_name": "nation",
  "index.uuid": "4XDgsOITQ3CwI_qrtqEvlA",
  "index.version.created": "6081199"
}

删除索引

public static void deleteIndex() {
    DeleteIndexRequest request = new DeleteIndexRequest();
    request.indices(index);
    try {
        AcknowledgedResponse response = highLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

操作文档

添加文档

实体类

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Nation {

    @JSONField(serialize = false)
    private int id;

    private String name;

    private double territory;

    private long population;

    @JSONField(format = "yyyy-MM-dd")
    private Date liberation;
    
}

工具类

import com.alibaba.fastjson.JSON;
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;
import org.silence.entity.Nation;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

public class Doc {
    public static RestHighLevelClient highLevelClient = ESClient.getHighLevelClient();
    public static String index = "nation";

    public static String type = "China";

    public static void createDoc() {
        //准备JSON数据
        Calendar calendar = Calendar.getInstance();
        calendar.set(1949,9,1);
        Nation china = new Nation(1, "China", 957.13, 14000, new Date(calendar.getTimeInMillis()));
        String jsonString = JSON.toJSONString(china);

        //准备request对象
        IndexRequest request = new IndexRequest(index, type, String.valueOf(china.getId()));
        request.source(jsonString, XContentType.JSON);

        //通过client对象执行操作
        try {
            IndexResponse response = highLevelClient.index(request, RequestOptions.DEFAULT);
            System.out.println(JSON.toJSONString(response));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

返回结果

{
  "fragment": false,
  "id": "1",
  "index": "nation",
  "primaryTerm": 1,
  "result": "CREATED",
  "seqNo": 0,
  "shardId": {
    "fragment": true,
    "id": -1,
    "index": {
      "fragment": false,
      "name": "nation",
      "uUID": "_na_"
    },
    "indexName": "nation"
  },
  "shardInfo": {
    "failed": 0,
    "failures": [],
    "fragment": false,
    "successful": 1,
    "total": 2
  },
  "type": "China",
  "version": 1
}

修改文档

public static void updateDoc() {
    //创建map
    Map map = new HashMap();
    map.put("population", 15000);

    //准备request对象
    UpdateRequest request = new UpdateRequest(index, type, "1");
    request.doc(map);

    //通过client对象执行操作
    try {
        UpdateResponse response = highLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(response));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

删除文档

public static void deleteDoc() {
    //准备request对象
    DeleteRequest request = new DeleteRequest(index, type, "1");

    //通过client对象执行操作
    try {
        DeleteResponse response = highLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(response));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

批量添加

public static void bulkAddDocs() {
    //准备多个JSON数据
    Calendar calendar = Calendar.getInstance();
    calendar.set(1949,9,1);
    Nation china = new Nation(1, "China", 957.13, 14000, new Date(calendar.getTimeInMillis()));
    Nation america = new Nation(2, "China", 927.13, 4000, new Date(calendar.getTimeInMillis()));
    Nation england = new Nation(3, "China", 157.13, 1000, new Date(calendar.getTimeInMillis()));

    //准备request对象
    BulkRequest request = new BulkRequest();
    request.add(new IndexRequest(index, type, String.valueOf(china.getId())).source(china,XContentType.JSON));
    request.add(new IndexRequest(index, type, String.valueOf(america.getId())).source(america,XContentType.JSON));
    request.add(new IndexRequest(index, type, String.valueOf(england.getId())).source(england,XContentType.JSON));

    //通过client对象执行操作
    try {
        BulkResponse response = highLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(response));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

批量删除

public static void bulkDeleteDocs() {
    //准备request对象
    BulkRequest request = new BulkRequest();
    request.add(new DeleteRequest(index,type,"1"));
    request.add(new DeleteRequest(index,type,"2"));
    request.add(new DeleteRequest(index,type,"3"));

    //通过client对象执行操作
    try {
        BulkResponse response = highLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(response));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

posted on 2021-07-20 01:16  敖胤  阅读(2663)  评论(0编辑  收藏  举报