springboot集成elasticsearch

  在基礎階段學習ES通常是首先是 安裝ES後藉助 Kibana 來進行CURD 瞭解ES的使用;mysql

  在進階階段能夠須要學習ES的底層原理,如何經過Version來實現樂觀鎖保證ES不出問題等核心原理;web

  第三個階段就是學以至用 ,在項目中如何作到 springboot集成elasticsearch來解決實際問題,下邊經過一個Demo的介紹過程來引導學習。spring

   一、首先pom.xml配置所需jar包,jar使用的版本須要和測試環境上的es保持配套;sql

<!-- elasticsearch 5.x 依賴 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons.lang3.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <!-- <scope>test</scope> -->
        </dependency>

 

   二、配置類:數據庫

@Configuration
public class ESConfiguration implements FactoryBean<TransportClient>, InitializingBean, DisposableBean {
    
    private static final Logger logger = LoggerFactory.getLogger(ESConfiguration.class);
    
    /**
     * es集羣地址
     */
    @Value("${elasticsearch.ip}")
    private String hostName;
    /**
     * 端口
     */
    @Value("${elasticsearch.port}")
    private String port;
    /**
     * 集羣名稱
     */
    @Value("${elasticsearch.cluster.name}")
    private String clusterName;
    
    /**
     * 鏈接池
     */
    @Value("${elasticsearch.pool}")
    private String poolSize;
    
    private TransportClient client;

    @Override
    public void destroy() throws Exception {
        try {
            logger.info("Closing elasticSearch client");
            if (client != null) {
                client.close();
            }
        } catch (final Exception e) {
            logger.error("Error closing ElasticSearch client: ", e);
        }
    }

    @Override
    public TransportClient getObject() throws Exception {
        return client;
    }

    @Override
    public Class<TransportClient> getObjectType() {
        return TransportClient.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            // 配置信息
            Settings esSetting = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", true)// 增長嗅探機制,找到ES集羣
                    .put("thread_pool.search.size", Integer.parseInt(poolSize))// 增長線程池個數,暫時設爲5
                    .build();

            client = new PreBuiltTransportClient(esSetting);
            InetSocketTransportAddress inetSocketTransportAddress = new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
            client.addTransportAddresses(inetSocketTransportAddress);

        } catch (Exception e) {
            logger.error("elasticsearch TransportClient create error!!!", e);
        }
    }

}

 

 三、涉及controller層apache

@RestController
@RequestMapping("/search")
public class SearchRestController extends BaseController{
    
    private static final Logger log = LoggerFactory.getLogger(SearchRestController.class);

    @Autowired
    private ESSearchService esSearchService;
    
    @Autowired
    private ESAggsSearchService eSAggsSearchService;
    
    @Autowired
    private ESSuggestSearchService esSuggestSearchService;

    /**
     * 關鍵字查詢
     * @param index
     * @return
     */
    @RequestMapping(value = "/test")
    public ResponseVo<?> test(
            @RequestParam(value = "index", required = false) String index,
            @RequestParam(value = "filed", required = false) String filed,
            @RequestParam(value = "keyWord", required = false) String keyWord
    ) throws Exception{
        //判空
        List<String> searchList = esSearchService.searchMessageByKeyWord(index, filed, keyWord, 10, 0);
        return generateResponseVo(ESWebStatusEnum.SUCCESS, searchList);
    }
    
    /**
     * 構建索引
     * @param index
     * @return
     */
    @RequestMapping(value = "/buildIndex")
    public ResponseVo<?> buildIndex(@RequestParam(value = "index", required = false) String index)
    {
        //判空
        if(index == null) {
            return generateResponseVo(ESWebStatusEnum.FAILED, null);
        }
        esSearchService.buildIndex(index);
        return generateResponseVo(ESWebStatusEnum.SUCCESS, null);
    }
    
    /*@RequestMapping(value = "/delIndex")
    public ResponseVo<?> delIndex(
            ) {
        
        for(int j=1; j<7; j++) {
            for(int i=1; i<=30; i++) {
                StringBuilder sb = new StringBuilder("forum2018-0");
                sb.append(j);
                sb.append("-");
                
                if(i < 10) {
                    sb.append("0" + i);
                }else {
                    sb.append(i);
                }
                try { 
                    esSearchService.delIndex(sb.toString());
                }catch(Exception e) {
                    System.out.println("繼續");
                }
            }
        }
        
        return generateResponseVo(ESWebStatusEnum.SUCCESS, null);
    }*/
    
