国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

java 整合ES實現(xiàn)文檔增刪改查(多條件分頁查詢)

這篇具有很好參考價值的文章主要介紹了java 整合ES實現(xiàn)文檔增刪改查(多條件分頁查詢)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

本文采用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);
        //設(shè)置超時時間
        request.id(id);
        //將數(shù)據(jù)放到j(luò)son字符串
        request.source(JSON.toJSONString(dynamic), XContentType.JSON);
        //發(fā)送請求
        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,構(gòu)建SearchRequest請求對象,指定索引庫
        SearchRequest searchRequest = new SearchRequest(index);
        //2,構(gòu)建SearchSourceBuilder查詢對象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //3,構(gòu)建QueryBuilder對象指定查詢方式和查詢條件

        //4,將QuseryBuilder對象設(shè)置到SearchSourceBuilder對象中

        BoolQueryBuilder  builder = new BoolQueryBuilder();

        //設(shè)置編號
        if (StringUtils.isNotBlank(bizInformationPageParam.getInformationTabulationCode())) {
            builder = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("informationTabulationCode", bizInformationPageParam.getInformationTabulationCode()));
        }
        //設(shè)置副標題
        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設(shè)置到SearchRequest中
        searchRequest.source(sourceBuilder);

        try {
            //6,調(diào)用方法查詢數(shù)據(jù)
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            //7,解析返回結(jié)果
            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;
    }

我這邊只需要單索引操作,有需求的可以讓前端傳過來文章來源地址http://www.zghlxwxcb.cn/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();
        //設(shè)置編號
        if(StringUtils.isNotBlank(tabulationCode)) {
            queryBuilder = QueryBuilders.matchQuery("informationTabulationCode", tabulationCode);
        }

        //設(shè)置副標題
        if(StringUtils.isNotBlank(subtitle)) {
            queryBuilder2 = QueryBuilders.matchQuery("subtitle", subtitle);
        }


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

到了這里,關(guān)于java 整合ES實現(xiàn)文檔增刪改查(多條件分頁查詢)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包