ES基本操作

该代码示例展示了如何使用RestHighLevelClient进行Elasticsearch的基本操作,包括创建索引、查询索引、删除索引、添加文档、查询文档、更新文档以及批量操作。主要涉及的学生信息数据结构,使用了JSON格式进行序列化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ES基本操作

package com.atguigu.es;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
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.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.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;

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

public class ESTest {
    RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
            new HttpHost("localhost", 9200, "http")
    ));

    /**
     * 测试创建索引库
     */
    @Test
    public void testCreateIndex() throws IOException {
        // 创建createIndex对象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("students");
        createIndexRequest.mapping("{\n" +
                "    \"properties\": {\n" +
                "      \"name\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": true,\n" +
                "        \"store\": true\n" +
                "      },\n" +
                "      \"age\": {\n" +
                "        \"type\": \"integer\",\n" +
                "        \"index\": true,\n" +
                "        \"store\": true\n" +
                "      },\n" +
                "      \"remark\": {\n" +
                "        \"type\": \"text\",\n" +
                "        \"index\": true,\n" +
                "        \"store\": true,\n" +
                "        \"analyzer\": \"ik_max_word\",\n" +
                "        \"search_analyzer\": \"ik_max_word\"\n" +
                "      }\n" +
                "    }\n" +
                "  }", XContentType.JSON);
        // 创建索引
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        // 获取ack
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println("acknowledged = " + acknowledged);
    }

    /**
     * 查询索引
     */
    @Test
    public void testGetIndex() throws IOException {
        // 创建getIndex对象
        GetIndexRequest getIndexRequest = new GetIndexRequest("students");
        GetIndexResponse getIndexResponse = client.indices().get(getIndexRequest, RequestOptions.DEFAULT);
        // 获取结果
        Map<String, Settings> settings = getIndexResponse.getSettings();
        System.out.println("settings = " + settings);
        Map<String, MappingMetaData> mappings = getIndexResponse.getMappings();
        System.out.println("mappings = " + mappings);
    }

    /**
     * 删除索引
     */
    @Test
    public void testDeleteIndex() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("book");
        AcknowledgedResponse acknowledgedResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        boolean acknowledged = acknowledgedResponse.isAcknowledged();
        System.out.println("acknowledged = " + acknowledged);
    }

    /**
     * 测试添加文档 索引文档
     */
    @Test
    public void testIndexDoc() throws IOException {
        IndexRequest indexRequest = new IndexRequest("students");
        // 设置文档id
        IndexRequest id = indexRequest.id("1");
        Student student = new Student("张三", 23, "三三三三三");
        // java转json
        String studentJsonString = JSONObject.toJSONString(student);
        // 添加文档数据
        IndexRequest source = indexRequest.source(studentJsonString, XContentType.JSON);
        // 调用客户端 添加文档
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        DocWriteResponse.Result result = indexResponse.getResult();
        System.out.println("result = " + result);
    }

    /**
     * 查询文档
     */
    @Test
    public void testGetDoc() throws IOException {
        GetRequest getRequest = new GetRequest("students", "1");
        // 调用客户端方法
        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        // 获取结果
        String sourceAsString = documentFields.getSourceAsString();
        System.out.println("sourceAsString = " + sourceAsString);
    }

    /**
     * 更新文档
     */
    @Test
    public void testUpdateDoc() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("students", "1");
        Student student = new Student();
        student.setName("张小三");
        UpdateRequest doc = updateRequest.doc(JSONObject.toJSONString(student), XContentType.JSON);
        UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("update = " + update);
    }

    /**
     * 批量添加
     */
    @Test
    public void testBulkDoc() {
        BulkRequest bulkRequest = new BulkRequest();
        Student student = new Student();
        for (int i = 0; i < 10; i++) {
            student.setAge(18 + i);
            student.setName("robin" + i);
            student.setRemark("good man " + i);
            bulkRequest.add(new IndexRequest("students").id(String.valueOf(10 + i)).source(JSONObject.toJSONString(student), XContentType.JSON));
        }
        try {
            BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            for (BulkItemResponse itemResponse : response.getItems()) {
                System.out.println(itemResponse.isFailed());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文档
     */
    @Test
    public void deleteDocument() {
        DeleteRequest request = new DeleteRequest("students", "11");
        try {
            DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
            System.out.println(response.getResult());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}












评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值