欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

ElasticSearch:个人博客搜索及首页展示

程序员文章站 2022-11-02 09:19:05
前言 最近学习了SpringBoot,搞了一个小型博客系统,在这个系统中的首页内容展示、全文搜索用到了elasticsearch。系统中持久层使用的是Springdata,但是没有使用spr...

前言

最近学习了SpringBoot,搞了一个小型博客系统,在这个系统中的首页内容展示、全文搜索用到了elasticsearch。系统中持久层使用的是Springdata,但是没有使用spring-data-elasticsearch,而是单独引入的elasticsearch、transport依赖。下面就将我系统中涉及到的关于elasticsearch的代码贴出来、供大家一起学习。

准备环境

window系统安装zip版,直接解压就可以。

引入依赖


        
            org.elasticsearch.client
            transport
            5.5.2
        
        
           org.elasticsearch
           elasticsearch
           5.5.2
        

返回数据包装类EsBlogVO

用来包装elasticsearch返回的数据。

public class EsBlogVO implements Serializable {

    private static final long serialVersionUID = 1L;

    private String id;

    private Long blogId; // Blog 的 id

    private String title;

    private String summary;

    private String content;

    private String username;

    private String avatar;

    private Timestamp createTime;

    private Integer readSize = 0; // 访问量、阅读量

    private Integer commentSize = 0; // 评论量

    private Integer voteSize = 0; // 点赞量

    private String tags; // 标签  

    public EsBlogVO(){

    }

    public EsBlogVO(Blog blog){
        this.blogId = blog.getId();
        this.title = blog.getTitle();
        this.summary = blog.getSummary();
        this.content = blog.getContent();
        this.username = blog.getUser().getUsername();
        this.avatar = blog.getUser().getAvatar();
        this.createTime = blog.getCreateTime();
        this.readSize = blog.getReading();
        this.commentSize = blog.getCommentSize();
        this.voteSize = blog.getVoteSize();
        this.tags = blog.getTags();
    }

    public void update(Blog blog){
        this.blogId = blog.getId();
        this.title = blog.getTitle();
        this.summary = blog.getSummary();
        this.content = blog.getContent();
        this.username = blog.getUser().getUsername();
        this.avatar = blog.getUser().getAvatar();
        this.createTime = blog.getCreateTime();
        this.readSize = blog.getReading();
        this.commentSize = blog.getCommentSize();
        this.voteSize = blog.getVoteSize();
        this.tags = blog.getTags();
    }

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public Long getBlogId() {
        return blogId;
    }
    public void setBlogId(Long blogId) {
        this.blogId = blogId;
    }

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }

    public String getSummary() {
        return summary;
    }
    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public String getAvatar() {
        return avatar;
    }
    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public Timestamp getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Timestamp createTime) {
        this.createTime = createTime;
    }

    public Integer getReadSize() {
        return readSize;
    }
    public void setReadSize(Integer readSize) {
        this.readSize = readSize;
    }

    public Integer getCommentSize() {
        return commentSize;
    }
    public void setCommentSize(Integer commentSize) {
        this.commentSize = commentSize;
    }

    public Integer getVoteSize() {
        return voteSize;
    }
    public void setVoteSize(Integer voteSize) {
        this.voteSize = voteSize;
    }

    public String getTags() {
        return tags;
    }
    public void setTags(String tags) {
        this.tags = tags;
    }

    @Override
    public String toString() {
        return "EsBlogVO [id=" + id + ", blogId=" + blogId + ", title=" + title + ", summary=" + summary + ", content="
                + content + ", username=" + username + ", avatar=" + avatar + ", createTime=" + createTime
                + ", readSize=" + readSize + ", commentSize=" + commentSize + ", voteSize=" + voteSize + ", tags="
                + tags + "]";
    }

分页PageBean

系统中持久层用到的是SpringData框架,他有自己的Page,为了方便与前端pageHtml中的属性不冲突,依照SpringData的page自己写了一个PageBean。

