SpringBoot 2.x 集成ElasticSearch6.x

虾米哥 阅读:780 2021-03-31 16:55:48 评论:0

任务要求:SpringBoot集成ElasticSearch6.x ,并且封装相关功能.

核心pom.xml 文件:

<parent> 
		<groupId>org.springframework.boot</groupId> 
		<artifactId>spring-boot-starter-parent</artifactId> 
		<version>2.1.1.RELEASE</version> 
	</parent> 
 
	<properties> 
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
		<java.version>1.8</java.version> 
		<mybatis-spring-boot-starter.version>1.3.2</mybatis-spring-boot-starter.version> 
		<mysql-connector-java.version>8.0.11</mysql-connector-java.version> 
		<com.alibaba.druid.version>1.1.9</com.alibaba.druid.version> 
		<commons-lang.version>2.6</commons-lang.version> 
		<commons-codec.version>1.10</commons-codec.version> 
		<commons-lang3.version>3.8.1</commons-lang3.version> 
		<commons-net.version>3.6</commons-net.version> 
		<commons-io.version>2.6</commons-io.version> 
		<commons-collections.version>3.2.1</commons-collections.version> 
		<common-fileupload.version>1.3.1</common-fileupload.version> 
		<fastjson.version>1.2.48</fastjson.version> 
		<jasperreports.version>6.10.0</jasperreports.version> 
	</properties> 
 
 
	<dependencies> 
		<!-- SpringWeb模块 --> 
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-starter-web</artifactId> 
			<!-- 移除springboot 自带日志框架log-back  --> 
			 <exclusions> 
                <exclusion> 
                    <groupId>org.springframework.boot</groupId> 
                    <artifactId>spring-boot-starter-logging</artifactId> 
                </exclusion> 
            </exclusions> 
		</dependency> 
 
		<!--springboot 集成测试框架 --> 
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-starter-test</artifactId> 
			<scope>test</scope> 
		</dependency> 
 
 
		<!--lombok插件 --> 
		<dependency> 
			<groupId>org.projectlombok</groupId> 
			<artifactId>lombok</artifactId> 
			<version>${lombok.version}</version> 
			<scope>provided</scope> 
		</dependency> 
 
 
		<!-- mysql 连接 --> 
		<dependency> 
			<groupId>org.mybatis.spring.boot</groupId> 
			<artifactId>mybatis-spring-boot-starter</artifactId> 
			<version>${mybatis-spring-boot-starter.version}</version> 
		</dependency> 
		<dependency> 
			<groupId>mysql</groupId> 
			<artifactId>mysql-connector-java</artifactId> 
			<version>${mysql-connector-java.version}</version> 
			<scope>runtime</scope> 
		</dependency> 
		<dependency> 
			<groupId>com.alibaba</groupId> 
			<artifactId>druid-spring-boot-starter</artifactId> 
			<version>${com.alibaba.druid.version}</version> 
		</dependency> 
		<!-- 分页控件 --> 
		<dependency> 
			<groupId>com.github.pagehelper</groupId> 
			<artifactId>pagehelper</artifactId> 
			<version>4.1.6</version> 
		</dependency> 
 
		<!--common-lang 常用工具包 --> 
		<dependency> 
			<groupId>commons-lang</groupId> 
			<artifactId>commons-lang</artifactId> 
			<version>${commons-lang.version}</version> 
		</dependency> 
		<!--commons-lang3 工具包 --> 
		<dependency> 
			<groupId>org.apache.commons</groupId> 
			<artifactId>commons-lang3</artifactId> 
			<version>${commons-lang3.version}</version> 
		</dependency> 
 
		<!--commons-codec 加密工具包 --> 
		<dependency> 
			<groupId>commons-codec</groupId> 
			<artifactId>commons-codec</artifactId> 
			<version>${commons-codec.version}</version> 
		</dependency> 
		<!--commons-net 网络工具包 --> 
		<dependency> 
			<groupId>commons-net</groupId> 
			<artifactId>commons-net</artifactId> 
			<version>${commons-net.version}</version> 
		</dependency> 
		<!--common-io 工具包 --> 
		<dependency> 
			<groupId>commons-io</groupId> 
			<artifactId>commons-io</artifactId> 
			<version>${commons-io.version}</version> 
		</dependency> 
		<!--common-collection 工具包 --> 
		<dependency> 
			<groupId>commons-collections</groupId> 
			<artifactId>commons-collections</artifactId> 
			<version>${commons-collections.version}</version> 
		</dependency> 
		<!--common-fileupload 工具包 --> 
		<dependency> 
			<groupId>commons-fileupload</groupId> 
			<artifactId>commons-fileupload</artifactId> 
			<version>${common-fileupload.version}</version> 
		</dependency> 
 
		<!-- Swagger2 --> 
		<dependency> 
			<groupId>io.springfox</groupId> 
			<artifactId>springfox-swagger2</artifactId> 
			<version>2.7.0</version> 
		</dependency> 
		<dependency> 
			<groupId>io.springfox</groupId> 
			<artifactId>springfox-swagger-ui</artifactId> 
			<version>2.7.0</version> 
		</dependency> 
 
		<!-- fastjson --> 
		<dependency> 
			<groupId>com.alibaba</groupId> 
			<artifactId>fastjson</artifactId> 
			<version>${fastjson.version}</version> 
		</dependency> 
 
        <!-- 集成elasticsearch 框架 --> 
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId> 
		</dependency>

