SpringBoot下Jest實現ElasticSearch查詢結果直接寫入實體對象中

前一篇博文:SpringBoot下使用Jest實現對ElasticSearch的多條件查詢 中使用Jest獲取到ElasticSearch中的數據後其一中做法是轉換爲JsonObject後自行解析獲取自己想要的字段信息放置到實體對象之中,這種做法雖然繁瑣一點,但是有一個優點就是結構可以自己指定,不用再考慮層級關係如何。但是人是懶惰的,那麼如何使用Jest將結果直接放置進實體之中呢?下面簡單介紹一下做法。

 

 

一、構建實體

首先以下爲demo的mapping:

{
    "mapping": {
        "info": {
            "properties": {
                "textInfo": {
                    "type": "nested",
                    "properties": {
                    }
                },
                "textId": {
                    "type": "keyword"
                },
                "textTags": {
                    "type": "nested",
                    "properties": {
                    }
                }
            }
        }
    }
}

 其中,textId爲keyword,剩下兩個爲複雜結構,詳細便不列出,對應的程序內實體類爲:

import java.util.List;

public class MInfo {
    private String textId;
    private List<textDetail> textInfo;
    private List<textTag> textTags;

    public String getTextId() {
        return textId;
    }

    public void setTextId(String textId) {
        this.textId = textId;
    }

    public List<textDetail> getTextInfo() {
        return textInfo;
    }

    public void setTextInfo(List<textDetail> textInfo) {
        this.textInfo = textInfo;
    }

    public List<textTag> getTextTags() {
        return textTags;
    }

    public void setTextTags(List<textTag> textTags) {
        this.textTags = textTags;
    }
}

其實也就是寫入時的實體,當然讀取數據的時候不必要讀取全部的數據,按需獲取。

 

 

 

二、方法構造

    public List<MInfo> getSentence(QueryConditions queryConditions, Integer begin){
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        List<MInfo> mInfos;
        try{
            setBoolQueryBuilder(queryBuilder, queryConditions);
            searchSourceBuilder.query(queryBuilder).from(begin).size(limitSize);
            Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).addType(typeName).build();
            JestResult jestResult = jestClient.execute(search);
            mInfos = jestResult.getSourceAsObjectList(MInfo.class);
            logger.info("已經獲取條件下的信息");
            return mInfos;
        }catch (IOException e){
            logger.error("獲取指定條件下的信息:" + queryConditions.toString() + "IO異常:", e);
            return null;
        }catch (Exception e){
            logger.error("獲取指定條件下的信息:" + queryConditions.toString() + "異常:", e);
            return null;
        }
    }

其中的setBoolQueryBuilder(queryBuilder, queryConditions)爲自定義的通用設置檢索條件的方法。

因爲這裏是查詢es內數據,所以會得到多條結果,需要調用的是getSourceAsObjectList,而getSourceAsObject多見用於聚合結果寫入實體類中。

讀取數據時,推薦要使用分頁的方法,尤其在讀取量大時,採用適量多次獲取數據的方法。

發佈了17 篇原創文章 · 獲贊 9 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章