You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.1 KiB

package com.example.es.service.impl;
import com.example.es.service.BaseSearchService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* elasticsearch 搜索引擎
*
* @author lyn
* @version 0.1
* @date 2018/12/13 15:33
*/
@Service
public class BaseSearchServiceImpl<T> implements BaseSearchService<T> {
private Logger log = LoggerFactory.getLogger(getClass());
@Resource
private ElasticsearchOperations searchOperations;
@Override
public List<T> query(String keyword, Class<T> clazz) {
Query searchQuery = new NativeSearchQueryBuilder()
.withQuery(new QueryStringQueryBuilder(keyword).field("goodsName"))
.withSort(SortBuilders.scoreSort().order(SortOrder.DESC))
// .withSort(new FieldSortBuilder("createTime").order(SortOrder.DESC))
.build();
SearchHitsIterator<T> stream = searchOperations
.searchForStream(searchQuery, clazz);
List<T> list = new ArrayList<>();
while (stream.hasNext()) {
list.add(stream.next().getContent());
}
stream.close();
return list;
}
}