Last active
August 14, 2020 02:33
-
-
Save AdrianJiao/a27c30957c86fec708be714fd2c44040 to your computer and use it in GitHub Desktop.
Es复杂搜索及当天时间
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
public List<MatchEntity> matchSearchInit(MatchEsSearchItem matchEsSearchItem) { | |
String searchKey = matchEsSearchItem.getSearchKey(); | |
Preconditions.checkArgument(StringUtil.isNotBlank(searchKey), "搜索关键字不能为空!"); | |
//搜索 | |
LocalDate today = LocalDate.now(); | |
Date beginDate = Date.from(today.minusMonths(3).atStartOfDay(ZoneId.systemDefault()).toInstant()); | |
Date endDate = Date.from(today.plusMonths(3).atStartOfDay(ZoneId.systemDefault()).toInstant()); | |
//时间过滤 | |
RangeQueryBuilder rangeQuery = QueryBuilders | |
.rangeQuery("matchTime") | |
.gte(beginDate.getTime()) | |
.lte(endDate.getTime()); | |
//匹配查询 | |
MatchPhraseQueryBuilder leagueNameMatch = QueryBuilders.matchPhraseQuery("leagueName", searchKey); | |
MatchPhraseQueryBuilder hostTeamNameMatch = QueryBuilders.matchPhraseQuery("hostTeamName", searchKey); | |
MatchPhraseQueryBuilder guestTeamNameMatch = QueryBuilders.matchPhraseQuery("guestTeamName", searchKey); | |
//bool关系 | |
BoolQueryBuilder boolQuery = QueryBuilders | |
.boolQuery() | |
.should(leagueNameMatch) | |
.should(hostTeamNameMatch) | |
.should(guestTeamNameMatch) | |
.minimumShouldMatch(1) | |
.filter(rangeQuery); | |
ScriptSortBuilder order = getTimeSort(); | |
//构造查询 | |
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder() | |
.withQuery(boolQuery) | |
.withSort(order) | |
.withPageable(PageRequest.of(0, 60)); | |
Page<MatchEntity> search = this.matchEsSearchRepository.search(queryBuilder.build()); | |
List<MatchEntity> content = search.getContent(); | |
return content.stream().sorted(Comparator.comparing(MatchEntity::getMatchTime)).collect(Collectors.toList()); | |
} | |
private ScriptSortBuilder getTimeSort() { | |
//时间过滤 | |
long now = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli(); | |
Script script = new Script("Math.abs(" + now + "L-doc['matchTime'].value)"); | |
return SortBuilders.scriptSort(script, ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.ASC); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment