首页 > 其他分享 >RestCilent语句【ElasticSearch】

RestCilent语句【ElasticSearch】

时间:2023-06-22 18:11:23浏览次数:30  
标签:语句 hotel new RestCilent client ElasticSearch org import todo

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

}

 

标签:语句,hotel,new,RestCilent,client,ElasticSearch,org,import,todo
From: https://www.cnblogs.com/Rover20230226/p/17498082.html

相关文章

  • VB.NET开发Autocad,拿来就用的常用语句
    一,导入命名空间                             一、导入命名空间ImportsAcApps=Autodesk.AutoCAD.ApplicationServicesImportsAutodesk.AutoCAD.DatabaseServicesImportsAutodesk.AutoCAD.EditorInputImpor......
  • POSTGRESQL SQL 语句案例,一场由LIMIT 1 引发的“奇怪异像”
    开头还是介绍一下群,如果感兴趣polardb,mongodb,mysql,postgresql,redis等有问题,有需求都可以加群群内有各大数据库行业大咖,CTO,可以解决你的问题。最近一段工作很少优化SQL,实际上7-8年前的确有一段疯狂优化的“美好时光”。 最近一个同事提出一个问题,他的一个POSTGRESQL的SQ......
  • python在if判断语句中对于0和None的处理
    情景:我在访问一个字典的key,但是我不知道这个key有没有,或者有,我也不知道value取值多少,即dict1.get(key)有可能输出None,也有可能输出0如果我对这个key进行判断,例如:ifdict1.get(key)这种判断,可能对于None和0的条件都是一样的,因此,如果我只是想判断是否存在这个key,我需要ifdict1......
  • logstash1 - kafka - logstash2 - elasticsearch - kibana - 运维神器
    0.拓扑图官网: http://kafka.apache.org/documentation.html#introductionkafka原理 https://www.jianshu.com/p/e64d57d467ec?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation1.logstash的配置[root@VM_0_4_centosconfig]#ca......
  • PG-DBA培训05:PostgreSQL数据查询与SQL语句增删改 原创
    一、风哥PG-DBA培训05:PostgreSQL数据查询与SQL语句增删改本课程由风哥发布的基于PostgreSQL数据库的系列课程,本课程属于PostgreSQL数据库SQL开发与应用实战阶段之PostgreSQL数据查询与SQL语句增删改,学完本课程可以掌握PostgreSQLSQL增删改,插入数据(insert),修改数据(update),删除......
  • PG-DBA培训05:PostgreSQL数据查询与SQL语句增删改
    一、风哥PG-DBA培训05:PostgreSQL数据查询与SQL语句增删改本课程由风哥发布的基于PostgreSQL数据库的系列课程,本课程属于PostgreSQL数据库SQL开发与应用实战阶段之PostgreSQL数据查询与SQL语句增删改,学完本课程可以掌握PostgreSQLSQL增删改,插入数据(insert),修改数据(update),删除数......
  • elasticsearch 语句
    #测试分词器GET/_analyze{"analyzer":"ik_max_word","text":"泰裤辣,萌萌哒"}#创建索引库和映射PUT/student{"mappings":{"properties":{"name":{"type":"te......
  • MYSQL 执行update语句时报错: The total number of locks exceeds the lock table size
    由于数据量较大导致报错:‘’Thetotalnumberoflocksexceedsthelocktablesize‘’。这句话翻译过来大概是这个意思:总数已经超过锁定表的大小。解决办法:输入查询:showvariableslike"%_buffer%";找到innodb_buffer_pool_size对应的值默认为8388608也就是8兆。我们将其设置......
  • 探索C语言的控制流:循环和条件语句
    在C语言中,控制流是编程中的核心概念之一。它允许我们根据特定的条件或循环来决定程序的执行路径。掌握C语言的控制流对于编写高效和灵活的程序非常重要。本文将深入探索C语言中的控制流,重点介绍循环和条件语句,并提供相应的代码示例。条件语句在C语言中,最常用的条件语句是if-else语......
  • SQL语句_字符串的处理
    user_name表:firstnamemiddlenamelastnameJohnWilsonSmithAdamEdwardDavisMarieElaineWhite 我们在日常的工作中,使用SQL语句查询出数据后,需要对一些数据的字段做一些合并、取其一段或是去掉空格的处理。这里我们就会用到SQL语句中的CONCAT(链接)、S......