ElasticsearchTemplate實現ES讀寫操作

1 實現的讀寫操作

1.1 一般操作

package com.lenovo.qes.portal.modules.knowledge.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.lenovo.qes.portal.modules.knowledge.demo.document.ProductDocument;
import com.lenovo.qes.portal.modules.knowledge.demo.repository.ProductDocumentRepository;
import com.lenovo.qes.portal.modules.knowledge.demo.service.EsSearchService;
import com.lenovo.qes.portal.modules.knowledge.service.impl.BaseSearchServiceImpl;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * elasticsearch 搜索引擎 service實現
 * @author zhoudong
 * @version 0.1
 * @date 2018/12/13 15:33
 */
@Service
public class EsSearchServiceImpl extends BaseSearchServiceImpl<ProductDocument> implements EsSearchService {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;
    @Resource
    private ProductDocumentRepository productDocumentRepository;

    @Override
    public void save(ProductDocument ... productDocuments) {

		/**
		* 設置映射關係
		*/
        elasticsearchTemplate.putMapping(ProductDocument.class);
        if(productDocuments.length > 0){
            log.info("【保存索引】:{}",JSON.toJSONString(productDocumentRepository.saveAll(Arrays.asList(productDocuments))));
        }
    }

    /**
     * 按關鍵字搜索
     * @param keyword 關鍵字
     * @param clazz es文檔映射的Java類型
     * @return 查詢條件列表
     */
    @Override
    public List<T> query(String keyword, Class<T> clazz) {

		// 封裝查詢條件對象
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(new QueryStringQueryBuilder(keyword))
                .withSort(SortBuilders.scoreSort().order(SortOrder.DESC))
                .withSort(new FieldSortBuilder("createTime").order(SortOrder.DESC))
                .build();

        return elasticsearchTemplate.queryForList(searchQuery,clazz);
    }

    /**
     * 搜索,命中關鍵字高亮,不分頁
     * 
     * http://localhost:8080/query_hit?keyword=無印良品榮耀&indexName=orders&fields=productName,productDesc
     * @param keyword   關鍵字
     * @param indexName 索引庫名稱
     * @param fieldNames 搜索字段名稱數組
     * @return 返回關鍵字對應的所有高亮的map數據
     */
    @Override
    public  List<Map<String,Object>> queryHit(String keyword,String indexName,String ... fieldNames) {
    
        // 構造查詢條件,使用標準分詞器.
        QueryBuilder matchQuery = createQueryBuilder(keyword,fieldNames);

        // 設置高亮,使用默認的highlighter高亮器
        HighlightBuilder highlightBuilder = createHighlightBuilder(fieldNames);

        // 設置查詢字段
        SearchResponse response = elasticsearchTemplate
		        .getClient()
		        .prepareSearch(indexName)// 設置索引
                .setQuery(matchQuery)
                .highlighter(highlightBuilder)
                .setSize(10000) // 設置一次返回的文檔數量,最大值:10000
                .get();

        // 返回搜索結果
        SearchHits hits = response.getHits();

        return getHitList(hits);
    }


    /**
     * 搜索高亮顯示,然後分頁返回
     * 
     * @param pageNo        當前頁
     * @param pageSize      每頁顯示的總條數
     * @param keyword       關鍵字
     * @param indexName     索引庫名稱
     * @param fieldNames    搜索的字段數組
     * @return 返回關鍵字對應的所有高亮的map數據
     * @sample http://localhost:8080/query_hit_page?keyword=無印良品榮耀&indexName=orders&fields=productName,productDesc&pageNo=1&pageSize=1
     */
    @Override
    public Page<Map<String, Object>> queryHitByPage(int pageNo,int pageSize, String keyword, String indexName, String... fieldNames) {
        // 構造查詢條件,使用標準分詞器.
        QueryBuilder matchQuery = createQueryBuilder(keyword,fieldNames);

        // 設置高亮,使用默認的highlighter高亮器
        HighlightBuilder highlightBuilder = createHighlightBuilder(fieldNames);

        // 設置查詢字段
        SearchResponse response = elasticsearchTemplate
		        .getClient()
		        .prepareSearch(indexName)
                .setQuery(matchQuery)
                .highlighter(highlightBuilder)
                .setFrom((pageNo-1) * pageSize)
                .setSize(pageNo * pageSize) // 設置一次返回的文檔數量,最大值:10000
                .get();


        // 返回搜索結果
        SearchHits hits = response.getHits();

        Long totalCount = hits.getTotalHits();
        Page<Map<String, Object>> page = new Page<>(pageNo,pageSize,totalCount.intValue());
        page.setList(getHitList(hits));
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteIndex(String indexName) {

		/**
		* 刪除索引庫
		*/
        elasticsearchTemplate.deleteIndex(indexName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(QesDocumentVo... qesDocumentVos) {

		// 初次保存的時候,設置映射類型。
        elasticsearchTemplate.putMapping(QesDocumentVo.class);
        if (qesDocumentVos.length > 0) {
            log.info("【保存索引】:{}", JSON.toJSONString(qesDocumentRepository.saveAll(Arrays.asList(qesDocumentVos))));
        }
    }

	/**
	* 根據文檔id,所有文檔刪除
	* @param idList 文檔ids
	*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<String> idList) {
        
        if (CollectionUtils.isEmpty(idList)) {
            return;
        }
        
        // 構建es客戶端
        String index = "qes";
        String type = "_doc";
        Client client = elasticsearchTemplate.getClient();
        
        // 構建批量刪除請求對象
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        for (String docId : idList) {
            DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete(index, type, docId);
            bulkRequestBuilder.add(deleteRequestBuilder);
        }
        
        // 執行批量刪除
        BulkResponse bulkResponse = bulkRequestBuilder.execute().actionGet();
        if (bulkResponse.hasFailures()) {
            log.error(bulkResponse.buildFailureMessage());
        }
    }




/*********************************私有方法************************************/
    /**
     * 處理高亮結果
     * @auther: zhoudong
     * @date: 2018/12/18 10:48
     */
    private List<Map<String,Object>> getHitList(SearchHits hits){
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map;
        for(SearchHit searchHit : hits){
            map = new HashMap<>(16);
            // 處理源數據
            map.put("source",searchHit.getSourceAsMap());
            // 處理高亮數據
            Map<String,Object> hitMap = new HashMap<>();
            searchHit.getHighlightFields().forEach((k,v) -> {
                StringBuilder hight = new StringBuilder();
                for(Text text : v.getFragments()) {
                    hight.append(text.string());
                }
                hitMap.put(v.getName(), hight.toString());
            });
            map.put("highlight",hitMap);
            list.add(map);
        }
        return list;
    }
}




1.2 其他操作

	/**
	* 根據ids,查詢指定數量的文檔
	*/
    @Override
    public List<QesDocumentVo> getDocumentByIdList(List<String> docIdList) {
        
        // 校驗參數,並初始化數據
        List<QesDocumentVo> qesDocumentVoList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(docIdList)) {
            return qesDocumentVoList;
        }

		// 查詢
        SearchResponse response = initBaseRequestBuilder()
                .setQuery(QueryBuilders.termsQuery("_id", docIdList))
                .setFrom(0)
                .setSize(1000)
                .get();
        
        // 解析結果
        SearchHits hits = response.getHits();
        
        // 返回數據
        if(hits.getTotalHits() <= 0) {
            return qesDocumentVoList;
        }
        
        return getHitList(hits);
    }

/**************************私有方法****************************/

    /**
     * 構建es查詢請求對象
     * @auther: zhoudong
     * @date: 2018/12/18 10:48
     */
    private SearchRequestBuilder initBaseRequestBuilder(){
        String indexName = "qes";
        String[] includeFields = {"content", "meta.author", "meta.modifier", "file", "path"};
        return elasticsearchTemplate.getClient().prepareSearch(indexName)
                .setFetchSource(includeFields, null);
    }
    
    /**
     * 處理高亮結果
     * @auther: zhoudong
     * @date: 2018/12/18 10:48
     */
    private List<QesDocumentVo> getHitList(SearchHits hits){
        
        List<QesDocumentVo> list = Lists.newArrayList();
        if (hits == null || hits.getTotalHits() == 0) {
            return list;
        }
        
        for(SearchHit searchHit : hits){

			// convertEsDocument2QesDocumentVo string 轉json裝model,不贅述;
            list.add(convertEsDocument2QesDocumentVo(searchHit));
        }
        return list;
    }

2 使用的實體類

2.1 文檔映射對象

package com.lenovo.qes.portal.modules.knowledge.Vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.elasticsearch.annotations.Document;

import java.io.Serializable;

/**
 * 產品實體
 * @author chenjun20
 * @version 0.1
 * @date 2020-03-25
 */
@Data
@Accessors(chain = true)
@ApiModel(value = "QesDocumentVo")
@Document(indexName = "qes", type = "_doc")
public class QesDocumentVo implements Serializable {
    @ApiModelProperty(value = "id")
    private String id;
    @ApiModelProperty(value = "文檔id")
    private String docId;
    @ApiModelProperty(value = "文檔內容")
    private String content;
    private KnowledgeDocPropertyVo knowledgeDocPropertyVo;
    private DocumentFileVo file;
    private DocumentMetaVo meta;
}

2.2 分頁對象

/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lenovo.qes.platform.common.vo;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * @author geekidea
 * @date 2018-11-08
 */
@Data
@ApiModel("分頁")
public class Paging<T> implements Serializable {
    private static final long serialVersionUID = -1683800405530086022L;

    @ApiModelProperty("總行數")
    @JSONField(name = "total")
    @JsonProperty("total")
    private long total = 0;

    @ApiModelProperty("數據列表")
    @JSONField(name = "records")
    @JsonProperty("records")
    private List<T> records = Collections.emptyList();

    public Paging() {
    }

    public Paging(IPage page) {
        this.total = page.getTotal();
        this.records = page.getRecords();
    }
    
    @Override
    public String toString() {
        return "Paging{" +
                "total=" + total +
                ", records=" + records +
                '}';
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章