Elasticsearch数据库的基本使用及ES健康状态red问题处理_es数据库的使用(1)

img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化资料的朋友,可以戳这里获取

        mappingBuilder.startObject("properties");
        {
            mappingBuilder.startObject("id");
            {
                mappingBuilder.field("type", "text");
                mappingBuilder.field("analyzer", "standard");
            }
            mappingBuilder.endObject();
            mappingBuilder.startObject("name");
            {
                mappingBuilder.field("type", "text");
                mappingBuilder.field("analyzer", "standard");
            }
            mappingBuilder.endObject();
            mappingBuilder.startObject("time");
            {
                mappingBuilder.field("type", "text");
                mappingBuilder.field("analyzer", "standard");
            }
            mappingBuilder.endObject();
            mappingBuilder.startObject("content");
            {
                mappingBuilder.field("type", "text");
                mappingBuilder.field("analyzer", "standard");
            }
            mappingBuilder.endObject();
        }
        mappingBuilder.endObject();
    }

    boolean exists = restHighLevelClient.indices().exists(requests, RequestOptions.DEFAULT);
    if (!exists) {
        CreateIndexRequest request = new CreateIndexRequest(esCreateVo.getIndex());
        request.mapping(mappingBuilder);
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        //判断是否创建成功
        boolean acknowledged = response.isAcknowledged();
        return acknowledged ? new CommonResult().success() : new CommonResult().failed("创建分类失败!");
    }
    return new CommonResult().failed("分类已存在!");
}

mappingBuilder.startObject() 是在创建索引的时候把索引中字段映射关系提前新建,不这样做的话,如果你查询的时候用了一些特定的条件的话,会报错(当新建索引,而且索引中没有添加过数据的时候)


删除索引



public CommonResult DeleteIndex(@RequestBody EsCreateVo esCreateVo) throws IOException {
//判断索引是否存在
GetIndexRequest requests = new GetIndexRequest(esCreateVo.getIndex());
boolean exists = restHighLevelClient.indices().exists(requests, RequestOptions.DEFAULT);
if (exists) {
DeleteIndexRequest request = new DeleteIndexRequest(esCreateVo.getIndex());
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
return delete.isAcknowledged() ? new CommonResult().success() : new CommonResult().failed(“创建分类失败!”);
}
return new CommonResult().failed(“分类已删除或不存在!”);
}


判断索引是否存在



public Boolean IndexIsExists(@RequestBody EsCreateVo esCreateVo) throws IOException {
    GetIndexRequest request = new GetIndexRequest(esCreateVo.getIndex());
    boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
    return exists ? true : false;
}

查询所有索引



public CommonResult selectIndexAll() throws IOException {
GetAliasesRequest request = new GetAliasesRequest();
GetAliasesResponse alias = restHighLevelClient.indices().getAlias(request, RequestOptions.DEFAULT);
Map<String, Set> aliases = alias.getAliases();

    Set<String> indices = aliases.keySet();
    List<EsCreateVo> esCreateVoList = new ArrayList<>();
    for (String s : indices) {
        EsCreateVo esCreateVo = new EsCreateVo();
        esCreateVo.setIndex(s);
        esCreateVoList.add(esCreateVo);
    }
    return new CommonResult().success(esCreateVoList);
}

创建文档



public CommonResult AddDocument(EsReqVO esReqVO) throws Exception {
System.out.println(“》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》执行创建所有文档”+ DateTime.now());
//上传文件,获取文件基本信息
MultipartFile file = esReqVO.getFile();

    String content = wordService.importDatas(file);

// DecimalFormat decimalFormat = new DecimalFormat(“#0.000”);

// 判断文件大小来转换并拼接 M单位
long size = file.getSize();
Double fileSizes =file.getSize()/1024/1024.;
BigDecimal bigDecimal = BigDecimal.valueOf(fileSizes).setScale(2, BigDecimal.ROUND_HALF_UP);

    // 创建一个DocumentVO对象
    DocumentVO documentVO = new DocumentVO(file.getOriginalFilename(), String.valueOf(bigDecimal) + " M", DateTime.now().toString(), content);
    // 创建请求
    IndexRequest request = new IndexRequest(esReqVO.getIndex());
    // 制定规则 PUT /liuyou_index/_doc/1
    // request.id("13");// 设置文档ID,不设置自动生成
    request.timeout(TimeValue.timeValueMillis(1000));// request.timeout("1s")
    // 将我们的数据放入请求中
    request.source(JSON.toJSONString(documentVO), XContentType.JSON);
    // 客户端发送请求,获取响应的结果
    try {
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println("======" + response.status());// 获取建立索引的状态信息 CREATED
        System.out.println("[[[[[[[[[" + response);// 查看返回内容
    } catch (Exception e) {
        String msg = e.getMessage();
        if (!msg.contains("201 Created") && !msg.contains("200 OK")) {
            throw e;
        }
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return new CommonResult().success();
}

创建文档的时候 需要在return之前让线程休眠至少一秒,删除也一样,因为ES有一个机制是你创建或删除文档的时候,他不会立即刷新,而是把数据放到一个类似于暂存区的地方1秒,如果不执行现成休眠的话,前端操作完创建/删除的时候,调用查询接口会查询不到你刚新增的数据,或是删除的数据还在存在列表,这是个坑,一定要注意!!!



修改文档



public CommonResult UpdateDocument(@RequestBody DocumentsVO documentsVO) throws IOException {
UpdateRequest request = new UpdateRequest(documentsVO.getIndex(), documentsVO.getId());
DocumentVO documentVO = new DocumentVO();
BeanUtil.copyProperties(documentsVO, documentVO);
request.doc(JSON.toJSONString(documentVO), XContentType.JSON);
try {
UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
System.out.println(response.status()); // OK
restHighLevelClient.close();
} catch (Exception e) {
String msg = e.getMessage();
if (!msg.contains(“201 Created”) && !msg.contains(“200 OK”)) {
throw e;
}
}

    return new CommonResult().success();
}

查询某条文档信息的获取



public CommonResult GetDocument(String index, String id) throws IOException {
GetRequest request = new GetRequest(index, id);
GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());// 打印文档内容
System.out.println(request);// 返回的全部内容和命令是一样的

    return new CommonResult().success(response.getSourceAsString());
}