    /**
     *  查詢數據
     *  
     * @param index
     * @param type
     * @param id
     * @return
     */
    //http://localhost:8088/search/data?index=suggest_term_index$type=tech&id=AWpNa9UkTc7xOmAB67Cu
    @RequestMapping(value = "/data")
    @ResponseBody
    public ResponseVo<?> search(
            @RequestParam(value = "index", required = false) String index,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "id", required = false) String id
            ) {
        //判空
        if(index == null || type == null || id == null) {
            return generateResponseVo(ESWebStatusEnum.FAILED, null);
        }
        //搜索具體的數據來源
        Map<String, Object> returnMap = esSearchService.searchDataByParam("suggest_term_index", "tech", "AWpNa9UkTc7xOmAB67Cu");
        return generateResponseVo(ESWebStatusEnum.SUCCESS, returnMap);
    }
    
    /**
     * 增長索引
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/build_suggest_index")
    @ResponseBody
    public ResponseVo<?> build_suggest_index(
            ) throws Exception {
        //搜索具體的數據來源
        
//        String index = "search_suggest_index";
        String term_index = "suggest_term_index";
        esSuggestSearchService.buildIndexByParam(term_index);
        
        return generateResponseVo(ESWebStatusEnum.SUCCESS, null);
        
    }
    
    /**
     * 加入數據
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addDataToIndex")
    @ResponseBody
    public ResponseVo<?> addDataToIndexForSuggest() throws Exception
    {
        String term_index = "suggest_term_index";
        
        //搜索具體的數據來源
        SuggestModel data = new SuggestModel();
        data.setContent("聯合信用股份有限公司");//北京聯合信用投資諮詢有限公司,聯合信用投資諮詢有限公司
        data.setId(1l);
        data.setData(12);
        
        esSuggestSearchService.addDataDocForSuggest( term_index, "tech", data);
        
        SuggestModel data1 = new SuggestModel();
        data1.setContent("北京聯合信用投資諮詢有限公司");//,聯合信用投資諮詢有限公司
        data1.setId(1l);
        data1.setData(12);
        
        esSuggestSearchService.addDataDocForSuggest( term_index, "tech", data1);
        
        SuggestModel data2 = new SuggestModel();
        data2.setContent("聯合信用投資諮詢有限公司");//
        data2.setId(1l);
        data2.setData(12);
        esSuggestSearchService.addDataDocForSuggest( term_index, "tech", data2);
        
        return generateResponseVo(ESWebStatusEnum.SUCCESS, null);
    }
    
    /**
     * JSON格式化插入數據
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addJSONDataDoc")
    @ResponseBody
    public ResponseVo<?> addJSONDataDoc() throws Exception
    {
        String index = "bbs_post_index";
        
        ModelMap map = new ModelMap();
        map.put("collectCount", 0);
        map.put("commentCount", 0);
        map.put("content", "壓力測試,<a data-name=\"themeName\" href=\"#searchList?search=債券市場&type=2\" data-value=\"債券市場\" contenteditable=\"false\" class=\"comment-a\">#債券市場#</a> ,<a data-name=\"bondName\" href=\"#bondInfo/b6028d34b4b16ed2bf3513dcca91daa0\" data-value=\"b6028d34b4b16ed2bf3513dcca91daa0\" contenteditable=\"false\" class=\"comment-a\">$12進出12(120312.IB)$</a> 是發的這隻債券嗎? okokok,<a data-name=\"entityName\" href=\"#entityInfo/2029149\" data-value=\"2029149\" contenteditable=\"false\" class=\"comment-a\">$浙江省手工業合做社聯合社$</a> 是否是和公司");
        map.put("createTime", "2018-09-03 13:49:51");
        map.put("downloadCount", 0);
        map.put("forwardCount", 0);
        map.put("id", 773);
        map.put("isAnonymity", 0);
        map.put("originalContent", "壓力測試,#債券市場# ,$12進出12(120312.IB)$ 是發的這隻債券嗎? okokok,$浙江省手工業合做社聯合社$ 是否是和公司");
        map.put("postVariety", 0);
        map.put("readCount", 0);
        map.put("type", 1);
        map.put("updateTime", "2018-09-03 13:49:51");
        map.put("userId", 241);
        map.put("valid", 1);
        
        String esId = esSearchService.addJSONDataDoc(index, "post", map);
        
        return generateResponseVo(ESWebStatusEnum.SUCCESS, esId);
    }
    
    /**
     * 封裝參數進行查詢
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSearchByParam")
    @ResponseBody
    public ResponseVo<?> getSearchByParam(
            ) throws Exception {
        //搜索具體的數據來源
        
        BasicSearchParam param = new BasicSearchParam();
        param.setIndex("bbs_post_index");
        param.setField("content");
        param.setDistictField("id");
        param.setKeyWord("壓力測試");
        param.setLimit(10);
        param.setOffset(0);
        
        /*List<String> list = esSearchService.searchMsgByParam(param);
        Long count = esSearchService.searchMsgCountByParam(param);
        System.out.println(JSONObject.toJSONString(list));
        System.out.println(count);*/
        
        BootstrapTablePaginationVo<String> vo = eSAggsSearchService.searchMsgByParam(param);
        
        return generateResponseVo(ESWebStatusEnum.SUCCESS, vo);
    }
    
}

 

 四、service層json