配置类:

package com.zzg.search.config; 
 
import java.util.HashMap; 
import java.util.Map; 
 
import org.springframework.boot.web.servlet.FilterRegistrationBean; 
import org.springframework.boot.web.servlet.ServletRegistrationBean; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
 
import com.alibaba.druid.support.http.StatViewServlet; 
import com.alibaba.druid.support.http.WebStatFilter; 
/** 
 * druid 监控配置 
 * @author zzg 
 * 
 */ 
@Configuration 
public class DruidConfig { 
	 	@Bean 
	    public ServletRegistrationBean druidServletRegistrationBean() { 
	        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(); 
	        servletRegistrationBean.setServlet(new StatViewServlet()); 
	        servletRegistrationBean.addUrlMappings("/druid/*"); 
	        servletRegistrationBean.addInitParameter("allow", ""); 
	        servletRegistrationBean.addInitParameter("deny", ""); 
	        servletRegistrationBean.addInitParameter("loginUsername", "admin"); 
	        servletRegistrationBean.addInitParameter("loginPassword", "admin"); 
	        return servletRegistrationBean; 
	    } 
 
	    /** 
	     * 注册DruidFilter拦截 
	     * 
	     * @return 
	     */ 
	    @Bean 
	    public FilterRegistrationBean duridFilterRegistrationBean() { 
	        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 
	        filterRegistrationBean.setFilter(new WebStatFilter()); 
	        Map<String, String> initParams = new HashMap<String, String>(); 
	        //设置忽略请求 
	        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); 
	        filterRegistrationBean.setInitParameters(initParams); 
	        filterRegistrationBean.addUrlPatterns("/*"); 
	        return filterRegistrationBean; 
	    } 
} 
package com.zzg.search.config; 
 
import java.util.Properties; 
 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
 
import com.github.pagehelper.PageHelper; 
 
/** 
 * mybatis 配置对象 
 * @author zzg 
 * 
 */ 
@Configuration 
public class MyBatisConfig { 
	/** 
	 * 分页对象实列化 
	 * @return 
	 */ 
	@Bean 
	public PageHelper pageHelper() { 
		PageHelper pageHelper = new PageHelper(); 
		Properties p = new Properties(); 
		p.setProperty("offsetAsPageNum", "true"); 
		p.setProperty("rowBoundsWithCount", "true"); 
		p.setProperty("reasonable", "true"); 
		p.setProperty("dialect", "mysql"); 
		pageHelper.setProperties(p); 
		return pageHelper; 
	} 
}
package com.zzg.search.config; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
 
import io.swagger.annotations.ApiOperation; 
import springfox.documentation.builders.ApiInfoBuilder; 
import springfox.documentation.builders.ParameterBuilder; 
import springfox.documentation.builders.PathSelectors; 
import springfox.documentation.builders.RequestHandlerSelectors; 
import springfox.documentation.schema.ModelRef; 
import springfox.documentation.service.ApiInfo; 
import springfox.documentation.service.Contact; 
import springfox.documentation.service.Parameter; 
import springfox.documentation.spi.DocumentationType; 
import springfox.documentation.spring.web.plugins.Docket; 
import springfox.documentation.swagger2.annotations.EnableSwagger2; 
 
@Configuration 
@EnableSwagger2 
public class SwaggerConfig { 
	@Bean 
	public Docket buildDocket() { 
 
		ParameterBuilder tokenPar = new ParameterBuilder(); 
		List<Parameter> pars = new ArrayList<Parameter>(); 
		tokenPar.name("X-CSRF-TOKEN").description("令牌").modelRef(new ModelRef("string")).parameterType("header") 
				.required(false).build(); 
		pars.add(tokenPar.build()); 
 
		return new Docket(DocumentationType.SWAGGER_2).select() 
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any()) 
				.build().globalOperationParameters(pars).apiInfo(buildApiInf()); 
	} 
 
	private ApiInfo buildApiInf() { 
		return new ApiInfoBuilder().title("****").termsOfServiceUrl("http://www.baidu.cn/") 
				.description("API接口") 
				.contact(new Contact("baidu", "http://www.baidu.cn/", "zhouzhiwengang@163.com")) 
				.version("2.0").build(); 
 
	} 
} 

elasticsearch6.x 检索组件封装:

package com.zzg.search.component; 
 
import java.net.InetAddress; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 
 
import org.apache.commons.collections.map.HashedMap; 
import org.apache.commons.lang.StringUtils; 
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; 
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; 
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; 
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; 
import org.elasticsearch.action.bulk.BulkRequestBuilder; 
import org.elasticsearch.action.bulk.BulkResponse; 
import org.elasticsearch.action.delete.DeleteResponse; 
import org.elasticsearch.action.index.IndexResponse; 
import org.elasticsearch.action.search.SearchRequestBuilder; 
import org.elasticsearch.action.search.SearchResponse; 
import org.elasticsearch.action.update.UpdateRequest; 
import org.elasticsearch.client.transport.TransportClient; 
import org.elasticsearch.common.settings.Settings; 
import org.elasticsearch.common.transport.TransportAddress; 
import org.elasticsearch.index.query.QueryBuilders; 
import org.elasticsearch.search.SearchHit; 
import org.elasticsearch.search.SearchHits; 
import org.elasticsearch.search.aggregations.AggregationBuilder; 
import org.elasticsearch.search.aggregations.AggregationBuilders; 
import org.elasticsearch.search.aggregations.bucket.terms.Terms; 
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 
import org.elasticsearch.search.sort.SortOrder; 
import org.elasticsearch.transport.client.PreBuiltTransportClient; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import com.zzg.search.component.builder.impl.ESQueryProduce; 
import com.zzg.search.component.exception.ESFailedException; 
import com.zzg.search.component.exception.ESIndexException; 
 
