希望给同样遇见es的你带来帮助,也希望彼此有更多的讨论
版本选择6.4.3
1-Java 客户端的使用 (中)
自动补全
条件查询(高亮展示)
1-自动补全功能
- 自动补全,选择你想补全的字段,经过分词,后存储到es
private boolean updateSuggest(CometIndex cometIndex) {
AnalyzeRequest request = new AnalyzeRequest();
request.text(cometIndex.getTitle(), cometIndex.getAuthor());
request.analyzer("ik_smart");
try {
AnalyzeResponse response = client.indices().analyze(request, RequestOptions.DEFAULT);
List<AnalyzeResponse.AnalyzeToken> tokens = response.getTokens();
if (tokens == null) {
log.warn("Can not analyze token for comet:{}", cometIndex.getCometId());
return false;
}
List<CometSuggest> suggests = Lists.newArrayList();
for (AnalyzeResponse.AnalyzeToken token : tokens) {
if ("<NUM>".equals(token.getTerm()) || token.getTerm().length() < 2) {
continue;
}
CometSuggest cometSuggest = new CometSuggest();
cometSuggest.setInput(token.getTerm());
suggests.add(cometSuggest);
}
cometIndex.setSuggest(suggests);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public List<String> suggest(String prefix) {
try {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
CompletionSuggestionBuilder completionSuggestionBuilder=SuggestBuilders.completionSuggestion("suggest").prefix(prefix).size(5);
SuggestBuilder suggestBuilder = new SuggestBuilder();
suggestBuilder.addSuggestion("search_autoComplete", completionSuggestionBuilder);
searchSourceBuilder.suggest(suggestBuilder);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(CometIndexKey.INDEX_NAME);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Suggest suggest = searchResponse.getSuggest();
int maxSuggest=0;
Set<String> suggestSet=new HashSet<String>();
CompletionSuggestion completionSuggestion = suggest.getSuggestion("search_autoComplete");
for (CompletionSuggestion.Entry entry : completionSuggestion.getEntries()) {
if(entry.getOptions().isEmpty()){
continue;
}
for (CompletionSuggestion.Entry.Option option : entry) {
String suggestText = option.getText().string();
if(suggestSet.contains(suggestText)){
continue;
}
suggestSet.add(suggestText);
maxSuggest++;
}
if(maxSuggest>5){
break;
}
}
List <String>stringList=Lists.newArrayList(suggestSet.toArray(new String[]{}));
return stringList;
}catch (Exception e){
e.printStackTrace();
log.error("suggest error");
return null;
}
}
2-条件查询(高亮展示)
@Override
public List<CometIndexVO> query(RentSearch rentSearch) {
try {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
if (StringUtils.isNoneBlank(rentSearch.getCategory())) {
boolQuery.filter(QueryBuilders.termQuery(CometIndexKey.CATEGORY, rentSearch.getCategory()));
}
if (rentSearch.getStartTime() != null || rentSearch.getEndTime() != null) {
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(CometIndexKey.CREATE_TIME);
if (rentSearch.getStartTime() != null) {
rangeQueryBuilder.gte(rentSearch.getStartTime());
}
if (rentSearch.getEndTime() != null) {
rangeQueryBuilder.lte(rentSearch.getEndTime());
}
boolQuery.filter(rangeQueryBuilder);
}
BoolQueryBuilder keyWordBoolQuery=QueryBuilders.boolQuery();
keyWordBoolQuery.should(
QueryBuilders.matchQuery(CometIndexKey.TITLE, rentSearch.getKeywords()).boost(2.0f)
);
keyWordBoolQuery.should(QueryBuilders.multiMatchQuery(rentSearch.getKeywords(),
CometIndexKey.DESCRIPTION,
CometIndexKey.CONTENT,
CometIndexKey.AUTHOR
));
boolQuery.must(keyWordBoolQuery);
sourceBuilder.query(boolQuery);
boolean isHighlight=rentSearch.isHighlight();
if(isHighlight){
HighlightBuilder highlightBuilder = new HighlightBuilder();
HighlightBuilder.Field highlightTitle =
new HighlightBuilder.Field(CometIndexKey.TITLE);
highlightTitle.highlighterType("unified");
highlightBuilder.field(highlightTitle);
sourceBuilder.highlighter(highlightBuilder);
}
sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
sourceBuilder.sort(new FieldSortBuilder(CometIndexKey.CREATE_TIME).order(SortOrder.DESC));
sourceBuilder.from(rentSearch.getStart());
sourceBuilder.size(rentSearch.getSize());
log.info("Builder:{}", sourceBuilder.toString());
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(CometIndexKey.INDEX_NAME);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
RestStatus status = searchResponse.status();
List<CometIndexVO> list = Lists.newArrayList();
if (status == RestStatus.OK) {
TimeValue took = searchResponse.getTook();
log.info("[请求花费的毫秒]:{},({}),{}", took, took.getMillis(), took.getSeconds());
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
long totalRecord=hits.getTotalHits();
log.info("[请求返回总数]:{}",totalRecord);
CometIndexVO cometIndexVO = null;
for (SearchHit hit : searchHits) {
cometIndexVO = new CometIndexVO();
convert(hit,cometIndexVO,isHighlight);
list.add(cometIndexVO);
}
return list;
} else {
log.warn("search status is not Ok");
return list;
}
} catch (IOException e) {
e.printStackTrace();
log.error("search error");
return null;
}
}
private void convert(SearchHit hit,CometIndexVO cometIndexVO,boolean isHighlight){
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
Long cometId = Longs.tryParse(String.valueOf(sourceAsMap.get(CometIndexKey.COMET_ID)));
String title = (String) sourceAsMap.get(CometIndexKey.TITLE);
String category = (String) sourceAsMap.get(CometIndexKey.CATEGORY);
String author = (String) sourceAsMap.get(CometIndexKey.AUTHOR);
String editor = (String) sourceAsMap.get(CometIndexKey.EDITOR);
String description = (String) sourceAsMap.get(CometIndexKey.DESCRIPTION);
String content = (String) sourceAsMap.get(CometIndexKey.CONTENT);
String createTime = (String) sourceAsMap.get(CometIndexKey.CREATE_TIME);
cometIndexVO.setCometId(cometId);
cometIndexVO.setCategory(category);
cometIndexVO.setAuthor(author);
cometIndexVO.setContent(content);
cometIndexVO.setEditor(editor);
cometIndexVO.setCreateTime(createTime);
cometIndexVO.setDescription(description);
cometIndexVO.setTitle(title);
if(isHighlight){
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
if(highlightFields!=null&&highlightFields.size()>0){
HighlightField highlight = highlightFields.get(CometIndexKey.TITLE);
Text[] fragments = highlight.fragments();
String fragmentString = fragments[0].string();
log.info("fragmentString:{}",fragmentString);
cometIndexVO.setTitle(fragmentString);
}
}
}
3-测试
@Test
public void testSuggest(){
List<String> list=searchService.suggest("西");
for(String s:list){
System.out.println(s);
}
}
@Test
public void testQuery(){
RentSearch rentSearch=new RentSearch();
rentSearch.setCategory("article");
rentSearch.setKeywords("西游记");
rentSearch.setStart(0);
rentSearch.setSize(5);
rentSearch.setHighlight(true);
List<CometIndexVO>result= searchService.query(rentSearch);
for(CometIndexVO cometIndexVO:result){
System.out.println(cometIndexVO.toString());
}
}
打开App,阅读手记