@Service
public class ESAggsSearchImpl implements ESAggsSearchService {

    @Autowired
    private ESRepository eSRepository;
    
    @Autowired
    private ESAggsRepository eSAggsRepository;

    @Override
    public BootstrapTablePaginationVo<String> searchMsgByParam(BasicSearchParam param) throws Exception {
        return eSAggsRepository.searchMsgByParam(param);
    }

}
@Service
public class ESDeleteServiceImpl implements EsDeleteService{

    @Autowired
    private ESDeleteRepository esDeleteRepository;

    @Override
    public boolean delDataById(DeleteParam esDeleteParam) {
        return esDeleteRepository.delDataById(esDeleteParam);
    }

    
}
@Service
public class ESSearchServiceImpl implements ESSearchService{

    @Autowired
    private ESRepository eSRepository;
    
    @Autowired
    private ESSuggestRepository eSSuggestRepository;

    @Override
    public boolean buildIndex(String index) {
        return eSRepository.buildIndex(index);
    }

    @Override
    public int addPostDataDoc(String postId, String postContent) throws Exception {
        return eSRepository.addPostDataDoc(postId, postContent);
    }

    @Override
    public String addJSONDataDoc(String index, String type, Object obj) throws Exception {
        return eSRepository.addJSONDataDoc(index, type, obj);
    }

    @Override
    public void matchQuery(String keyWord, String index, int limit, int offset) throws Exception {
        eSRepository.matchQuery(keyWord, index, limit, offset);
    }

    @Override
    public Map<String, Object> searchDataByParam(String index, String type, String id) {
        return eSRepository.searchDataByParam(index, type, id);
    }

    @Override
    public String addTargetDataALL(JSONObject data, String index, String type, String id) {
        return eSRepository.addTargetDataALL(data, index, type, id);
    }

    @Override
    public boolean isIndexExist(String index) {
        return eSRepository.isIndexExist(index);
    }

    @Override
    public Iterator<MultiGetItemResponse> multiGetData(List<Item> itemList) {
        return eSRepository.multiGetData(itemList);
    }

    @Override
    public List<String> searchMessageByKeyWord(String index, String filed, String keyWord, int limit, int offset) throws Exception {
        return eSRepository.searchMessageByKeyWord(index, keyWord, limit, offset);
    }

    @Override
    public List<String> searchMsgByParam(BasicSearchParam param) throws Exception {
        return eSRepository.searchMsgByParam(param);
    }

    @Override
    public Long searchMsgCountByParam(BasicSearchParam param) throws Exception {
        return eSRepository.searchMsgCountByParam(param);
    }

    
}

 

 五、dao層,應該是最重要的層,主要用來進行操做es;瀏覽器

@Component
public class ESRepository extends BaseRepository{

    private static final Logger LOG = LoggerFactory.getLogger(ESRepository.class);

    @Autowired
    private TransportClient client;
    