public class PageBean implements Serializable {

    private static final long serialVersionUID = 1L;

    //当前页面
    private int number;
    //页面大小
    private int size;
    //总页数
    @SuppressWarnings("unused")  
    private int totalPages;
    //总记录数
    private int totalElements;
    //是否是第一个
    @SuppressWarnings("unused")  
    private boolean first;
    //是否是最后一个
    @SuppressWarnings("unused")  
    private boolean last;
    //是否有上一页
    @SuppressWarnings("unused")  
    private boolean hasPrevious;
    //是否有下一页
    @SuppressWarnings("unused")  
    private boolean hasNext;
    //页数位置
    @SuppressWarnings("unused")  
    private int offSet;

    private List contentList;


    public PageBean() {

    }

    public PageBean(int number, int size) {
        super();
        this.number = number;
        this.size = size;
    }

    public PageBean(int number, int size, int totalElements) {
        super();
        this.number = number;
        this.size = size;
        this.totalElements = totalElements;
    }

    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }

    public int getSize() {
        return size;
    }
    public void setSize(int size) {
        this.size = size;
    }
    /**
     * 计算页数
     * @return
     */
    public int getTotalPages() {
        return (int) Math.ceil((double) totalElements / (double) getSize());
    }
    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    public int getTotalElements() {
        return totalElements;
    }
    public void setTotalElements(int totalElements) {
        this.totalElements = totalElements;
    }

    public boolean isFirst() {
        return !isHasPrevious();
    }
    public void setFirst(boolean first) {
        this.first = first;
    }
    /**
     * 计算位置
     * @return
     */
    public int getOffSet() {
        return this.number * this.size;
    }
    public void setOffSet(int offSet) {
        this.offSet = offSet;
    }

    public boolean isLast() {
        return !isHasNext();  
    }
    public void setLast(boolean last) {
        this.last = last;
    }

    public boolean isHasPrevious() {
        return getNumber() > 0;
    }
    public void setHasPrevious(boolean hasPrevious) {
        this.hasPrevious = hasPrevious;
    }

    public boolean isHasNext() {
        return (number == getTotalPages()) ? false : true;
    }
    public void setHasNext(boolean hasNext) {
        this.hasNext = hasNext;
    }

    public List getContentList() {
        return contentList;
    }
    public void setContentList(List contentList) {
        this.contentList = contentList;
    }
}

EsRepositity

博客中涉及到的elastcisearch所有业务代码

@Component
public class EsBlogRepository {

    private static final String String = null;

    @Autowired
    private TransportClient client;

    @Autowired
    private UserRepository userRepository;

