Elasticsearch:索引表以及文档的增删改查

初始化JavaRestClient

1、引入依赖



    org.elasticsearch.client
    elasticsearch-rest-high-level-client

2、初始化RestHighLevelClient

package cn.itcast.hotel;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.http.HttpHost;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@MapperScan("cn.itcast.hotel.mapper")
@SpringBootApplication
public class HotelDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(HotelDemoApplication.class, args);
    }

    @Bean
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.201.128:9200")
        ));
    }
}

 3、在kibana中准备好mappings映射

Elasticsearch:索引表以及文档的增删改查_第1张图片

索引库和文档增删改查

1、将准备好的mappings映射封装为静态常量字符串

package cn.itcast.hotel.constants;

public class HotelIndexConstants {
    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" +
            "      },\n" +
            "      \"starName\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"pic\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"location\": {\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"all\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}

2、索引库增删改查demo

package cn.itcast.hotel;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
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 java.io.IOException;
import static cn.itcast.hotel.constants.HotelIndexConstants.MAPPING_TEMPLATE;

public class HotelIndexTest {

    //引入RestHighLevelClient对象
    private RestHighLevelClient client;


    @Test //创建索引库
    void testCreateHotelIndex() throws IOException {
        //1、创建requst对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //2、请求参数、MAPPING_TEMPLATE是静态常量字符串,内容是创建索引库的DSL语句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //3、发起请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test //删除索引库
    void testDelHotelIndex() throws IOException {
        //1、创建requst对象
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        //2、发起请求
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

    @Test //判断索引库是否存在
    void testExistsHotelIndex() throws IOException {
        //1、创建requst对象
        GetIndexRequest request = new GetIndexRequest("hotel");
        //2、发起请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        //3、打印结果
        System.out.println(exists);
    }

    @BeforeEach //client对象初始化
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
            HttpHost.create("http://192.168.201.128:9200")
        ));
    }

    @AfterEach //client对象销毁
    void outUp() throws IOException {
        this.client.close();
    }
}

3、文档增删改查demo

package cn.itcast.hotel;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
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.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
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.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.List;

@SpringBootTest
public class HotelDocumentTest {

    @Autowired
    private IHotelService iHotelService;

    //引入RestHighLevelClient对象
    private RestHighLevelClient client;


    //==========================================================

    //新增文档
    @Test
    void testDocumentAdd() throws IOException {
        //根据id获取一个酒店数据
        Hotel hotel = iHotelService.getById(36934L);
        //通过HotelDoc实体类将数据库数据转换成索引库数据
        HotelDoc hotelDoc = new HotelDoc(hotel);

        //1、准备requst对象
        IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
        //2、准备json文档
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        //3、发送请求
        client.index(request, RequestOptions.DEFAULT);
    }


    //根据id查询文档
    @Test
    void testGetDocument() throws IOException {
        //1、创建requst对象
        GetRequest request = new GetRequest("hotel","36934");
        //2、发送请求,得到结果
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3、解析结果
        String json = response.getSourceAsString();

        System.out.println(json);
    }

    //根据id更新文档
    @Test
    void testUpdataDocument() throws IOException {
        //1、创建requst对象
        UpdateRequest request = new UpdateRequest("hotel","36934");
        //2、准备参数,每两个参数为一对 key value
        request.doc(
                "age",10,
                "name","tom"
        );
        //3、更新文档
        client.update(request,RequestOptions.DEFAULT);
    }

    //根据id删除文档
    @Test
    void testDelDocument() throws IOException {
        //1、创建requst对象
        DeleteRequest request = new DeleteRequest("hotel","36934");
        //2、发送请求
        client.delete(request,RequestOptions.DEFAULT);
    }

    //批量新增文档
    @Test
    void testBulkRequest() throws IOException {
        //获取所有酒店数据
        List hotels = iHotelService.list();

        //1、创建request
        BulkRequest request = new BulkRequest();
        //2、准备参数,添加多个request
        //转换为文档类型
        for (Hotel hotel : hotels) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            request.add(new IndexRequest("hotel")
                    .id(hotelDoc.getId().toString())
                    .source(JSON.toJSONString(hotelDoc), XContentType.JSON));
        }

        //3、发送请求
        client.bulk(request,RequestOptions.DEFAULT);
    }

    //==========================================================


    //client对象初始化
    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.201.128:9200")
        ));
    }

    //client对象销毁
    @AfterEach
    void outUp() throws IOException {
        this.client.close();
    }
}

你可能感兴趣的:(elasticsearch,大数据,搜索引擎)