    /**
     * 增長文檔,測試用的- 增長文檔
     * 
     * @param post
     * @return
     * @throws Exception
     */
    public int addPostDataDoc(String postId, String postContent) throws Exception {
        IndexResponse response = client.prepareIndex("forum_index", "post").setSource(XContentFactory.jsonBuilder().startObject().field("id", postId).field("content", postContent).endObject()).get();
        return response.hashCode();
    }
    
    /**
     * 搜索
     * @param param
     * @return
     * @throws Exception
     */
    public List<String> searchMsgByParam(BasicSearchParam param) throws Exception {
        String keyWord = param.getKeyWord();
        String filed = param.getField();
        String index = param.getIndex();
        
        Assert.assertNotNull(client);
        Assert.assertNotNull(filed);
        Assert.assertNotNull(index);
        Assert.assertNotNull(keyWord);
        
        //校驗索引是否成功
        if (!isIndexExist(index)) {
            return null;
        }
        
        //響應信息
        List<String> responseStrList = new ArrayList<String>();
        //去重的信息
        CollapseBuilder cb = new CollapseBuilder(param.getDistictField());
        
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(filed, keyWord);
        //查詢
        SearchResponse response = client.prepareSearch(index)
                                        .setQuery(matchQueryBuilder)
                                        .setCollapse(cb)
                                        .setFrom(param.getOffset())
                                        .setSize(param.getLimit())
                                        .get();
        
        SearchHits shList = response.getHits();
        for (SearchHit searchHit : shList) {  
            responseStrList.add(searchHit.getSourceAsString());
        }  
        return responseStrList;
    }
    
    /**
     * 搜索
     * @param param
     * @return
     * @throws Exception
     */
    public Long searchMsgCountByParam(BasicSearchParam param) throws Exception {
        String keyWord = param.getKeyWord();
        String filed = param.getField();
        String index = param.getIndex();
        
        Assert.assertNotNull(client);
        Assert.assertNotNull(filed);
        Assert.assertNotNull(index);
        Assert.assertNotNull(keyWord);
        
        //校驗索引是否成功
        if (!isIndexExist(index)) {
            return null;
        }
        
        //去重的信息
        CollapseBuilder cb = new CollapseBuilder(param.getDistictField());
        
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(filed, keyWord);
        SearchResponse response = client.prepareSearch(index)
                                .setQuery(matchQueryBuilder)
                                .setCollapse(cb)
                                .get();
        
        SearchHits shList = response.getHits();
        return shList.totalHits;
    }

    /**
     * 查詢
     * 
     * @param keyWord
     * @param index
     * @param limit
     * @param offset
     * @return
     * @throws Exception
     */
    public void matchQuery(String keyWord, String index, int limit, int offset) throws Exception {
        TermsQueryBuilder queryBuilder = QueryBuilders.termsQuery("content", keyWord);
        SearchResponse response = client.prepareSearch(index).setQuery(queryBuilder).setFrom(offset).setSize(limit).get();
        for (SearchHit searchHit : response.getHits()) {
            String sourceStr = searchHit.getSourceAsString();
            LOG.info("matchQuery-->>>" + sourceStr);
        }
    }

    /**
     * 批量查詢
     * 
     * 備註: 一、批量查詢是再你知道下面的屬性的時候,纔去批量查詢,若是都不知道Index,type就 直接查詢,那個是ES搜索,不是批量查詢
     * 二、批量查詢能提升程序查詢效率,根據需求自我添加
     * 
     * Item 類結構裏有屬性,index<==>_index,type<==>_type,id<==>_id
     * 
     * 下面是es文檔結構 { "_index": "bond2018-03-15", "_type": "bond", "_id":
     * "AWIoxzdzUfSIA3djz-ZK", "_score": 1, "_source": { "code": "130523",
     * "@timestamp": "2018-03-15T16:29:27.214Z", "name": "15福建09", "@version":
     * "1", "id": 13293, "type": "bond", "tags": [ ], "timestamp":
     * "2018-03-15T16:29:27.214Z" } }
     * 
     * @param itemList
     * @return
     */
    public Iterator<MultiGetItemResponse> multiGetData(List<Item> itemList) {
        if (!CollectionUtils.isEmpty(itemList)) {
            MultiGetRequestBuilder mgrb = client.prepareMultiGet();
            itemList.forEach(item -> {
                mgrb.add(item);
            });
            MultiGetResponse response = mgrb.get();
            // 查詢
            Iterator<MultiGetItemResponse> itMultigetItem = response.iterator();
            return itMultigetItem;
        }
        return null;
    }

