1 实现的读写操作
1.1 一般操作
package com. lenovo. qes. portal. modules. knowledge. demo. service. impl;
import com. alibaba. fastjson. JSON;
import com. lenovo. qes. portal. modules. knowledge. demo. document. ProductDocument;
import com. lenovo. qes. portal. modules. knowledge. demo. repository. ProductDocumentRepository;
import com. lenovo. qes. portal. modules. knowledge. demo. service. EsSearchService;
import com. lenovo. qes. portal. modules. knowledge. service. impl. BaseSearchServiceImpl;
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. FieldSortBuilder;
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. ElasticsearchTemplate;
import org. springframework. stereotype. Service;
import javax. annotation. Resource;
import java. util. *;
@Service
public class EsSearchServiceImpl extends BaseSearchServiceImpl < ProductDocument> implements EsSearchService {
private Logger log = LoggerFactory. getLogger ( getClass ( ) ) ;
@Resource
private ElasticsearchTemplate elasticsearchTemplate;
@Resource
private ProductDocumentRepository productDocumentRepository;
@Override
public void save ( ProductDocument . . . productDocuments) {
elasticsearchTemplate. putMapping ( ProductDocument. class ) ;
if ( productDocuments. length > 0 ) {
log. info ( "【保存索引】:{}" , JSON. toJSONString ( productDocumentRepository. saveAll ( Arrays. asList ( productDocuments) ) ) ) ;
}
}
@Override
public List< T> query ( String keyword, Class< T> clazz) {
SearchQuery searchQuery = new NativeSearchQueryBuilder ( )
. withQuery ( new QueryStringQueryBuilder ( keyword) )
. withSort ( SortBuilders. scoreSort ( ) . order ( SortOrder. DESC) )
. withSort ( new FieldSortBuilder ( "createTime" ) . order ( SortOrder. DESC) )
. build ( ) ;
return elasticsearchTemplate. queryForList ( searchQuery, clazz) ;
}
@Override
public List< Map< String, Object> > queryHit ( String keyword, String indexName, String . . . fieldNames) {
QueryBuilder matchQuery = createQueryBuilder ( keyword, fieldNames) ;
HighlightBuilder highlightBuilder = createHighlightBuilder ( fieldNames) ;
SearchResponse response = elasticsearchTemplate
. getClient ( )
. prepareSearch ( indexName)
. setQuery ( matchQuery)
. highlighter ( highlightBuilder)
. setSize ( 10000 )
. get ( ) ;
SearchHits hits = response. getHits ( ) ;
return getHitList ( hits) ;
}
@Override
public Page< Map< String, Object> > queryHitByPage ( int pageNo, int pageSize, String keyword, String indexName, String. . . fieldNames) {
QueryBuilder matchQuery = createQueryBuilder ( keyword, fieldNames) ;
HighlightBuilder highlightBuilder = createHighlightBuilder ( fieldNames) ;
SearchResponse response = elasticsearchTemplate
. getClient ( )
. prepareSearch ( indexName)
. setQuery ( matchQuery)
. highlighter ( highlightBuilder)
. setFrom ( ( pageNo- 1 ) * pageSize)
. setSize ( pageNo * pageSize)
. get ( ) ;
SearchHits hits = response. getHits ( ) ;
Long totalCount = hits. getTotalHits ( ) ;
Page< Map< String, Object> > page = new Page < > ( pageNo, pageSize, totalCount. intValue ( ) ) ;
page. setList ( getHitList ( hits) ) ;
return page;
}
@Override
@Transactional ( rollbackFor = Exception. class )
public void deleteIndex ( String indexName) {
elasticsearchTemplate. deleteIndex ( indexName) ;
}
@Override
@Transactional ( rollbackFor = Exception. class )
public void save ( QesDocumentVo. . . qesDocumentVos) {
elasticsearchTemplate. putMapping ( QesDocumentVo. class ) ;
if ( qesDocumentVos. length > 0 ) {
log. info ( "【保存索引】:{}" , JSON. toJSONString ( qesDocumentRepository. saveAll ( Arrays. asList ( qesDocumentVos) ) ) ) ;
}
}
@Override
@Transactional ( rollbackFor = Exception. class )
public void batchDelete ( List< String> idList) {
if ( CollectionUtils. isEmpty ( idList) ) {
return ;
}
String index = "qes" ;
String type = "_doc" ;
Client client = elasticsearchTemplate. getClient ( ) ;
BulkRequestBuilder bulkRequestBuilder = client. prepareBulk ( ) ;
for ( String docId : idList) {
DeleteRequestBuilder deleteRequestBuilder = client. prepareDelete ( index, type, docId) ;
bulkRequestBuilder. add ( deleteRequestBuilder) ;
}
BulkResponse bulkResponse = bulkRequestBuilder. execute ( ) . actionGet ( ) ;
if ( bulkResponse. hasFailures ( ) ) {
log. error ( bulkResponse. buildFailureMessage ( ) ) ;
}
}
private List< Map< String, Object> > getHitList ( SearchHits hits) {
List< Map< String, Object> > list = new ArrayList < > ( ) ;
Map< String, Object> map;
for ( SearchHit searchHit : hits) {
map = new HashMap < > ( 16 ) ;
map. put ( "source" , searchHit. getSourceAsMap ( ) ) ;
Map< String, Object> hitMap = new HashMap < > ( ) ;
searchHit. getHighlightFields ( ) . forEach ( ( k, v) - > {
StringBuilder hight = new StringBuilder ( ) ;
for ( Text text : v. getFragments ( ) ) {
hight. append ( text. string ( ) ) ;
}
hitMap. put ( v. getName ( ) , hight. toString ( ) ) ;
} ) ;
map. put ( "highlight" , hitMap) ;
list. add ( map) ;
}
return list;
}
}
1.2 其他操作
@Override
public List< QesDocumentVo> getDocumentByIdList ( List< String> docIdList) {
List< QesDocumentVo> qesDocumentVoList = Lists. newArrayList ( ) ;
if ( CollectionUtils. isEmpty ( docIdList) ) {
return qesDocumentVoList;
}
SearchResponse response = initBaseRequestBuilder ( )
. setQuery ( QueryBuilders. termsQuery ( "_id" , docIdList) )
. setFrom ( 0 )
. setSize ( 1000 )
. get ( ) ;
SearchHits hits = response. getHits ( ) ;
if ( hits. getTotalHits ( ) <= 0 ) {
return qesDocumentVoList;
}
return getHitList ( hits) ;
}
private SearchRequestBuilder initBaseRequestBuilder ( ) {
String indexName = "qes" ;
String[ ] includeFields = { "content" , "meta.author" , "meta.modifier" , "file" , "path" } ;
return elasticsearchTemplate. getClient ( ) . prepareSearch ( indexName)
. setFetchSource ( includeFields, null) ;
}
private List< QesDocumentVo> getHitList ( SearchHits hits) {
List< QesDocumentVo> list = Lists. newArrayList ( ) ;
if ( hits == null || hits. getTotalHits ( ) == 0 ) {
return list;
}
for ( SearchHit searchHit : hits) {
list. add ( convertEsDocument2QesDocumentVo ( searchHit) ) ;
}
return list;
}
2 使用的实体类
2.1 文档映射对象
package com. lenovo. qes. portal. modules. knowledge. Vo;
import io. swagger. annotations. ApiModel;
import io. swagger. annotations. ApiModelProperty;
import lombok. Data;
import lombok. experimental. Accessors;
import org. springframework. data. elasticsearch. annotations. Document;
import java. io. Serializable;
@Data
@Accessors ( chain = true )
@ApiModel ( value = "QesDocumentVo" )
@Document ( indexName = "qes" , type = "_doc" )
public class QesDocumentVo implements Serializable {
@ApiModelProperty ( value = "id" )
private String id;
@ApiModelProperty ( value = "文档id" )
private String docId;
@ApiModelProperty ( value = "文档内容" )
private String content;
private KnowledgeDocPropertyVo knowledgeDocPropertyVo;
private DocumentFileVo file;
private DocumentMetaVo meta;
}
2.2 分页对象
package com. lenovo. qes. platform. common. vo;
import com. alibaba. fastjson. annotation. JSONField;
import com. baomidou. mybatisplus. core. metadata. IPage;
import com. fasterxml. jackson. annotation. JsonProperty;
import io. swagger. annotations. ApiModel;
import io. swagger. annotations. ApiModelProperty;
import lombok. Data;
import java. io. Serializable;
import java. util. Collections;
import java. util. List;
@Data
@ApiModel ( "分页" )
public class Paging < T> implements Serializable {
private static final long serialVersionUID = - 1683800405530086022 L;
@ApiModelProperty ( "总行数" )
@JSONField ( name = "total" )
@JsonProperty ( "total" )
private long total = 0 ;
@ApiModelProperty ( "数据列表" )
@JSONField ( name = "records" )
@JsonProperty ( "records" )
private List< T> records = Collections. emptyList ( ) ;
public Paging ( ) {
}
public Paging ( IPage page) {
this . total = page. getTotal ( ) ;
this . records = page. getRecords ( ) ;
}
@Override
public String toString ( ) {
return "Paging{" +
"total=" + total +
", records=" + records +
'}' ;
}
}