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

我这边只需要单索引操作,有需求的可以让前端传过来

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

你可能感兴趣的:(elasticsearch,java)