    /**
     * 用戶添加索引數據文檔
     * 
     * @param index
     *            對應的數據庫
     * @param type
     *            類型 對應mysql的數據表
     * @param obj
     *            能夠添加目標類
     * @return
     * @throws Exception
     */
    public int addTargetObjectDataDoc(String index, String type, Object obj) throws Exception {
        // 構建參數和須要屬性
        Assert.assertNotNull(client);
        Assert.assertNotNull(index);
        Assert.assertNotNull(type);
        XContentBuilder xb = XContentFactory.jsonBuilder().startObject();

        // 下面是反射處理傳來的Object類,對應每一個字段映射到對應的索引裏,若是不須要這麼作的,就能夠註釋掉下面的代碼
        // 獲得類對象
        Class<?> userCla = (Class<?>) obj.getClass();
        // 獲得類中的全部屬性集合
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {// 遍歷obj文檔的字段字段,添加到數據裏
            Field f = fs[i];
            f.setAccessible(true); // 設置些屬性是能夠訪問的
            Object val = new Object();
            val = f.get(obj);
            // 獲得此屬性的值
            xb.field(f.getName(), val);
        }

        // 返回數據來源

        IndexResponse indexResponse = client.prepareIndex().setIndex(index).setType(type)
        // .setId(id) // 若是沒有設置id,則ES會自動生成一個id
                .setSource(xb.endObject()).get();
        LOG.info("添加document,index:" + index + ",type:" + type + ",目標類obj:" + JSONObject.toJSONString(obj));
        return indexResponse.hashCode();
    }

    /**
     * 查詢數據
     * 
     * @param index
     *            索引<----->關係型數據庫
     * @param type
     *            類型<----->關係型數據表
     * @param id
     *            數據ID<----->id
     * @return
     */
    public Map<String, Object> searchDataByParam(String index, String type, String id) {
        if (index == null || type == null || id == null) {
            LOG.info(" 沒法查詢數據,缺惟一值!!!!!!! ");
            return null;
        }
        // 來獲取查詢數據信息 - 查詢依據: index type id
        GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
        GetResponse getResponse = getRequestBuilder.execute().actionGet();
        // 這裏也有指定的時間獲取返回值的信息,若有特殊需求能夠

        return getResponse.getSource();
    }

    /**
     * 更新數據
     *
     * @param data
     *            添加的數據類型 json格式的
     * @param index
     *            索引<----->關係型數據庫
     * @param type
     *            類型<----->關係型數據表
     * @param id
     *            數據ID<----->id
     * @return
     */
    public void updateDataById(JSONObject data, String index, String type, String id) {
        if (index == null || type == null || id == null) {
            LOG.info(" 沒法更新數據,缺惟一值!!!!!!! ");
            return;
        }

        // 更新步驟
        UpdateRequest up = new UpdateRequest();
        up.index(index).type(type).id(id).doc(data);

        // 獲取響應信息
        // .actionGet(timeoutMillis),也能夠用這個方法,當過了必定的時間還沒獲得返回值的時候,就自動返回。
        UpdateResponse response = client.update(up).actionGet();
        LOG.info("更新數據狀態信息,status{}", response.status().getStatus());
    }

    /**
     * 添加數據
     *
     * @param data
     *            添加的數據類型 json格式的
     * @param index
     *            索引<----->關係型數據庫
     * @param type
     *            類型<----->關係型數據表
     * @param id
     *            數據ID<----->id
     * @return
     */
    public String addTargetDataALL(JSONObject data, String index, String type, String id) {
        // 判斷一下次id是否爲空,爲空的話就設置一個id
        if (id == null) {
            id = UUID.randomUUID().toString();
        }
        // 正式添加數據進去
        IndexResponse response = client.prepareIndex(index, type, id).setSource(data).get();

        LOG.info("addTargetDataALL 添加數據的狀態:{}", response.status().getStatus());

        return response.getId();
    }
    