    /**
     * 根据id查询document
     * @param id
     * @return
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @throws ParseException 
     */
    public EsBlogVO getEsBlogByBlogId(Long blogId) throws IllegalAccessException, InvocationTargetException, ParseException {

        TermQueryBuilder termQuery = QueryBuilders.termQuery("blogId", blogId);

        SearchResponse searchResponse = this.client.prepareSearch("myblog")
                            .setTypes("blog")
                            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                            .setQuery(termQuery)
                            .get();

        EsBlogVO esBlogVo = null;
        for(SearchHit hit:searchResponse.getHits()) {
            //
            esBlogVo = new EsBlogVO();
            Map source = hit.getSource();
            //将id存放到Map中
            source.put("id", hit.getId());
            //转化时间
            String date = (java.lang.String) source.get("createTime");

            if( date!=null && !(date.equals(""))) {
                 date = date.replace("Z", " UTC");//注意是空格+UTC
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
                    Date d = format.parse(date );
                    SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
                    String sdate=format2.format(d);        
                    Timestamp fTimestamp=Timestamp.valueOf(sdate);   
                    //将转化后的时间存放到map中
                    source.put("createTime", fTimestamp);
            }
            //将map转化为Bean
            BeanUtils.populate(esBlogVo, source);
            break;
        }
        System.out.println(esBlogVo);
        return esBlogVo;
    }
    /**
     * 删除索引中的document
     * @param esBlogId
     */
    public void deleteEsBlog(String esBlogId) {
        DeleteResponse response = client.prepareDelete("myblog", "blog", esBlogId).get(); 
        Result result = response.getResult();
        System.out.println(result);
    }
    /**
     * 将document添加到索引中
     * @param blog
     * @throws IOException
     */
    public void addEsBlog(EsBlogVO blog) throws IOException {

        IndexResponse response = client.prepareIndex("myblog", "blog")  
                .setSource(XContentFactory.jsonBuilder()  
                        .startObject()  
                            .field("blogId", blog.getBlogId())  
                            .field("title", blog.getTitle())  
                            .field("summary",blog.getSummary())  
                            .field("content", blog.getContent())  
                            .field("username", blog.getUsername())  
                            .field("avatar", blog.getAvatar())  
                            .field("createTime",blog.getCreateTime())  
                            .field("readSize", blog.getReadSize())  
                            .field("commentSize", blog.getCommentSize())  
                            .field("voteSize", blog.getVoteSize())  
                            .field("tags",blog.getTags())  
                        .endObject())  
                .get();
        System.out.println(response.getResult()+","+response.getId());
    }
    /**
     * 修改索引中的document数据
     * @param blog
     * @throws IOException
     */
    public void updateEsblog(EsBlogVO blog) throws IOException {

        UpdateResponse response = client.prepareUpdate("myblog", "blog",blog.getId())  
                .setDoc(XContentFactory.jsonBuilder()  
                        .startObject()  
                        .field("blogId", blog.getBlogId())  
                        .field("title", blog.getTitle())  
                        .field("summary",blog.getSummary())  
                        .field("content", blog.getContent())  
                        .field("username", blog.getUsername())  
                        .field("avatar", blog.getAvatar())  
                        .field("createTime",blog.getCreateTime())  
                        .field("readSize", blog.getReadSize())  
                        .field("commentSize", blog.getCommentSize())  
                        .field("voteSize", blog.getVoteSize())  
                        .field("tags",blog.getTags())  
                        .endObject())  
                .get();  
        System.out.println(response.getResult());
    }
    /**
     * 查询前三十个标签
     * @return
     */
    public List listTop30tags(){
        List list = new ArrayList<>();
        //进行聚合查询,terms按照某个字段中进行分组  
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders  
                .terms("tags")    //aggs的名称,自定义,取数据的时候与其一致即可  
                .field("tags")             //需要分组的字段  
                .order(Terms.Order.count(false));  //true表asc按照doc_count排序,false表示desc排序       

        //查询数据进行聚合分析  
        SearchResponse response = client.prepareSearch("myblog").setTypes("blog")  
                .addAggregation(termsAggregationBuilder)  
                .setSize(30)  
                .execute()  
                .actionGet();  
        //获取聚合   
        StringTerms modelTerms = (StringTerms) response.getAggregations().asMap().get("tags");
        Iterator modelBucketIt = modelTerms.getBuckets().iterator();
        //遍历桶
        while(modelBucketIt.hasNext()) {
             Bucket actiontypeBucket = modelBucketIt.next();
             list.add(new TagVO(actiontypeBucket.getKey().toString(),
                     actiontypeBucket.getDocCount()));

        }
        return list;
    }

    /**
     * 获取前12个user
     * @return
     */
    public List listTop12Users(){
        List usernamelist = new ArrayList<>();
        //进行聚合查询,terms按照某个字段中进行分组  
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders  
                .terms("usernames")    //aggs的名称,自定义,取数据的时候与其一致即可  
                .field("username")             //需要分组的字段  
                .order(Terms.Order.count(false));  //true表asc按照doc_count排序,false表示desc排序       

        //查询数据进行聚合分析  
        SearchResponse response = client.prepareSearch("myblog").setTypes("blog")  
                .addAggregation(termsAggregationBuilder)  
                .setSize(12)  
                .execute()  
                .actionGet();  
        //获取聚合   
        StringTerms modelTerms = (StringTerms) response.getAggregations().asMap().get("usernames");
        Iterator modelBucketIt = modelTerms.getBuckets().iterator();
        //遍历桶
        while(modelBucketIt.hasNext()) {
             Bucket actiontypeBucket = modelBucketIt.next();
             String username = actiontypeBucket.getKey().toString();
             usernamelist.add(username);
        }
        List list = userRepository.findByUsernameIn(usernamelist);
        return list;
    }