/** 
 * ES 工具类 
 * @author zzg 
 * 
 */ 
public class ESService { 
	//日志记录 
	private Logger logger = LoggerFactory.getLogger(ESService.class); 
	 
	private final static int MAX = 10000; 
 
    TransportClient client; 
     
    public ESService(String clusterName, String ip, int port){ 
    	try { 
            Settings settings = Settings.builder() 
                    .put("cluster.name", clusterName).build(); 
 
            this.client = new PreBuiltTransportClient(settings) 
                    .addTransportAddress(new TransportAddress(InetAddress.getByName(ip), port)); 
        } catch (UnknownHostException e) { 
        	logger.error(e.getMessage()); 
            throw new ESFailedException("es init failed!", e); 
        } 
    } 
     
    /** 
     * 功能描述:新建索引 
     * @param indexName 索引名 
     */ 
    public void createIndex(String indexName) { 
        client.admin().indices().create(new CreateIndexRequest(indexName)) 
                .actionGet(); 
    } 
 
    /** 
     * 功能描述:新建索引 
     * @param index 索引名 
     * @param type 类型 
     */ 
    public void createIndex(String index, String type) { 
        client.prepareIndex(index, type).setSource().get(); 
    } 
 
    /** 
     * 功能描述:删除索引 
     * @param index 索引名 
     */ 
    public void deleteIndex(String index) { 
        if (indexExist(index)) { 
            DeleteIndexResponse dResponse = client.admin().indices().prepareDelete(index) 
                    .execute().actionGet(); 
            if (!dResponse.isAcknowledged()) { 
                throw new ESIndexException("failed to delete index."); 
            } 
        } else { 
            throw new ESIndexException("index name not exists"); 
        } 
    } 
 
    /** 
     * 功能描述:验证索引是否存在 
     * @param index 索引名 
     */ 
    public boolean indexExist(String index) { 
        IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(index); 
        IndicesExistsResponse inExistsResponse = client.admin().indices() 
                .exists(inExistsRequest).actionGet(); 
        return inExistsResponse.isExists(); 
    } 
 
    /** 
     * 功能描述:插入数据 
     * @param index 索引名 
     * @param type 类型 
     * @param json 数据 
     */ 
    public void insertData(String index, String type, String json) { 
        IndexResponse response = client.prepareIndex(index, type) 
                .setSource(json) 
                .get(); 
    } 
 
    /** 
     * 功能描述:插入数据 
     * @param index 索引名 
     * @param type 类型 
     * @param _id 数据id 
     * @param json 数据 
     */ 
    public void insertData(String index, String type, String _id, String json) { 
        IndexResponse response = client.prepareIndex(index, type).setId(_id) 
                .setSource(json) 
                .get(); 
    } 
 
    /** 
     * 功能描述:更新数据 
     * @param index 索引名 
     * @param type 类型 
     * @param _id 数据id 
     * @param json 数据 
     */ 
    public void updateData(String index, String type, String _id, String json) throws Exception { 
        try { 
            UpdateRequest updateRequest = new UpdateRequest(index, type, _id) 
                    .doc(json); 
            client.update(updateRequest).get(); 
        } catch (Exception e) { 
        	logger.error(e.getMessage()); 
            throw new ESIndexException("update data failed.", e); 
        } 
    } 
 
    /** 
     * 功能描述:删除数据 
     * @param index 索引名 
     * @param type 类型 
     * @param _id 数据id 
     */ 
    public void deleteData(String index, String type, String _id) { 
        DeleteResponse response = client.prepareDelete(index, type, _id) 
                .get(); 
    } 
 
    /** 
     * 功能描述:批量插入数据 
     * @param index 索引名 
     * @param type 类型 
     * @param data (_id 主键, json 数据) 
     */ 
    public void bulkInsertData(String index, String type, Map<String, String> data) { 
        BulkRequestBuilder bulkRequest = client.prepareBulk(); 
        data.forEach((param1, param2) -> { 
            bulkRequest.add(client.prepareIndex(index, type, param1) 
                    .setSource(param2) 
            ); 
        }); 
        BulkResponse bulkResponse = bulkRequest.get(); 
    } 
 
    /** 
     * 功能描述:批量插入数据 
     * @param index 索引名 
     * @param type 类型 
     * @param jsonList 批量数据 
     */ 
    public void bulkInsertData(String index, String type, List<String> jsonList) { 
        BulkRequestBuilder bulkRequest = client.prepareBulk(); 
        jsonList.forEach(item -> { 
            bulkRequest.add(client.prepareIndex(index, type) 
                    .setSource(item) 
            ); 
        }); 
        BulkResponse bulkResponse = bulkRequest.get(); 
    } 
     