    /**
     * JSON字符串加入到es裏
     * @param index
     * @param type
     * @param obj
     * @return
     * @throws Exception
     */
    public String addJSONDataDoc(String index, String type, Object obj) throws Exception{  
        //構建參數和須要屬性
        Assert.assertNotNull(client);
        Assert.assertNotNull(index);
        Assert.assertNotNull(type);

        client.prepareIndex().setIndex(index).setType(type).setSource();
        
        //返回數據來源
        IndexResponse indexResponse = client.prepareIndex().setIndex(index).setType(type).setSource(JSONObject.toJSONString(obj), XContentType.JSON).get();
        LOG.debug("添加document,index:" + index + ",type:" + type + ",目標類obj:" + JSONObject.toJSONString(obj));
        return indexResponse.getId();
    } 

    /**
     * 判斷索引是否存在
     *
     * @param index
     * @return
     */
    public boolean isIndexExist(String index) {
        IndicesExistsResponse iep = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet();
        if (iep.isExists()) {
            LOG.info("此索引 [" + index + "] 已經在ES集羣裏存在");
        } else {
            LOG.info(" 沒有此索引 [" + index + "] ");
        }
        return iep.isExists();
    }

    /**
     * 根據關鍵詞查詢
     * 
     * @param keyWord
     *            搜索詞
     * @param index
     *            索引
     * @param limit
     *            分頁參數
     * @param offset
     *            分頁參數
     * @return
     * @throws Exception
     */
    public List<String> searchMessageByKeyWord(String index, String keyWord, int limit, int offset) throws Exception {
        List<String> responseStrList = new ArrayList<String>();
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("content", keyWord);
        SearchResponse response = client.prepareSearch(index).setQuery(matchQueryBuilder).setFrom(offset).setSize(limit).get();
        for (SearchHit searchHit : response.getHits()) {
            responseStrList.add(searchHit.getSourceAsString());
        }
        return responseStrList;
    }
    
     /**
     * @param index
     * @param filed
     * @param keyWord
     * @param limit
     * @param offset
     * @return
     */
    public List<String> search_IdByKeyWord(String index, String filed, String keyWord, int limit, int offset) {  
        LOG.debug("es serarch index->" + index + ",filed->" + filed + ",keyWord->" + keyWord);
        Assert.assertNotNull(client);
        Assert.assertNotNull(index);
        Assert.assertNotNull(keyWord);
        List<String> responseStrList = new ArrayList<String>();
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(filed, keyWord);
        
        SearchResponse response = client.prepareSearch(index).setQuery(matchQueryBuilder).setFrom(offset).setSize(limit).get();
        
        for (SearchHit searchHit : response.getHits()) {  
            responseStrList.add(searchHit.getId());
        }  
        return responseStrList;
    }
    
    /**
     * 根據關鍵詞查詢,使用的查詢是term_query
     * @param index
     * @param filed
     * @param keyWord
     * @param limit
     * @param offset
     * @return
     */
    public List<String> searchMessageTermQueryByKeyWord(String index, String filed, String keyWord, int limit,
            int offset) {  
        LOG.info("es serarch index->" + index + ",filed->" + filed + ",keyWord->" + keyWord);
        Assert.assertNotNull(client);
        Assert.assertNotNull(index);
        Assert.assertNotNull(keyWord);
        List<String> responseStrList = new ArrayList<String>();
        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery(filed, keyWord);
        
        //查詢信息
        SearchResponse response = client.prepareSearch(index).setQuery(termsQueryBuilder).setFrom(offset).setSize(limit).get();
        for (SearchHit searchHit : response.getHits()) {  
            responseStrList.add(searchHit.getSourceAsString());
        }  
        return responseStrList;
    }
    
    /**
     * 根據關鍵詞查詢,使用的查詢是match_phrase
     * @param index
     * @param filed
     * @param keyWord
     * @param limit
     * @param offset
     * @return
     */
    public List<String> searchMessageMatchPhraseQueryByKeyWord(String index, String filed, String keyWord, int limit,
            int offset) {  
        LOG.info("es serarch index->" + index + ",filed->" + filed + ",keyWord->" + keyWord);
        Assert.assertNotNull(client);
        Assert.assertNotNull(index);
        Assert.assertNotNull(keyWord);
        List<String> responseStrList = new ArrayList<String>();
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery(filed, keyWord);
        
        SearchResponse response = client.prepareSearch(index).setQuery(matchPhraseQueryBuilder).setFrom(offset).setSize(limit).get();
        for (SearchHit searchHit : response.getHits()) {  
            responseStrList.add(searchHit.getSourceAsString());
        }  
        return responseStrList;
    }
    