    /**
     * 搜索条件的总数
     * @param title
     * @param Summary
     * @param content
     * @param tags
     * @return
     */
    public Integer findTotalElementBySearchtxt(String title, String Summary, String content, String tags) {
        //建立bool查询
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        //使用should实现或者查询
        boolBuilder.should(QueryBuilders.matchQuery("title",title));
        boolBuilder.should(QueryBuilders.matchQuery("summary",Summary));
        boolBuilder.should(QueryBuilders.matchQuery("content",content));
        boolBuilder.should(QueryBuilders.matchQuery("tags",tags));
        //查询
        SearchRequestBuilder searchRequestBuilder = this.client.prepareSearch("myblog")
                .setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                .setQuery(boolBuilder);
        //执行结果
        SearchResponse response = searchRequestBuilder.get();
        long totalHits = response.getHits().totalHits;
        return new Long(totalHits).intValue();
    }

    /**
     * 根据搜索条件进行查询,查询结果高亮显示,数据分页
     * @param title
     * @param Summary
     * @param content
     * @param tags
     * @param pageable
     * @return
     * @throws ParseException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     */
    public PageBean findByTitleOrSummaryOrTagsOrContent(String title, String Summary, String content, String tags,
            PageBean pageable) throws ParseException, IllegalAccessException, InvocationTargetException {

        //建立bool查询
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        //使用should实现或者查询
        boolBuilder.should(QueryBuilders.matchQuery("title",title));
        boolBuilder.should(QueryBuilders.matchQuery("summary",Summary));
        boolBuilder.should(QueryBuilders.matchQuery("content",content));
        boolBuilder.should(QueryBuilders.matchQuery("tags",tags));
        //查询
        SearchRequestBuilder searchRequestBuilder = this.client.prepareSearch("myblog")
                .setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                .setQuery(boolBuilder)
                .setFrom(pageable.getOffSet())
                .setSize(pageable.getSize());
        // 设置高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        searchRequestBuilder.highlighter(highlightBuilder);
        // 执行结果
         //执行结果
        SearchResponse response = searchRequestBuilder.get();
        //接受结果
        List result = new ArrayList();

        //遍历结果
        //SearchHits hits = response.getHits();
        for(SearchHit hits:response.getHits()){
            //实例化对象
            EsBlogVO esBlogVo = new EsBlogVO();
            //获得查询数据
            Map source = hits.getSource();
            //转化时间
            String date = (java.lang.String) source.get("createTime");
            date = date.replace("Z", " UTC");//注意是空格+UTC
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
            Date d = format.parse(date );
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
            String sdate=format2.format(d);        
            Timestamp fTimestamp=Timestamp.valueOf(sdate);   
            //将转化后的时间存放到map中
            source.put("createTime", fTimestamp);
            //将map转化为Bean
            BeanUtils.populate(esBlogVo, source);

            //处理高亮片段
            Map highlightFields = hits.getHighlightFields();
            //title
            HighlightField titleField = highlightFields.get("title");
            if(titleField!=null){
                Text[] fragments = titleField.fragments();
                String titleTmp ="";
                for(Text text:fragments){
                    titleTmp+=text;
                }
                //将高亮片段组装到结果中去
                esBlogVo.setTitle(titleTmp);
            }
            //summary
            HighlightField summary = highlightFields.get("summary");
            if(summary != null) {
                Text[] fragmentSummary = summary.fragments();
                String summaryTmp = "";
                for(Text sum:fragmentSummary) {
                    summaryTmp += sum;
                }
                esBlogVo.setSummary(summaryTmp);
            }
            //将查询出来的结果放到集合当中
            result.add(esBlogVo);
        }
        pageable.setContentList(result);
        return pageable;
    }
    /**
     * 按最热查询
     * @param keyword
     * @param pageable
     * @return
     * @throws ParseException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public PageBean listHotstEsBlogs(String keyword,PageBean pageable) throws ParseException, IllegalAccessException, InvocationTargetException{
        //建立bool查询
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        //使用should实现或者查询
        boolBuilder.should(QueryBuilders.matchQuery("title",keyword));
        boolBuilder.should(QueryBuilders.matchQuery("summary",keyword));
        boolBuilder.should(QueryBuilders.matchQuery("content",keyword));
        boolBuilder.should(QueryBuilders.matchQuery("tags",keyword));
        //设置排序
        FieldSortBuilder readSize = SortBuilders.fieldSort("readSize").order(SortOrder.DESC);
        FieldSortBuilder commentSize = SortBuilders.fieldSort("commentSize").order(SortOrder.DESC);
        FieldSortBuilder voteSize = SortBuilders.fieldSort("voteSize").order(SortOrder.DESC);
        FieldSortBuilder createTime = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);

        //查询
       SearchResponse searchResponse = this.client.prepareSearch("myblog")
                .setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                .setQuery(boolBuilder)
                .addSort(readSize)
                .addSort(commentSize)
                .addSort(voteSize)
                .addSort(createTime)
                .setFrom(pageable.getOffSet())
                .setSize(pageable.getSize())
                .get();
        //打印语句
        System.out.println(searchResponse.toString());
        //接受结果
        List result = new ArrayList();
        for(SearchHit hits:searchResponse.getHits()){
            //实例化对象
            EsBlogVO esBlogVo = new EsBlogVO();
            //获得查询数据
            Map source = hits.getSource();
            //转化时间
            String date = (java.lang.String) source.get("createTime");
            date = date.replace("Z", " UTC");//注意是空格+UTC
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
            Date d = format.parse(date );
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
            String sdate=format2.format(d);        
            Timestamp fTimestamp=Timestamp.valueOf(sdate);   
            //将转化后的时间存放到map中
            source.put("createTime", fTimestamp);
            //将map转化为Bean
            BeanUtils.populate(esBlogVo, source);
            //将查询出来的结果放到集合当中
            result.add(esBlogVo);
        }
        pageable.setContentList(result);
        return pageable;
    }

    /**
     * 按最新查询
     * @param keyword
     * @param pageable
     * @return
     * @throws ParseException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public PageBean listNewestEsBlogs(String keyword,PageBean pageable) throws ParseException, IllegalAccessException, InvocationTargetException{
        //建立bool查询
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        //使用should实现或者查询
        boolBuilder.should(QueryBuilders.matchQuery("title",keyword));
        boolBuilder.should(QueryBuilders.matchQuery("summary",keyword));
        boolBuilder.should(QueryBuilders.matchQuery("content",keyword));
        boolBuilder.should(QueryBuilders.matchQuery("tags",keyword));
        //设置排序
        FieldSortBuilder createTime = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);

        //查询
       SearchResponse searchResponse = this.client.prepareSearch("myblog")
                .setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                .setQuery(boolBuilder)
                .addSort(createTime)
                .setFrom(pageable.getOffSet())
                .setSize(pageable.getSize())
                .get();
        //打印语句
        System.out.println(searchResponse.toString());
        //接受结果
        List result = new ArrayList();
        for(SearchHit hits:searchResponse.getHits()){
            //实例化对象
            EsBlogVO esBlogVo = new EsBlogVO();
            //获得查询数据
            Map source = hits.getSource();
            //转化时间
            String date = (java.lang.String) source.get("createTime");
            date = date.replace("Z", " UTC");//注意是空格+UTC
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
            Date d = format.parse(date );
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
            String sdate=format2.format(d);        
            Timestamp fTimestamp=Timestamp.valueOf(sdate);   
            //将转化后的时间存放到map中
            source.put("createTime", fTimestamp);
            //将map转化为Bean
            BeanUtils.populate(esBlogVo, source);
            //将查询出来的结果放到集合当中
            result.add(esBlogVo);
        }
        pageable.setContentList(result);
        return pageable;
    }

    /**
     * 查询document中最新的前5个
     * @param offset
     * @param pageSize
     * @return
     * @throws ParseException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public List listnewTop5EsBlog (int offset,int pageSize) throws ParseException, IllegalAccessException, InvocationTargetException{
        //全文检索
        MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
        //设置排序
        FieldSortBuilder createTime = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);

        //查询
       SearchResponse searchResponse = this.client.prepareSearch("myblog")
                .setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                .setQuery(matchAllQuery)
                .addSort(createTime)
                .setFrom(offset)
                .setSize(pageSize)
                .get();
        //打印语句
        System.out.println(searchResponse.toString());
        //接受结果
        List result = new ArrayList();
        for(SearchHit hits:searchResponse.getHits()){
            //实例化对象
            EsBlogVO esBlogVo = new EsBlogVO();
            //获得查询数据
            Map source = hits.getSource();
            //转化时间
            String date = (java.lang.String) source.get("createTime");
            date = date.replace("Z", " UTC");//注意是空格+UTC
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
            Date d = format.parse(date );
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
            String sdate=format2.format(d);        
            Timestamp fTimestamp=Timestamp.valueOf(sdate);   
            //将转化后的时间存放到map中
            source.put("createTime", fTimestamp);
            //将map转化为Bean
            BeanUtils.populate(esBlogVo, source);
            //将查询出来的结果放到集合当中
            result.add(esBlogVo);
        }
        return result;
    }
    /**
     * 查询document中最热5个
     * @param offset
     * @param pageSize
     * @return
     * @throws ParseException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     */
    public List listHot5EsBlog (int offset,int pageSize) throws ParseException, IllegalAccessException, InvocationTargetException{
        //建立bool查询
        MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
        //设置排序
        FieldSortBuilder readSize = SortBuilders.fieldSort("readSize").order(SortOrder.DESC);
        FieldSortBuilder commentSize = SortBuilders.fieldSort("commentSize").order(SortOrder.DESC);
        FieldSortBuilder voteSize = SortBuilders.fieldSort("voteSize").order(SortOrder.DESC);
        FieldSortBuilder createTime = SortBuilders.fieldSort("createTime").order(SortOrder.DESC); 
        //查询
       SearchResponse searchResponse = this.client.prepareSearch("myblog")
                .setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                .setQuery(matchAllQuery)
                .addSort(readSize)
                .addSort(commentSize)
                .addSort(voteSize)
                .addSort(createTime)
                .setFrom(offset)
                .setSize(pageSize)
                .get();
        //打印语句
        System.out.println(searchResponse.toString());
        //接受结果
        List result = new ArrayList();
        for(SearchHit hits:searchResponse.getHits()){
            //实例化对象
            EsBlogVO esBlogVo = new EsBlogVO();
            //获得查询数据
            Map source = hits.getSource();
            //转化时间
            String date = (java.lang.String) source.get("createTime");
            date = date.replace("Z", " UTC");//注意是空格+UTC
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
            Date d = format.parse(date );
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
            String sdate=format2.format(d);        
            Timestamp fTimestamp=Timestamp.valueOf(sdate);   
            //将转化后的时间存放到map中
            source.put("createTime", fTimestamp);
            //将map转化为Bean
            BeanUtils.populate(esBlogVo, source);
            //将查询出来的结果放到集合当中
            result.add(esBlogVo);
        }
        return result;
    }
    /**
     * 查询document总记录数
     * @return
     */
    public Integer findTotalElement() {
        //建立bool查询
         MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();

        SearchRequestBuilder searchRequestBuilder = this.client.prepareSearch("myblog")
                .setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                .setQuery(matchAllQuery);
        //执行结果
        SearchResponse response = searchRequestBuilder.get();
        long totalHits = response.getHits().totalHits;
        return new Long(totalHits).intValue();
    }
    /**
     * esBlog的document的list分页查询,按时间进行排序
     * @param pageable
     * @return
     * @throws ParseException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public PageBean listEsBlogOrderByNew(PageBean pageable) throws ParseException, IllegalAccessException, InvocationTargetException {

        //建立bool查询
         MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
        //使用should实现或者查询
        //查询
       SearchResponse searchResponse = this.client.prepareSearch("myblog")
                .setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
                .setQuery(matchAllQuery)
                .addSort("createTime", SortOrder.DESC)
                .setFrom(pageable.getOffSet())
                .setSize(pageable.getSize())
                .get();

        //接受结果
        List result = new ArrayList();
        for(SearchHit hits:searchResponse.getHits()){
            //实例化对象
            EsBlogVO esBlogVo = new EsBlogVO();
            //获得查询数据
            Map source = hits.getSource();
            //转化时间
            String date = (java.lang.String) source.get("createTime");
            date = date.replace("Z", " UTC");//注意是空格+UTC
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
            Date d = format.parse(date );
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
            String sdate=format2.format(d);        
            Timestamp fTimestamp=Timestamp.valueOf(sdate);   
            //将转化后的时间存放到map中
            source.put("createTime", fTimestamp);
            //将map转化为Bean
            BeanUtils.populate(esBlogVo, source);
            //将查询出来的结果放到集合当中
            result.add(esBlogVo);
        }
        pageable.setContentList(result);
        return pageable;
    }
    /**
     * 查询博客document列表,按照热度进行排序
     * @param pageable
     * @return
     * @throws ParseException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public PageBean listEsBlogOrderByHot(PageBean pageable)
            throws ParseException, IllegalAccessException, InvocationTargetException {
        // 建立bool查询
        MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
        // 设置排序
        FieldSortBuilder readSize = SortBuilders.fieldSort("readSize").order(SortOrder.DESC);
        FieldSortBuilder commentSize = SortBuilders.fieldSort("commentSize").order(SortOrder.DESC);
        FieldSortBuilder voteSize = SortBuilders.fieldSort("voteSize").order(SortOrder.DESC);
        FieldSortBuilder createTime = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
        // 查询
        SearchResponse searchResponse = this.client.prepareSearch("myblog").setTypes("blog")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) // 设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询.// 2.SearchType.SCAN 扫描查询,无序
                .setQuery(matchAllQuery)
                .addSort(readSize)
                .addSort(commentSize)
                .addSort(voteSize)
                .addSort(createTime)
                .setFrom(pageable.getOffSet())
                .setSize(pageable.getSize())
                .get();
        System.out.println(searchResponse.toString());
        // 接受结果
        List result = new ArrayList();
        for (SearchHit hits : searchResponse.getHits()) {
            // 实例化对象
            EsBlogVO esBlogVo = new EsBlogVO();
            // 获得查询数据
            Map source = hits.getSource();
            // 转化时间
            String date = (java.lang.String) source.get("createTime");
            date = date.replace("Z", " UTC");// 注意是空格+UTC
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");// 注意格式化的表达式
            Date d = format.parse(date);
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sdate = format2.format(d);
            Timestamp fTimestamp = Timestamp.valueOf(sdate);
            // 将转化后的时间存放到map中
            source.put("createTime", fTimestamp);
            // 将map转化为Bean
            BeanUtils.populate(esBlogVo, source);
            // 将查询出来的结果放到集合当中
            result.add(esBlogVo);
        }
        pageable.setContentList(result);
        return pageable;
    }
}

小结

上边ElasticSearch中的业务代码写的有点复杂,因为我是一个初学者,但是基本功能能够实现,如果上面有什么错误或者大家有什么建议,请大家留言,一起讨论一下。