    /** 
     * 功能描述:查询 
     * @param index 索引名 
     * @param type 类型 
     * @param constructor 查询构造 
     */ 
    public List<Map<String, Object>> search(String index, String type, ESQueryProduce constructor) { 
        List<Map<String, Object>> result = new ArrayList<>(); 
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index).setTypes(type); 
        //排序 
        if (StringUtils.isNotEmpty(constructor.getAsc())) 
            searchRequestBuilder.addSort(constructor.getAsc(), SortOrder.ASC); 
        if (StringUtils.isNotEmpty(constructor.getDesc())) 
            searchRequestBuilder.addSort(constructor.getDesc(), SortOrder.DESC); 
        //设置查询体 
        searchRequestBuilder.setQuery(constructor.getBoolQueryBuilder()); 
        //返回条目数 
        int size = constructor.getSize(); 
        if (size < 0) { 
            size = 0; 
        } 
        if (size > MAX) { 
            size = MAX; 
        } 
        //返回条目数 
        searchRequestBuilder.setSize(size); 
 
        searchRequestBuilder.setFrom(constructor.getFrom() < 0 ? 0 : constructor.getFrom()); 
 
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet(); 
 
        SearchHits hits = searchResponse.getHits(); 
        SearchHit[] searchHists = hits.getHits(); 
        for (SearchHit sh : searchHists) { 
            result.add(sh.getSourceAsMap()); 
        } 
        return result; 
    } 
     
    /** 
     * 功能描述:统计查询 
     * @param index 索引名 
     * @param type 类型 
     * @param constructor 查询构造 
     * @param groupBy 统计字段 
     */ 
    public Map<Object, Object> statSearch(String index, String type, ESQueryProduce constructor, String groupBy) { 
        Map<Object, Object> map = new HashedMap(); 
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index).setTypes(type); 
        //排序 
        if (StringUtils.isNotEmpty(constructor.getAsc())) 
            searchRequestBuilder.addSort(constructor.getAsc(), SortOrder.ASC); 
        if (StringUtils.isNotEmpty(constructor.getDesc())) 
            searchRequestBuilder.addSort(constructor.getDesc(), SortOrder.DESC); 
        //设置查询体 
        if (null != constructor) { 
            searchRequestBuilder.setQuery(constructor.getBoolQueryBuilder()); 
        } else { 
            searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); 
        } 
        int size = constructor.getSize(); 
        if (size < 0) { 
            size = 0; 
        } 
        if (size > MAX) { 
            size = MAX; 
        } 
        //返回条目数 
        searchRequestBuilder.setSize(size); 
 
        searchRequestBuilder.setFrom(constructor.getFrom() < 0 ? 0 : constructor.getFrom()); 
        SearchResponse sr = searchRequestBuilder.addAggregation( 
                AggregationBuilders.terms("agg").field(groupBy) 
        ).get(); 
 
        Terms stateAgg = sr.getAggregations().get("agg"); 
        Iterator<Terms.Bucket> iter = (Iterator<Bucket>) stateAgg.getBuckets().iterator(); 
 
        while (iter.hasNext()) { 
            Terms.Bucket gradeBucket = iter.next(); 
            map.put(gradeBucket.getKey(), gradeBucket.getDocCount()); 
        } 
 
        return map; 
    } 
 
    /** 
     * 功能描述:统计查询 
     * @param index 索引名 
     * @param type 类型 
     * @param constructor 查询构造 
     * @param agg 自定义计算 
     */ 
    public Map<Object, Object> statSearch(String index, String type, ESQueryProduce constructor, AggregationBuilder agg) { 
        if (agg == null) { 
            return null; 
        } 
        Map<Object, Object> map = new HashedMap(); 
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index).setTypes(type); 
        //排序 
        if (StringUtils.isNotEmpty(constructor.getAsc())) 
            searchRequestBuilder.addSort(constructor.getAsc(), SortOrder.ASC); 
        if (StringUtils.isNotEmpty(constructor.getDesc())) 
            searchRequestBuilder.addSort(constructor.getDesc(), SortOrder.DESC); 
        //设置查询体 
        if (null != constructor) { 
            searchRequestBuilder.setQuery(constructor.getBoolQueryBuilder()); 
        } else { 
            searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); 
        } 
        int size = constructor.getSize(); 
        if (size < 0) { 
            size = 0; 
        } 
        if (size > MAX) { 
            size = MAX; 
        } 
        //返回条目数 
        searchRequestBuilder.setSize(size); 
 
        searchRequestBuilder.setFrom(constructor.getFrom() < 0 ? 0 : constructor.getFrom()); 
        SearchResponse sr = searchRequestBuilder.addAggregation( 
                agg 
        ).get(); 
 
        Terms stateAgg = sr.getAggregations().get("agg"); 
        Iterator<Terms.Bucket> iter = (Iterator<Bucket>) stateAgg.getBuckets().iterator(); 
 
        while (iter.hasNext()) { 
            Terms.Bucket gradeBucket = iter.next(); 
            map.put(gradeBucket.getKey(), gradeBucket.getDocCount()); 
        } 
 
        return map; 
    } 
 
 
    /** 
     * 功能描述:关闭链接 
     */ 
    public void close() { 
        client.close(); 
    } 
 
 
} 
package com.zzg.search.component.builder; 
 
import org.elasticsearch.index.query.BoolQueryBuilder; 
 
/** 
 * es 查询构建工具类 
 *  
 * @author zzg 
 * 
 */ 
public interface IESQueryBuilders { 
	/** 
	 * term 查询 
	 * @param name 
	 * @param valve 
	 * @return 
	 * @throws Exception 
	 */ 
	IESQueryBuilders termQuery(String name, String... values) throws Exception; 
 
	/** 
	 * wildcard 查询 
	 * @param name 
	 * @param values 
	 * @return 
	 * @throws Exception 
	 */ 
	IESQueryBuilders wildcardQuery(String name, String... values) throws Exception; 
 
	/** 
	 * rang 查询 
	 * @param name 
	 * @param from 
	 * @param to 
	 * @return 
	 * @throws Exception 
	 */ 
	IESQueryBuilders rangeQuery(String name, String from, String to) throws Exception; 
 
	/** 
	 * bool 查询 
	 * @return 
	 */ 
	BoolQueryBuilder getBoolQueryBuilder(); 
 
} 
package com.zzg.search.component.builder; 
 
import org.elasticsearch.index.query.BoolQueryBuilder; 
 
/** 
 * es 查询 生成类 
 * @author zzg 
 * 
 */ 
public interface IESQueryProduce { 
	 
	 
 
	/** 
	 * bool 查询 
	 * @return 
	 */ 
	BoolQueryBuilder getBoolQueryBuilder(); 
	 
	/** 
	 * es 生成核心方法 
	 * @param esQueryBuilders 
	 * @return 
	 */ 
	IESQueryProduce getProduct(IESQueryBuilders esQueryBuilders); 
	 
} 
package com.zzg.search.component.builder.factory; 
 
import com.zzg.search.component.builder.IESQueryBuilders; 
import com.zzg.search.component.builder.model.ESQueryMode; 
 
public class ESQueryBuilderFactory { 
	public static IESQueryBuilders creatESQueryBuilder(ESQueryMode mode) 
			throws ClassNotFoundException, IllegalAccessException, InstantiationException { 
		Class<?> clazz = Class.forName(mode.mode()); 
		return (IESQueryBuilders) clazz.newInstance(); 
	} 
 
} 
package com.zzg.search.component.builder.impl; 
 
import org.elasticsearch.index.query.BoolQueryBuilder; 
import org.elasticsearch.index.query.QueryBuilders; 
import com.zzg.search.component.builder.IESQueryBuilders; 
 
public class ESFilter implements IESQueryBuilders { 
	private BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); 
 
	@Override 
	public IESQueryBuilders termQuery(String name, String... values) throws Exception { 
		// TODO Auto-generated method stub 
		boolQueryBuilder.filter(QueryBuilders.termsQuery(name, values)); 
		return this; 
 
	} 
 
	@Override 
	public IESQueryBuilders wildcardQuery(String name, String... values) throws Exception { 
		// TODO Auto-generated method stub 
		 for (String value : values){ 
	            boolQueryBuilder.filter(QueryBuilders.wildcardQuery(name, "*" + value + "*")); 
	        } 
	     return this; 
	} 
 
	@Override 
	public IESQueryBuilders rangeQuery(String name, String from, String to) throws Exception { 
		// TODO Auto-generated method stub 
		return null; 
	} 
 
	@Override 
	public BoolQueryBuilder getBoolQueryBuilder() { 
		// TODO Auto-generated method stub 
		return boolQueryBuilder; 
	} 
 
} 
package com.zzg.search.component.builder.impl; 
 
import org.elasticsearch.index.query.BoolQueryBuilder; 
import org.elasticsearch.index.query.QueryBuilders; 
 
import com.zzg.search.component.builder.IESQueryBuilders; 
 
 
public class ESMust implements IESQueryBuilders { 
 
	private BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); 
 
	@Override 
	public IESQueryBuilders termQuery(String name, String... values) throws Exception { 
		// TODO Auto-generated method stub 
		boolQueryBuilder.must(QueryBuilders.termsQuery(name, values)); 
		return this; 
	} 
 
	@Override 
	public IESQueryBuilders wildcardQuery(String name, String... values) throws Exception { 
		// TODO Auto-generated method stub 
		for (String value : values){ 
            boolQueryBuilder.must(QueryBuilders.wildcardQuery(name, "*" + value + "*")); 
        } 
        return this; 
	} 
 
	@Override 
	public IESQueryBuilders rangeQuery(String name, String from, String to) throws Exception { 
		// TODO Auto-generated method stub 
		 boolQueryBuilder.must(QueryBuilders.rangeQuery(name).from(from, true).to(to, true)); 
	        return this; 
	} 
 
	@Override 
	public BoolQueryBuilder getBoolQueryBuilder() { 
		// TODO Auto-generated method stub 
		return boolQueryBuilder; 
	} 
 
} 
package com.zzg.search.component.builder.impl; 
 
import org.elasticsearch.index.query.BoolQueryBuilder; 
import org.elasticsearch.index.query.QueryBuilders; 
 
import com.zzg.search.component.builder.IESQueryBuilders; 
 