    /**
     * 根據關鍵詞查詢  分頁查詢
     * @param filedMap 搜索關鍵詞Map key 是要搜索的字段 value是關鍵詞
     * @param index 索引,庫
     * @param limit
     * @param offset
     * @param filed 字段
     * @return
     * @throws Exception
     */
    public List<String> searchMessageByMapKeyWord(String index, Map<String, String> filedMap, int limit, int offset) throws Exception{  
        LOG.info("es serarch index->" + index + ",filedMap->" + JSONObject.toJSONString(filedMap));
        Assert.assertNotNull(client);
        Assert.assertNotNull(index);
        List<String> responseStrList = new ArrayList<String>();
        
        QueryBuilder finalQueryBuilder = null;
        if(!CollectionUtils.isEmpty(filedMap)) {
            for(Map.Entry<String, String> entry : filedMap.entrySet()) {
                String key = entry.getKey(); //key 是要搜索的字段
                String value = entry.getValue();//value是關鍵詞
                
                TermQueryBuilder termQueryBuilder1 = QueryBuilders.termQuery(key, value);
                finalQueryBuilder = QueryBuilders.boolQuery().must(termQueryBuilder1);
            }
        }
        //query
        SearchResponse response = client.prepareSearch(index).setQuery(finalQueryBuilder).setFrom(offset).setSize(limit).get();  
        for (SearchHit searchHit : response.getHits()) {  
            responseStrList.add(searchHit.getSourceAsString());
        }  
        return responseStrList;
    } 
    
    /**
     * 根據關鍵詞查詢  獲取總數
     * @param filedMap 搜索關鍵詞Map key 是要搜索的字段 value是關鍵詞
     * @param index 索引,庫
     * @param limit
     * @param offset
     * @param filed 字段
     * @return
     * @throws Exception
     */
    public long searchMessageByMapKeyWordCount(String index, Map<String, String> filedMap) throws Exception{  
        LOG.info("es serarch index->" + index + ",filedMap->" + filedMap);
        Assert.assertNotNull(client);
        Assert.assertNotNull(index);
        QueryBuilder finalQueryBuilder = null;
        if(!CollectionUtils.isEmpty(filedMap)) {
            for(Map.Entry<String, String> entry : filedMap.entrySet()) {
                String key = entry.getKey(); //key 是要搜索的字段
                String value = entry.getValue();//value是關鍵詞
                
                TermQueryBuilder termQueryBuilder1 = QueryBuilders.termQuery(key, value);
                finalQueryBuilder = QueryBuilders.boolQuery().must(termQueryBuilder1);
            }
        }
        long count = client.prepareSearch(index).setQuery(finalQueryBuilder).get().getHits().totalHits;
        return count;
    } 

    public List<String> searchMessageByKeyWord(String index, String filed, String keyWord, int limit, int offset) throws Exception {
        List<String> responseStrList = new ArrayList<String>();
        TermQueryBuilder matchQueryBuilder = QueryBuilders.termQuery(filed, keyWord);
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("userId", "251");
        QueryBuilder finalQueryBuilder = QueryBuilders.boolQuery().must(matchQueryBuilder).must(termQueryBuilder);

        SearchResponse response = client.prepareSearch(index).setQuery(finalQueryBuilder).setFrom(offset).setSize(limit).get();
        
        for (SearchHit searchHit : response.getHits()) {
            responseStrList.add(searchHit.getSourceAsString());
        }
        return responseStrList;
    }
    
}

 

 七、springboot配置文件springboot

 

# Elasticsearch
elasticsearch.cluster.name=elasticsearch
elasticsearch.ip=127.0.0.1
elasticsearch.port=9300
elasticsearch.pool=5

server.port=8088

 

 

 八、測試結果app

 使用瀏覽器進行訪問結果測試:

 

使用kibana進行測試,結果是同樣的;

 

 

 

 

 

 

 

 

 

 

--------------------- 可關注本人的公章號,每週推送精品文章

相關文章
相關標籤/搜索