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 implements BaseSearchService { private Logger log = LoggerFactory.getLogger(getClass()); @Resource private ElasticsearchOperations searchOperations; @Override public List query(String keyword, Class 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 stream = searchOperations .searchForStream(searchQuery, clazz); List list = new ArrayList<>(); while (stream.hasNext()) { list.add(stream.next().getContent()); } stream.close(); return list; } }