Commit 116fff11 by 赵剑炜

增加es搜索,还未调试

parent 635a9086
......@@ -13,6 +13,11 @@
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
......
package com.junmp.jyzb.Repository;
import com.junmp.jyzb.document.ProductDocument;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.stereotype.Component;
public interface ProductDocumentRepository extends ElasticsearchRepository<ProductDocument,String> {
}
package com.junmp.jyzb.controller;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EsSearchController {
}
package com.junmp.jyzb.document;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Mapping;
import java.io.Serializable;
import java.util.Date;
@Document(indexName = "orders")
@Mapping(mappingPath = "productIndex.json") // 解决IK分词不能使用问题
public class ProductDocument implements Serializable {
@Id
private String id;
//@Field(analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String productName;
//@Field(analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String productDesc;
private Date createTime;
private Date updateTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
\ No newline at end of file
package com.junmp.jyzb.document;
import java.util.Date;
public class ProductDocumentBuilder {
private static ProductDocument productDocument;
// create start
public static ProductDocumentBuilder create(){
productDocument = new ProductDocument();
return new ProductDocumentBuilder();
}
public ProductDocumentBuilder addId(String id) {
productDocument.setId(id);
return this;
}
public ProductDocumentBuilder addProductName(String productName) {
productDocument.setProductName(productName);
return this;
}
public ProductDocumentBuilder addProductDesc(String productDesc) {
productDocument.setProductDesc(productDesc);
return this;
}
public ProductDocumentBuilder addCreateTime(Date createTime) {
productDocument.setCreateTime(createTime);
return this;
}
public ProductDocumentBuilder addUpdateTime(Date updateTime) {
productDocument.setUpdateTime(updateTime);
return this;
}
public ProductDocument builder() {
return productDocument;
}
}
package com.junmp.jyzb.service;
import java.util.List;
import java.util.Map;
/**
* @author zhoudong
* @version 0.1
* @date 2018/12/13 15:32
*/
public interface BaseSearchService<T> {
/**
* 搜 索
* @param keyword
* @param clazz
* @return
*/
Object query(String keyword, Class<T> clazz);
/**
* 搜索高亮显示
* @param keyword 关键字
* @param indexName 索引库
* @param fieldNames 搜索的字段
* @return
*/
List<Map<String,Object>> queryHit(String keyword, String indexName, String ... fieldNames);
/**
* 删除索引库
* @param indexName
* @return
*/
void deleteIndex(String indexName);
}
package com.junmp.jyzb.service;
import com.junmp.jyzb.document.ProductDocument;
import java.util.List;
/**
* @author zhoudong
* @version 0.1
* @date 2018/12/13 15:32
*/
public interface EsSearchService extends BaseSearchService<ProductDocument> {
/**
* 保存
* @auther: zhoudong
* @date: 2018/12/13 16:02
*/
void save(ProductDocument... productDocuments);
/**
* 删除
* @param id
*/
void delete(String id);
/**
* 清空索引
*/
void deleteAll();
/**
* 根据ID查询
* @param id
* @return
*/
ProductDocument getById(String id);
/**
* 查询全部
* @return
*/
List<ProductDocument> getAll();
}
package com.junmp.jyzb.service.impl;
import com.junmp.jyzb.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.builder.SearchSourceBuilder;
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.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
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.*;
/**
* elasticsearch 搜索引擎
* @author zhoudong
* @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 ElasticsearchRestTemplate elasticsearchTemplate;
@Override
public Object query(String keyword, Class<T> clazz) {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Object querys= searchSourceBuilder.query(QueryBuilders.termsQuery(keyword, clazz))
.sort(SortBuilders.scoreSort().order(SortOrder.DESC));
return querys;
}
@Override
public List<Map<String, Object>> queryHit(String keyword, String indexName, String... fieldNames) {
return null;
}
/**
* 高亮显示
* @auther: zhoudong
* @date: 2018/12/13 21:22
*/
// @Override
// public List<Map<String,Object>> queryHit(String keyword, String indexName, String ... fieldNames) {
// // 构造查询条件,使用标准分词器.
// QueryBuilder matchQuery = createQueryBuilder(keyword,fieldNames);
//
// // 设置高亮,使用默认的highlighter高亮器
// HighlightBuilder highlightBuilder = createHighlightBuilder(fieldNames);
//
// // 设置查询字段
// SearchResponse response = elasticsearchTemplate.getClient().prepareSearch(indexName)
// .setQuery(matchQuery)
// .highlighter(highlightBuilder)
// .setSize(10000) // 设置一次返回的文档数量,最大值:10000
// .get();
//
// // 返回搜索结果
// SearchHits hits = response.getHits();
//
// return getHitList(hits);
// }
/**
* 构造查询条件
* @auther: zhoudong
* @date: 2018/12/18 10:42
*/
private QueryBuilder createQueryBuilder(String keyword, String... fieldNames){
// 构造查询条件,使用标准分词器.
return QueryBuilders.multiMatchQuery(keyword,fieldNames) // matchQuery(),单字段搜索
.analyzer("ik_max_word")
.operator(Operator.OR);
}
/**
* 构造高亮器
* @auther: zhoudong
* @date: 2018/12/18 10:44
*/
private HighlightBuilder createHighlightBuilder(String... fieldNames){
// 设置高亮,使用默认的highlighter高亮器
HighlightBuilder highlightBuilder = new HighlightBuilder()
// .field("productName")
.preTags("<span style='color:red'>")
.postTags("</span>");
// 设置高亮字段
for (String fieldName: fieldNames) highlightBuilder.field(fieldName);
return highlightBuilder;
}
/**
* 处理高亮结果
* @auther: zhoudong
* @date: 2018/12/18 10:48
*/
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<>();
// 处理源数据
map.put("source",searchHit.getSourceAsMap());
// 处理高亮数据
Map<String,Object> hitMap = new HashMap<>();
searchHit.getHighlightFields().forEach((k,v) -> {
String hight = "";
for(Text text : v.getFragments()) hight += text.string();
hitMap.put(v.getName(),hight);
});
map.put("highlight",hitMap);
list.add(map);
}
return list;
}
@Override
public void deleteIndex(String indexName) {
elasticsearchTemplate.deleteIndex(indexName);
}
}
package com.junmp.jyzb.service.impl;
import com.alibaba.fastjson.JSON;
import com.junmp.jyzb.Repository.ProductDocumentRepository;
import com.junmp.jyzb.document.ProductDocument;
import com.junmp.jyzb.service.EsSearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* elasticsearch 搜索引擎 service实现
* @author zhoudong
* @version 0.1
* @date 2018/12/13 15:33
*/
@Service
public class EsSearchServiceImpl extends BaseSearchServiceImpl<ProductDocument> implements EsSearchService {
private Logger log = LoggerFactory.getLogger(getClass());
@Resource
private ElasticsearchRestTemplate 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 void delete(String id) {
productDocumentRepository.deleteById(id);
}
@Override
public void deleteAll() {
productDocumentRepository.deleteAll();
}
@Override
public ProductDocument getById(String id) {
return productDocumentRepository.findById(id).get();
}
@Override
public List<ProductDocument> getAll() {
List<ProductDocument> list = new ArrayList<>();
productDocumentRepository.findAll().forEach(list::add);
return list;
}
}
{
"properties": {
"createTime": {
"type": "long"
},
"productDesc": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"productName": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"updateTime": {
"type": "long"
}
}
}
\ No newline at end of file
......@@ -7,6 +7,7 @@ import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
......@@ -28,6 +29,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableScheduling
@EnableTransactionManagement
@EnableSwagger2
@EnableElasticsearchRepositories(basePackages = "com.junmp.jyzb.Repository")
@SpringBootApplication(scanBasePackages = {"com.junmp"}, exclude = {FlywayAutoConfiguration.class,
JpDataSourceAutoConfiguration.class})
public class JyzbBootApplication extends SpringBootServletInitializer {
......
......@@ -70,6 +70,10 @@
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论