public class ESMustNot implements IESQueryBuilders { 
	private BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); 
	 
	@Override 
	public IESQueryBuilders termQuery(String name, String... values) throws Exception { 
		// TODO Auto-generated method stub 
		boolQueryBuilder.mustNot(QueryBuilders.termQuery(name, values)); 
		return this; 
	} 
 
	@Override 
	public IESQueryBuilders wildcardQuery(String name, String... values) throws Exception { 
		// TODO Auto-generated method stub 
		for (String value : values){ 
            boolQueryBuilder.mustNot(QueryBuilders.wildcardQuery(name, "*" + value + "*")); 
        } 
        return this; 
 
	} 
 
	@Override 
	public IESQueryBuilders rangeQuery(String name, String from, String to) throws Exception { 
		// TODO Auto-generated method stub 
		return null; 
	} 
 
	@Override 
	public BoolQueryBuilder getBoolQueryBuilder() { 
		// TODO Auto-generated method stub 
		return boolQueryBuilder; 
	} 
 
} 
package com.zzg.search.component.builder.impl; 
 
import org.elasticsearch.index.query.BoolQueryBuilder; 
import com.zzg.search.component.builder.IESQueryBuilders; 
import com.zzg.search.component.builder.IESQueryProduce; 
 
public class ESQueryProduce implements IESQueryProduce{ 
	 
	private BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); 
	 
	private int size = Integer.MAX_VALUE; 
	 
	private String asc; 
 
	private String desc; 
	 
	private int from = 0; 
	 
	@Override 
	public BoolQueryBuilder getBoolQueryBuilder() { 
		// TODO Auto-generated method stub 
		return boolQueryBuilder; 
	} 
 
	@Override 
	public IESQueryProduce getProduct(IESQueryBuilders esQueryBuilders) { 
		// TODO Auto-generated method stub 
		boolQueryBuilder.must(esQueryBuilders.getBoolQueryBuilder()); 
		return this; 
	} 
 
	public String getAsc() { 
		return asc; 
	} 
 
	public void setAsc(String asc) { 
		this.asc = asc; 
	} 
 
	public String getDesc() { 
		return desc; 
	} 
 
	public void setDesc(String desc) { 
		this.desc = desc; 
	} 
	 
	public int getSize() { 
		return size; 
	} 
 
	public void setSize(int size) { 
		this.size = size; 
	} 
	 
	public int getFrom() { 
		return from; 
	} 
 
	public void setFrom(int from) { 
		this.from = from; 
	} 
} 
package com.zzg.search.component.builder.impl; 
 
import org.elasticsearch.index.query.BoolQueryBuilder; 
import org.elasticsearch.index.query.QueryBuilders; 
 
import com.zzg.search.component.builder.IESQueryBuilders; 
 
public class ESShould implements IESQueryBuilders { 
	private BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); 
 
	@Override 
	public IESQueryBuilders termQuery(String name, String... values) throws Exception { 
		// TODO Auto-generated method stub 
		boolQueryBuilder.should(QueryBuilders.termsQuery(name, values)); 
		return this; 
	} 
 
	@Override 
	public IESQueryBuilders wildcardQuery(String name, String... values) throws Exception { 
		// TODO Auto-generated method stub 
		 for (String value : values){ 
	            boolQueryBuilder.should(QueryBuilders.wildcardQuery(name, "*" + value + "*")); 
	        } 
	        return this; 
	} 
 
	@Override 
	public IESQueryBuilders rangeQuery(String name, String from, String to) throws Exception { 
		// TODO Auto-generated method stub 
		return null; 
	} 
 
	@Override 
	public BoolQueryBuilder getBoolQueryBuilder() { 
		// TODO Auto-generated method stub 
		return boolQueryBuilder; 
	} 
 
} 
package com.zzg.search.component.builder.model; 
 
import java.io.Serializable; 
 
public enum ESQueryMode implements Serializable { 
	MUST("com.zzg.search.component.builder.impl.ESMust"), MUST_NOT("com.zzg.search.component.builder.impl.ESMustNot"), SHOULD( 
			"com.zzg.search.component.builder.impl.ESShould"), FILTER("com.zzg.search.component.builder.impl.ESFilter"); 
 
	private String mode; 
 
	ESQueryMode(String mode) { 
		this.mode = mode; 
	} 
 
	public String mode() { 
		return mode; 
	} 
 
} 
package com.zzg.search.component.exception; 
 
import org.apache.commons.lang3.StringUtils; 
 
@SuppressWarnings("serial") 
public class ESFailedException extends RuntimeException  { 
	 /** The code. */ 
    private String code; 
 
    /** The params. */ 
    private String[] params; 
 
    /** 
     * Gets the code. 
     *  
     * @return the code 
     */ 
    public String getCode() { 
        return code; 
    } 
 
    /** 
     * Sets the code. 
     *  
     * @param code 
     *            the new code 
     */ 
    public void setCode(String code) { 
        this.code = code; 
    } 
 
    /** 
     * Gets the params. 
     *  
     * @return the params 
     */ 
    public String[] getParams() { 
        return params; 
    } 
 
