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();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM