RestCilent语句【ElasticSearch】

复制代码
package cn.itcast.hotel;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
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.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@SpringBootTest
class HotelDemoApplicationTests {

    private RestHighLevelClient client;

    public static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"score\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"city\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"starName\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"location\":{\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";

    @BeforeEach
    public void before() {
        //client对象就是操作ES的对象
        client =
                new RestHighLevelClient(RestClient.builder
                        (HttpHost.create("http://192.168.221.135:9200")));
    }

    @AfterEach
    public void after() throws IOException {
        client.close();
    }

    @Resource
    private HotelMapper hotelMapper;


    /**
     * 删除索引库
     *
     * @throws IOException
     */
    @Test
    void contextLoads() throws IOException {
        RestHighLevelClient client =
                new RestHighLevelClient(RestClient.builder
                        (HttpHost.create("http://192.168.221.135:9200")));
        //todo 1.等于告诉ES需要发送的是 Delete请求
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("hotel");
        //todo 2.调用删除请求
        AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 创建索引库
     */
    @Test
    public void createIndex() throws IOException {
        //todo 获取连接对象
        //索引库的名字
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("hotel");
        //todo 携带参数(映射)
        createIndexRequest.source(MAPPING_TEMPLATE, XContentType.JSON);
        //todo 找到创建索引的方法
        client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        //todo 关闭连接
    }

    /**
     * 查询索引  get /hotel
     */
    @Test
    public void getIndex() throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest("hotel");

        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

        System.out.println("hotel是否存在:" + exists);
    }

    /**
     * 新增数据到ES
     */
    @Test
    public void add() throws IOException {
        //todo 1.为了方便从数据库里面查询一个酒店
        Hotel hotel = hotelMapper.selectById(38609);
        //todo 把数据库的酒店对象转换成ES的HotelDOC对象
        HotelDoc hotelDoc = new HotelDoc(hotel);
        String jsonString = JSON.toJSONString(hotelDoc);
        //todo 注意: 如果不给数据设置ID,那么ES会自动的生成一个UUID的数据
        IndexRequest indexRequest = new IndexRequest("hotel").id(hotelDoc.getId().toString());
        //todo 2.添加的文档数据
        indexRequest.source(jsonString, XContentType.JSON);
        //todo 发送添加请求
        client.index(indexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 删除数据
     * Delete  /hotel/_doc/61Vq4ogB_DjiEoLwaSbe
     */
    @Test
    public void remove() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("hotel").id("61Vq4ogB_DjiEoLwaSbe");
        client.delete(deleteRequest, RequestOptions.DEFAULT);
    }

    /**
     * 查询数据
     * Delete  /hotel/_doc/38609
     */
    @Test
    public void find() throws IOException {
        GetRequest getRequest = new GetRequest("hotel").id("38609");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        String json = getResponse.getSourceAsString();
        //todo 把返回值的JSON转换成对象
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println(hotelDoc);
    }

    /**
     * 修改数据
     * <p>
     * 参考案例
     * PUT /student/_doc/1
     * {
     * "name":"关羽",
     * "info":"手持青龙偃月刀",
     * "age":40
     * }
     */
    @Test
    public void modify() throws IOException {
        //查询获得到数据
        GetRequest getRequest = new GetRequest("hotel").id("38609");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        String json = getResponse.getSourceAsString();
        //todo 把返回值的JSON转换成对象
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        hotelDoc.setName("自如享优品");
        //todo 修改数据
        UpdateRequest updateRequest = new UpdateRequest("hotel", "38609");
        updateRequest.doc(JSON.toJSONString(hotelDoc), XContentType.JSON);
        client.update(updateRequest, RequestOptions.DEFAULT);
    }

    /**
     * 数据批量导入
     */
    @Test
    public void adds() throws IOException {
        //todo 初始化所有的数据
        List<Hotel> hotelList = hotelMapper.selectList(null);

        //添加数据的桶
        BulkRequest bulkRequest = new BulkRequest();
        hotelList.stream().forEach(hotel -> {
            //todo 转换Hotel -> HotelDoc
            HotelDoc hotelDoc = new HotelDoc(hotel);
            IndexRequest indexRequest = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });

        //找方法 bulk() 批量导入的方法
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }

}
复制代码

 

posted @   青核桃啊  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示