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
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.tanpu.community.service.base;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tanpu.common.util.JsonUtil;
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 com.tanpu.community.model.ESWrapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
public class ESService {
@Autowired
private ESHelper helper;
public void insertOrUpdateThemes(List<ESThemeQo> qos) {
for (ESThemeQo qo : qos) {
insertOrUpdateTheme(qo);
}
}
// 只要设置了_id,则直接覆盖
public void insertOrUpdateTheme(ESThemeQo qo) {
helper.insert(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();
MatchPhraseQueryBuilder contentQb = QueryBuilders.matchPhraseQuery("textContent", keyword);
MatchPhraseQueryBuilder titleQb = QueryBuilders.matchPhraseQuery("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);
search.query(boolQb).sort("createTime", SortOrder.DESC).from(from).size(size);
SearchHit[] hits = helper.selectLike(search);
return Arrays.stream(hits).map(h -> {
return JsonUtil.toBean(h.getSourceAsString(), ESThemeQo.class);
}).collect(Collectors.toList());
}
}