java 整合ES实现文档增删改查(多条件分页查询)

这篇具有很好参考价值的文章主要介绍了java 整合ES实现文档增删改查(多条件分页查询)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文采用ES版本为8.7.1
由于只存储文章,仅用固定索引即可,索引用kibanna直接生成,省略索引部分的增删查步骤

引入pom文件

<!-- elasticsearch -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

项目启动连接ElasticSearch

@Configuration
public class ElasticSearchClientConfig {

    @Value("${elasticSearch.hostname}")
    private String hostname;

    @Value("${elasticSearch.port}")
    private Integer port;

    @Value("${elasticSearch.scheme}")
    private String scheme;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(hostname,port,scheme))
        );
    }
}

application配置文件

elasticSearch.hostname=127.0.0.1
elasticSearch.port=9200
elasticSearch.scheme=http

抓取返回信息是因为版本问题无法解析ES返回的正确信息,实际操作成功但是会报错

工具类

	//新增文档
    public IndexResponse add(Information information, String index, String id){
        IndexRequest request = new IndexRequest(index);
        //设置超时时间
        request.id(id);
        //将数据放到json字符串
        request.source(JSON.toJSONString(dynamic), XContentType.JSON);
        //发送请求
        IndexResponse response = null;
        try {
            response = client.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
        }
        return null;

    }
    
	//修改文档
    public UpdateResponse updateDocument(BizInformation dynamic, String index, String id){

        UpdateRequest request = new UpdateRequest(index, id);
        request.timeout("1s");
        request.doc(JSON.toJSONString(dynamic), XContentType.JSON);

        try {
            client.update(request, RequestOptions.DEFAULT);
        } catch (Exception e) {

        }

        return null;
    }


    //删除文档
    public RestStatus deleteDocument(String index, String documents){
        DeleteRequest request = new DeleteRequest(index, documents);
        request.timeout("1s");
        DeleteResponse response = null;
        try {
            client.delete(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
        }
        return null;
    }

    public DevInformationResult commonSearch(DevInformationPageParam bizInformationPageParam,String index) {


        DevInformationResult informationPageResult = new DevInformationResult();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //1,构建SearchRequest请求对象,指定索引库
        SearchRequest searchRequest = new SearchRequest(index);
        //2,构建SearchSourceBuilder查询对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //3,构建QueryBuilder对象指定查询方式和查询条件

        //4,将QuseryBuilder对象设置到SearchSourceBuilder对象中

        BoolQueryBuilder  builder = new BoolQueryBuilder();

        //设置编号
        if (StringUtils.isNotBlank(bizInformationPageParam.getInformationTabulationCode())) {
            builder = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("informationTabulationCode", bizInformationPageParam.getInformationTabulationCode()));
        }
        //设置副标题
        if (StringUtils.isNotBlank(bizInformationPageParam.getSearchKey())) {
            builder = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("informationTabulationCode", bizInformationPageParam.getInformationTabulationCode()))
            .must(QueryBuilders.boolQuery()
            .should(new WildcardQueryBuilder("author", "*" + bizInformationPageParam.getSearchKey() + "*"))
            .should(new WildcardQueryBuilder("content", "*" + bizInformationPageParam.getSearchKey() + "*"))
            .should(new WildcardQueryBuilder("content", "*" + bizInformationPageParam.getSearchKey() + "*"))
            .should(new WildcardQueryBuilder("informationTabulationName", "*" + bizInformationPageParam.getSearchKey() + "*"))
            .should(new WildcardQueryBuilder("subtitle", "*" + bizInformationPageParam.getSearchKey() + "*"))
            .should(new WildcardQueryBuilder("title", "*" + bizInformationPageParam.getSearchKey() + "*")));
        }

        boolQueryBuilder.must(builder);
        sourceBuilder.query(boolQueryBuilder);

        //字段过滤
        sourceBuilder.fetchSource(new String[]{"author", "content", "coverPicture", "id", "informationTabulationCode","informationTabulationName","sortCode" ,"subtitle", "time", "title"}, new String[]{"images"});
        //排序
        sourceBuilder.sort("time", SortOrder.DESC);
        //分页
        Integer offset = (bizInformationPageParam.getCurrent() - 1) * bizInformationPageParam.getSize();
        sourceBuilder.from(offset);
        sourceBuilder.size(bizInformationPageParam.getSize());

        informationPageResult.setCurrent(bizInformationPageParam.getCurrent());
        informationPageResult.setSize(bizInformationPageParam.getSize());

        //5,将SearchSourceBuilder设置到SearchRequest中
        searchRequest.source(sourceBuilder);

        try {
            //6,调用方法查询数据
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            //7,解析返回结果
            SearchHit[] hits = searchResponse.getHits().getHits();

            List<DevInformation> bizInformationList = new ArrayList<>();
            for (SearchHit hit : hits) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.putAll(hit.getSourceAsMap());
                DevInformation bizInformation = jsonObject.toJavaObject(DevInformation.class);
                bizInformationList.add(bizInformation);
            }

            informationPageResult.setRecords(bizInformationList);
            informationPageResult.setTotal(searchResponse.getHits().getTotalHits().value);
            return informationPageResult;

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

        return null;
    }

我这边只需要单索引操作,有需求的可以让前端传过来文章来源地址https://www.toymoban.com/news/detail-642147.html

Controller

 	@Autowired
    private ElasticSearchUtil elasticSearchUtil;

    @Value("${elasticSearch.index}")
    private String index;


    /**
     * 添加文档
     */
    @PostMapping("/addDocument")
    public CommonResult addDocument(@RequestBody BizInformation information) {
        information.setId(IdWorker.getId());
        information.setCreateTime(new Date());
//                information.setCreateUser(StpLoginUserUtil.getLoginUser().getName());
        return CommonResult.data(elasticSearchUtil.addDocumentId(information, index, information.getId().toString()));
    }

    /**
     * 修改文档
     */
    @PutMapping("/updateDocument")
    public CommonResult updateDocument(@RequestBody BizInformation information, @RequestParam String id) {
        return CommonResult.data(elasticSearchUtil.updateDocument(information, index, id));
    }

    /**
     * 删除文档
     */
    @DeleteMapping("/deleteDocument")
    public CommonResult deleteDocument(@RequestParam String id) {
        return CommonResult.data(elasticSearchUtil.deleteDocument(index, id));
    }
    
    /**
     * 分页查询
     */
    @GetMapping("/searchDocumentPageList")
    public CommonResult searchDocument(@RequestParam(required = false, defaultValue = "") String tabulationCode,
                                       @RequestParam(required = false, defaultValue = "") String subtitle,
                                       @RequestParam(required = false, defaultValue = "1") int pageNum,
                                       @RequestParam(required = false, defaultValue = "10") int pageSize) throws IOException {

        QueryBuilder queryBuilder = new BoolQueryBuilder();
        QueryBuilder queryBuilder2 = new BoolQueryBuilder();
        //设置编号
        if(StringUtils.isNotBlank(tabulationCode)) {
            queryBuilder = QueryBuilders.matchQuery("informationTabulationCode", tabulationCode);
        }

        //设置副标题
        if(StringUtils.isNotBlank(subtitle)) {
            queryBuilder2 = QueryBuilders.matchQuery("subtitle", subtitle);
        }


        return CommonResult.data(elasticSearchUtil.commonSearch(queryBuilder, queryBuilder2, index, pageNum, pageSize));
    }

到了这里,关于java 整合ES实现文档增删改查(多条件分页查询)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包