栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

2.4(ElasticSearch)Boot整合操作

2.4(ElasticSearch)Boot整合操作

Boot整合ElasticSearch

关于Boot整合存在很多的方式。一般步骤都是

  1. 导入依赖
  2. 写配置
  3. IOC调用
不使用starter的maven依赖

这种方式无论是Boot或Sping都可以使用。

查看目录结构

引入依赖
 
        
    7.4.0
    


        
        
            org.springframework.boot
            spring-boot-starter-web
        


        
        
            org.springframework.boot
            spring-boot-starter-test
        

        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            ${elasticsearch.version}
        
        
            org.elasticsearch
            elasticsearch
            ${elasticsearch.version}
        
        
            org.elasticsearch.client
            elasticsearch-rest-client
            ${elasticsearch.version}
        
    
配置类

因为依赖种存在我们需要使用的类。

为了使用Spring的IOC功能方便编写代码,我们通过配置类进行将类引入Spring容器中

@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient esRestClient() {
        return new RestHighLevelClient(
                RestClient.builder(
//                        指定ip 端口 协议
                        new HttpHost("192.168.159.140", 9200, "http")));
    }
}
Boot的测试类

我们在实际开发中,想写个测试。不能说就写在生产代码中。

为了区分所以还是要多写测试。

//测试中指定Boot的启动类。用于加载
@SpringBootTest(classes = HelloBoot.class)
public class ElasticBootTest {

//    可以在测试中使用了Boot的注解
    @Resource
    private RestHighLevelClient restHighLevelClient;

//    正常进行测试 返回类型是void哦
    @Test
    public void addindex(){
//        通过该ElK客户端对象得到添加索引的对象
        IndicesClient indices = restHighLevelClient.indices();

//        创建一个索引
//                        注意索引添加 名称 必须为小写
        CreateIndexRequest createRequest = new CreateIndexRequest("bootelastictestindex");
        try {
//            使用添加索引对象  将创建的索引 通过指定的请求方式添加到索引种
            CreateIndexResponse createIndexResponse = indices.create(createRequest, RequestOptions.DEFAULT);

//            判断是否添加索引成功
            System.out.println(createIndexResponse.isAcknowledged());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

异常

ElasticsearchStatusException[Elasticsearch exception [type=invalid_index_name_exception, reason=Invalid index name [bootElasticindex], must be lowercase]]

该异常表示索引名必须为全小写

结果展示

没有问题

更多操作

看到上面ElasticSearch整合Boot之后就是API操作了。

添加映射

在添加索引的时候进行指定即可

//        添加映射
//        创建一个映射
        String mapping ="{n" +
                "      "properties" : {n" +
                "        "age" : {n" +
                "          "type" : "integer"n" +
                "        },n" +
                "        "name" : {n" +
                "          "type" : "text"n" +
                "        }n" +
                "      }n" +
                "    }";
//        使用索引进行添加
        createRequest.mapping("doc",mapping, XContentType.JSON);

获取索引
    @Test
    public void queryIndex() throws Exception {
        IndicesClient indices = restHighLevelClient.indices();
//        获取索引
        GetIndexRequest boot01 = new GetIndexRequest("boot01");


        System.out.println("--------查询索引-------");
        GetIndexResponse getIndexResponse = indices.get(boot01, RequestOptions.DEFAULT);
//        查询到指定的索引
        Map mappings = getIndexResponse.getMappings();
        Set strings = mappings.keySet();
        for (String string : strings) {
            System.out.println("获取到的索引内容"+mappings.get(string));
        }
        
    }
删除索引
   @Test
    public void deleteIndex()throws Exception{
        System.out.println("--------删除索引-------");
        IndicesClient indices = restHighLevelClient.indices();
        DeleteIndexRequest boot01 = new DeleteIndexRequest("boot01");
        AcknowledgedResponse delete = indices.delete(boot01, RequestOptions.DEFAULT);

        System.out.println("是否删除成功:"+delete.isAcknowledged());
    }
判断索引exists
 @Test
    public void existsIndex()throws  Exception{
        IndicesClient indices = restHighLevelClient.indices();

        GetIndexRequest boot01 = new GetIndexRequest("boot01");
        boolean exists = indices.exists(boot01, RequestOptions.DEFAULT);

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

    }

文档操作

因为文档操作是很频繁的,所以这里不在需要通过客户端获取对象

直接可以通过RestHighLevelClient对象操作即可

添加文档(Map)
 @Test
    public void addDoc() throws Exception {

//        添加的数据
        Map data = new HashMap<>();
        data.put("name","wsl");
        data.put("age","21");
        data.put("sex","男");

//        1.获取操作文档的对象
        IndexRequest request = new IndexRequest("boot01").id("1").source(data);
//        添加数据获取结果
        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);

//        打印响应的结果
        System.out.println(index.getId());
        
    }

结果展示

虽然没有指定mapper,但是会进行自动生成

添加文档(JSON)

上面添加文档的形式通过传入Map对象

我们可以不可以直接传入对象呢

我们可以将我们的对象,转成JSON在传入ElasticSearch中

引入FastJson依赖
        
            com.alibaba
            fastjson
            1.2.4
        
展示测试类
 @Resource
    private User user;

    @Test
    public void addDocJSONTest() throws Exception {

        user.setName("wsm");
        user.setAge(21);
        user.setSex("男");
//        通过Alibaba的fastjson获取对象的json 格式
        String data = JSON.toJSONString(user);

//        1.获取操作文档的对象
//        指定文档类型
        IndexRequest request = new IndexRequest("boot01").id("3").source(data, XContentType.JSON);
//        添加数据获取结果
        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);

//        打印响应的结果
        System.out.println(index.getId());

    }

结果

修改文档

如果指定的文档id存在则修改,否则则添加

不需要演示

查询文档
  @Test
    public void getDocById()throws Exception{

//        指定索引名称和文档id进行标识
        GetRequest boot01 = new GetRequest("boot01", "1");
//        获取文档信息
        GetResponse documentFields = restHighLevelClient.get(boot01, RequestOptions.DEFAULT);

        System.out.println("打印文档信息:"+documentFields.getSourceAsString());
    }

删除文档
@Test
    public void deleteDocById()throws Exception{
//        指定索引名称和文档id进行标识
        DeleteRequest boot01 = new DeleteRequest("boot01", "1");
//        获取文档信息
        DeleteResponse delete = restHighLevelClient.delete(boot01, RequestOptions.DEFAULT);
        System.out.println(delete.getId());
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/688057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号