    /** 
     * Sets the params. 
     *  
     * @param params 
     *            the new params 
     */ 
    public void setParams(String[] params) { 
        this.params = params; 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     */ 
    public ESFailedException() { 
        super(); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param message 
     *            the message 
     * @param e 
     *            the e 
     */ 
    public ESFailedException(String message, Exception e) { 
        super(message, e); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param message 
     *            the message 
     */ 
    public ESFailedException(String message) { 
        super(message); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param e 
     *            the e 
     */ 
    public ESFailedException(Exception e) { 
        super(e); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param code 
     *            the code 
     * @param params 
     *            the params 
     */ 
    public ESFailedException(String code, String[] params) { 
        super(code); 
        this.setCode(code); 
        this.setParams(params); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param code 
     *            the code 
     * @param params 
     *            the params 
     * @param e 
     *            the e 
     */ 
    public ESFailedException(String code, String[] params, Exception e) { 
        super(e); 
        this.setCode(code); 
        this.setParams(params); 
    } 
 
    /* 
     * (non-Javadoc) 
     *  
     * @see java.lang.Throwable#getMessage() 
     */ 
    @Override 
    public String getMessage() { 
        if (code == null || code.length() == 0) { 
            return super.getMessage(); 
        } 
        String paramsStr = "NA"; 
        if (params != null) { 
            paramsStr = StringUtils.join(params, ","); 
        } 
        String codeMessage = "code:" + code + ";parameters:" + paramsStr; 
        return codeMessage; 
    } 
 
    /* 
     * (non-Javadoc) 
     *  
     * @see java.lang.Throwable#toString() 
     */ 
    @Override 
    public String toString() { 
        String s = getClass().getName(); 
        String message = this.getMessage(); 
        return (message != null) ? (s + ": " + message) : s; 
    } 
} 
package com.zzg.search.component.exception; 
 
import org.apache.commons.lang3.StringUtils; 
 
@SuppressWarnings("serial") 
public class ESIndexException extends RuntimeException { 
	 /** The code. */ 
    private String code; 
 
    /** The params. */ 
    private String[] params; 
 
    /** 
     * Gets the code. 
     *  
     * @return the code 
     */ 
    public String getCode() { 
        return code; 
    } 
 
    /** 
     * Sets the code. 
     *  
     * @param code 
     *            the new code 
     */ 
    public void setCode(String code) { 
        this.code = code; 
    } 
 
    /** 
     * Gets the params. 
     *  
     * @return the params 
     */ 
    public String[] getParams() { 
        return params; 
    } 
 
    /** 
     * Sets the params. 
     *  
     * @param params 
     *            the new params 
     */ 
    public void setParams(String[] params) { 
        this.params = params; 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     */ 
    public ESIndexException() { 
        super(); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param message 
     *            the message 
     * @param e 
     *            the e 
     */ 
    public ESIndexException(String message, Exception e) { 
        super(message, e); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param message 
     *            the message 
     */ 
    public ESIndexException(String message) { 
        super(message); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param e 
     *            the e 
     */ 
    public ESIndexException(Exception e) { 
        super(e); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param code 
     *            the code 
     * @param params 
     *            the params 
     */ 
    public ESIndexException(String code, String[] params) { 
        super(code); 
        this.setCode(code); 
        this.setParams(params); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param code 
     *            the code 
     * @param params 
     *            the params 
     * @param e 
     *            the e 
     */ 
    public ESIndexException(String code, String[] params, Exception e) { 
        super(e); 
        this.setCode(code); 
        this.setParams(params); 
    } 
 
    /* 
     * (non-Javadoc) 
     *  
     * @see java.lang.Throwable#getMessage() 
     */ 
    @Override 
    public String getMessage() { 
        if (code == null || code.length() == 0) { 
            return super.getMessage(); 
        } 
        String paramsStr = "NA"; 
        if (params != null) { 
            paramsStr = StringUtils.join(params, ","); 
        } 
        String codeMessage = "code:" + code + ";parameters:" + paramsStr; 
        return codeMessage; 
    } 
 
    /* 
     * (non-Javadoc) 
     *  
     * @see java.lang.Throwable#toString() 
     */ 
    @Override 
    public String toString() { 
        String s = getClass().getName(); 
        String message = this.getMessage(); 
        return (message != null) ? (s + ": " + message) : s; 
    } 
} 

业务逻辑模块domain、mapper、service 和serviceImpl 相关代码省略。

elasticsearch6.x controller 代码:

package com.zzg.search.controller; 
 
import java.util.List; 
import java.util.Map; 
 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 
 
import com.zzg.jreport.response.JreportResponse; 
import com.zzg.search.component.ESService; 
import com.zzg.search.component.builder.IESQueryBuilders; 
import com.zzg.search.component.builder.factory.ESQueryBuilderFactory; 
import com.zzg.search.component.builder.impl.ESQueryProduce; 
import com.zzg.search.component.builder.model.ESQueryMode; 
 
import io.swagger.annotations.Api; 
import io.swagger.annotations.ApiOperation; 
 
@Controller 
@RequestMapping("/api/es") 
@Api(value = "搜索引擎Controlle", tags = "搜索引擎操作服务") 
public class ESController { 
	 
	@ApiOperation(httpMethod = "POST", value = "ES检索") 
	@RequestMapping(value = "/search", method = { RequestMethod.POST }, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	public JreportResponse search() { 
		ESService util = new ESService("my-application","192.168.1.74", 9300); 
		 
		// 验证索引文件是否存在 
		boolean target = util.indexExist("username"); 
		if(target){ 
			System.out.println("指定索引是否存在:" + target); 
			util.deleteIndex("username"); 
			System.out.println("指定索引删除成功"); 
		} 
		return JreportResponse.ok(null); 
	} 
	 
	@ApiOperation(httpMethod = "POST", value = "ES检索") 
	@RequestMapping(value = "/find", method = { RequestMethod.POST }, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	public JreportResponse find() { 
		ESService util = new ESService("my-application","192.168.1.74", 9300); 
		 
		ESQueryProduce produce = new ESQueryProduce(); 
		// 构建查询条件 
		IESQueryBuilders must = null; 
		try { 
			must = ESQueryBuilderFactory.creatESQueryBuilder(ESQueryMode.MUST); 
			must.termQuery("author", "somebody"); 
			must.rangeQuery("postdate", "2015-01-01", "2019-01-01"); 
		} catch (Exception e) { 
			// TODO Auto-generated catch block 
			e.printStackTrace(); 
		}  
		produce.getProduct(must); 
		 
	    List<Map<String,Object>> list = util.search("website", "blog", produce); 
		 
		return JreportResponse.ok(list); 
	} 
 
} 

application.properties 文件和log4j 文件

# æå®æå¡ç«¯å£ 
server.port=7090 
# æå®æå¡ å称 
# server.context-path=/jreport 
#mybatis xml æ件éç½® 
mybatis.mapper-locations=classpath*:mapper/search/*Mapper.xml 
mybatis.type-aliases-package=com.zzg.search.domain 
# MyBatis mysql8 éç½® 
spring.datasource.url=jdbc:mysql://192.168.*.**:3306/boot-security?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&allowMultiQueries=true&nullCatalogMeansCurrent=true 
spring.datasource.username=root 
spring.datasource.password=****** 
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 
# Druid éç½® 
# åå§åæ¶å»ºç«ç©çè¿æ¥çä¸ªæ° 
spring.datasource.druid.initial-size=5 
# æ大è¿æ¥æ± æ°é 
spring.datasource.druid.max-active=30 
# æå°è¿æ¥æ± æ°é 
spring.datasource.druid.min-idle=5 
# è·åè¿æ¥æ¶æ大ç­å¾æ¶é´ï¼åä½æ¯«ç§ 
spring.datasource.druid.max-wait=60000 
# éç½®é´éå¤ä¹æè¿è¡ä¸æ¬¡æ£æµï¼æ£æµéè¦å³é­ç空é²è¿æ¥ï¼åä½æ¯æ¯«ç§ 
spring.datasource.druid.time-between-eviction-runs-millis=60000 
# è¿æ¥ä¿æ空é²èä¸è¢«é©±éçæå°æ¶é´ 
spring.datasource.druid.min-evictable-idle-time-millis=300000 
# ç¨æ¥æ£æµè¿æ¥æ¯å¦ææçsqlï¼è¦æ±æ¯ä¸ä¸ªæ¥è¯¢è¯­å¥ 
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL 
# 建议é置为trueï¼ä¸å½±åæ§è½ï¼å¹¶ä¸ä¿è¯å®å¨æ§ãç³è¯·è¿æ¥çæ¶åæ£æµï¼å¦æ空é²æ¶é´å¤§äºtimeBetweenEvictionRunsMillisï¼æ§è¡validationQueryæ£æµè¿æ¥æ¯å¦ææã 
spring.datasource.druid.test-while-idle=true 
# ç³è¯·è¿æ¥æ¶æ§è¡validationQueryæ£æµè¿æ¥æ¯å¦ææï¼åäºè¿ä¸ªéç½®ä¼éä½æ§è½ã 
spring.datasource.druid.test-on-borrow=false 
# å½è¿è¿æ¥æ¶æ§è¡validationQueryæ£æµè¿æ¥æ¯å¦ææï¼åäºè¿ä¸ªéç½®ä¼éä½æ§è½ã 
spring.datasource.druid.test-on-return=false 
# æ¯å¦ç¼å­preparedStatementï¼ä¹å°±æ¯PSCacheãPSCache对æ¯æ游æ çæ°æ®åºæ§è½æå巨大ï¼æ¯å¦è¯´oracleãå¨mysqlä¸å»ºè®®å³é­ã 
spring.datasource.druid.pool-prepared-statements=true 
# è¦å¯ç¨PSCacheï¼å¿é¡»é置大äº0ï¼å½å¤§äº0æ¶ï¼poolPreparedStatementsèªå¨è§¦åä¿®æ¹ä¸ºtrueã 
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=50 
# éç½®çæ§ç»è®¡æ¦æªçfiltersï¼å»æåçæ§çé¢sqlæ æ³ç»è®¡ 
#spring.datasource.druid.filters=stat,wall 
# éè¿connectPropertieså±æ§æ¥æå¼mergeSqlåè½ï¼æ¢SQLè®°å½ 
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 
# å并å¤ä¸ªDruidDataSourceççæ§æ°æ® 
spring.datasource.druid.use-global-data-source-stat=true 
# éç½®sql 注å¥æ¹å¼ 
spring.datasource.druid.filters=stat 
# æ¥å¿æ件éç½® 
logging.config=classpath:logback.xml 
 
# elasticsearch éç½®å±æ§ 
spring.data.elasticsearch.clusterName=my-application 
spring.data.elasticsearch.clusterNodes=192.168.1.74:9300

log4j.properties 配置文件:未编写。

项目整体结构:

标签:Spring Boot
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号