文档的获取,并判断其是否存在



public CommonResult DocumentIsExists(String index, String id) throws IOException {
GetRequest request = new GetRequest(index, id);
// 不获取返回的 _source的上下文了
request.fetchSourceContext(new FetchSourceContext(false));
request.storedFields(“none”);
boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
System.out.println(exists);

    return exists ? new CommonResult().success(exists) : new CommonResult().failed("文档不存在!");
}

删除文档



public CommonResult DeleteDocument(@RequestParam String index, @RequestParam String id) throws IOException {
System.out.println(“》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》执行删除文档”+ DateTime.now());
DeleteRequest request = new DeleteRequest(index, id);
request.timeout(“1s”);
try {
restHighLevelClient.delete(request, RequestOptions.DEFAULT);

    } catch (Exception e) {
        String msg = e.getMessage();
        if (!msg.contains("201 Created") && !msg.contains("200 OK")) {
            throw e;
        }
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return new CommonResult().success();
}

根据索引查询所有文档



public CommonResult SearchsDocument(@RequestParam(value = “fileName”, required = false) String fileName,
@RequestParam(value = “index”, required = false) String index,
@RequestParam(“pageNo”) int pageNo,
@RequestParam(“pageSize”) int pageSize) throws IOException {
System.out.println(“》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》执行查询所有文档”+ DateTime.now());
System.out.println(“》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》索引名称”+ index);
// 创建查询请求对象
SearchRequest searchRequest = new SearchRequest(index);
// 构建搜索条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = null;
if (StrUtil.isNotBlank(fileName)){
boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.matchQuery(“name”,fileName));
}

    //设置高亮
    searchSourceBuilder.highlighter(new HighlightBuilder());
    //设置分页
    searchSourceBuilder.from(pageNo);
    searchSourceBuilder.size(pageSize);

// 设置排序条件
searchSourceBuilder.sort(“time.keyword”, SortOrder.DESC);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchSourceBuilder.query(boolQueryBuilder);

    searchRequest.source(searchSourceBuilder);
    SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    SearchHits hits = search.getHits();
    //获取总条数
    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(hits));

// 设置总条数
jsonObject.put(“total”, hits.getTotalHits().value);
if (hits.getHits().length != 0 && StrUtil.isNotBlank(hits.getHits()[0].getIndex())){
// 给每条数据都设置索引
jsonObject.getJSONArray(“hits”).getJSONObject(0).getJSONObject(“sourceAsMap”).put(“index”, hits.getHits()[0].getIndex());
}

    return new CommonResult().success(jsonObject);

}

搭建的ES库不仅可以用来存储用户使用的数据,我们项目中还配置了,jar包每次启动后都会把日志文件给存储到ES库中这就间接的导致了几个问题:


   1.日志索引查询报错


解决方案:


![img](https://img-blog.csdnimg.cn/img_convert/a9a3314c4d3d434d42f5deeaa3355e13.png)
![img](https://img-blog.csdnimg.cn/img_convert/e6c8cf9f9f457cb8ef2ae4f909d1dc0f.png)
![img](https://img-blog.csdnimg.cn/img_convert/8365bd52352c2fae9ebdd6f3b0cd9cfa.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/forums/4f45ff00ff254613a03fab5e56a57acb)**

中...(img-sx6LMF4G-1715322962851)]
[外链图片转存中...(img-nehEgpdK-1715322962852)]

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/forums/4f45ff00ff254613a03fab5e56a57acb)**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值