ESService.java 1.95 KB
Newer Older
张辰's avatar
张辰 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
package com.tanpu.community.service.base;

import com.alibaba.fastjson.JSON;
import com.tanpu.community.api.beans.qo.ESThemeQo;
import com.tanpu.community.api.beans.qo.ThemeQo;
import com.tanpu.community.dao.entity.community.ThemeEntity;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ESService {

    @Autowired
    private ESHelper helper;

    private static final String INDEX_THEME = "theme";

    public void insertTheme(ESThemeQo qo) {
        helper.insert(INDEX_THEME, String.valueOf(qo.themeType), qo.themeId, JSON.toJSONString(qo));
    }

    public List<ESThemeQo> queryThemeIdByContentAndTitle(String keyword, int from, int size) {
        SearchSourceBuilder search = new SearchSourceBuilder();

        BoolQueryBuilder boolQb = QueryBuilders.boolQuery();
        MatchQueryBuilder contentQb = QueryBuilders.matchQuery("content", keyword);
        MatchQueryBuilder titleQb = QueryBuilders.matchQuery("title", keyword);
        boolQb.should(contentQb);
        boolQb.should(titleQb);

        String[] includes = new String[]{"id", "themeId", "createTime"};
        String[] excludes = new String[]{};
        search.query(boolQb).fetchSource(includes, excludes).sort("createTime", SortOrder.DESC).from(from).size(size);

        SearchHit[] hits = helper.selectLike(INDEX_THEME, search);
        return Arrays.stream(hits).map(h -> {
            return JSON.parseObject(h.toString(), ESThemeQo.class);
        }).collect(Collectors.toList());
    }
张辰's avatar
张辰 committed
51
}