elasticsearch spring 整合
项目清单 elasticsearch服务下载包括其中插件和分词 http://download.csdn.net/detail/u014201191/8809619 项目源码 资源文件 app.properties [html] view plain copy elasticsearch.esNodes=localhost:9300 elasticsearch.cluster.name=heroscluster app.xml [html] view plain copy <?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:elasticsearch="http://www.pilato.fr/schema/elasticsearch" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.pilato.fr/schema/elasticsearchhttp://www.pilato.fr/schema/elasticsearch/elasticsearch-0.3.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:annotation-config/> <!--自动扫描所有注解该路径--> <!--<context:component-scanbase-package="com.sf.heros.mq.*"/>--> <context:property-placeholderlocation="classpath:/app.properties"/> <importresource="elasticseach.xml"/> </beans> elasticseach.xml [html] view plain copy <?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:elasticsearch="http://www.pilato.fr/schema/elasticsearch" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.pilato.fr/schema/elasticsearchhttp://www.pilato.fr/schema/elasticsearch/elasticsearch-0.3.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd"> <util:mapid="esproperties"> <entrykey="cluster.name"value="${elasticsearch.cluster.name}"/> </util:map> <elasticsearch:clientid="client"properties="esproperties" esNodes="${elasticsearch.esNodes}"/> <beanname="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <constructor-argname="client"ref="client"/> </bean> <beanname="elasticsearchService"class="com.sf.heros.mq.consumer.service.ElasticsearchService" init-method="init"/> <beanname="es"class="com.sf.daidongxi.web.service.ElasticsearchService"></bean> </beans> log4j.properties [html] view plain copy ###\u8bbe\u7f6eLogger\u8f93\u51fa\u7ea7\u522b\u548c\u8f93\u51fa\u76ee\u7684\u5730### log4j.rootLogger=info,logfile log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.Threshold=info log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%-5p]%d{yyyy-MM-ddHH:mm:ss,SSS}-%m%n log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender log4j.appender.logfile.File=/app/logs/mq_consumer.log log4j.appender.logfile.datePattern='.'yyyy-MM-dd'.' log4j.appender.logfile.append=true log4j.appender.logfile.Threshold=debug log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=[%-5p]%d{yyyy-MM-ddHH:mm:ss,SSS}-%m%n maven管理 [html] view plain copy <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>elasticsearchMavenWebapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>3.1.1.RELEASE</spring.version> <findbugs.annotations>2.0.0</findbugs.annotations> <checkstyle.maven.plugin>2.11</checkstyle.maven.plugin> <pmd.maven.plugin>3.0</pmd.maven.plugin> <findbugs.maven.plugin>2.5.3</findbugs.maven.plugin> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!--springbegin--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!--springend--> <!--elasticsearchpackage--> <dependency> <groupId>fr.pilato.spring</groupId> <artifactId>spring-elasticsearch</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <version>1.0.0.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.5</version> </dependency> <!--json-lib--> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <!--quartzjob--> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <!--log4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> </dependencies> <build> <finalName>elasticsearch</finalName> </build> </project> Java.class Bean配置 [html] view plain copy packagecom.sf.heros.mq.consumer.vo; importorg.springframework.data.annotation.Id; importorg.springframework.data.elasticsearch.annotations.Document; importorg.springframework.data.elasticsearch.annotations.Field; importorg.springframework.data.elasticsearch.annotations.FieldIndex; importorg.springframework.data.elasticsearch.annotations.FieldType; importcom.sf.heros.mq.consumer.utils.APP; //@Document(indexName=APP.ESProp.INDEX_NAME,type=APP.ESProp.TYPE_TASK_INFO,indexStoreType=APP.ESProp.INDEX_STORE_TYPE,shards=APP.ESProp.SHARDS,replicas=APP.ESProp.REPLICAS,refreshInterval=APP.ESProp.REFRESH_INTERVAL) @Document(indexName=APP.ESProp.INDEX_NAME,type=APP.ESProp.TYPE_TASK_INFO) publicclassTaskInfo{ @Id @Field(index=FieldIndex.not_analyzed,store=true) privateStringtaskId; @Field(type=FieldType.Integer,index=FieldIndex.not_analyzed,store=true) privateIntegeruserId; @Field(type=FieldType.String,indexAnalyzer="ik",searchAnalyzer="ik",store=true) privateStringtaskContent; @Field(type=FieldType.String,indexAnalyzer="ik",searchAnalyzer="ik",store=true) privateStringtaskArea; @Field(type=FieldType.String,indexAnalyzer="ik",searchAnalyzer="ik",store=true) privateStringtaskTags; @Field(type=FieldType.Integer,index=FieldIndex.not_analyzed,store=true) privateIntegertaskState; @Field(type=FieldType.String,index=FieldIndex.not_analyzed,store=true) privateStringupdateTime; @Field(type=FieldType.String,indexAnalyzer="ik",searchAnalyzer="ik",store=true) privateStringuserNickName; publicStringgetTaskId(){ returntaskId; } publicvoidsetTaskId(StringtaskId){ this.taskId=taskId; } publicIntegergetUserId(){ returnuserId; } publicvoidsetUserId(IntegeruserId){ this.userId=userId; } publicStringgetTaskContent(){ returntaskContent; } publicvoidsetTaskContent(StringtaskContent){ this.taskContent=taskContent; } publicStringgetTaskArea(){ returntaskArea; } publicvoidsetTaskArea(StringtaskArea){ this.taskArea=taskArea; } publicStringgetTaskTags(){ returntaskTags; } publicvoidsetTaskTags(StringtaskTags){ this.taskTags=taskTags; } publicIntegergetTaskState(){ returntaskState; } publicvoidsetTaskState(IntegertaskState){ this.taskState=taskState; } publicStringgetUpdateTime(){ returnupdateTime; } publicvoidsetUpdateTime(StringupdateTime){ this.updateTime=updateTime; } publicStringgetUserNickName(){ returnuserNickName; } publicvoidsetUserNickName(StringuserNickName){ this.userNickName=userNickName; } @Override publicStringtoString(){ return"TaskInfo[taskId="+taskId+",userId="+userId +",taskContent="+taskContent+",taskArea="+taskArea +",taskState="+taskState +",updateTime="+updateTime+",userNickName=" +userNickName+"]"; } publicTaskInfo(StringtaskId,IntegeruserId,StringtaskContent, StringtaskArea,StringtaskTags,IntegertaskState, StringupdateTime,StringuserNickName){ this.taskId=taskId; this.userId=userId; this.taskContent=taskContent; this.taskArea=taskArea; this.taskTags=taskTags; this.taskState=taskState; this.updateTime=updateTime; this.userNickName=userNickName; } publicTaskInfo(){ //TODOAuto-generatedconstructorstub } } 其余的类在源码中下载,此处不列出了... 常量管理 [html] view plain copy packagecom.sf.heros.mq.consumer.utils; importjava.util.HashMap; importjava.util.Map; publicinterfaceAPP{ publicstaticfinalMap<String,String>map=newHashMap<String,String>(); publicstaticfinalStringCLOSED_MSG="#################closed####################"; publicstaticfinallongDELIVERIED_TAG=-1; classESProp{ publicstaticfinalStringINDEX_NAME="heros"; publicstaticfinalStringDAIDONGXI_INDEX_NAME="daidongxi"; publicstaticfinalStringTYPE_NEWS_INFO="news_info"; publicstaticfinalStringTYPE_PRODUCT_INFO="product_info"; publicstaticfinalStringTYPE_STORY_INFO="story_info"; publicstaticfinalStringTYPE_TASK_INFO="task_info"; publicstaticfinalStringTYPE_USER_INFO="user_info"; publicstaticfinalStringTYPE_BRANDCASE_INFO="brandcase_info"; publicstaticfinalStringINDEX_STORE_TYPE="memory"; publicstaticfinalintSHARDS=2; publicstaticfinalintREPLICAS=1; publicstaticfinalStringREFRESH_INTERVAL="-1"; } } 增删改类 [html] view plain copy /** *@Pr锛歨eros *@Date:2014-5-4涓婂崍9:21:27 *@Author:seaphy *@Copyright:漏2012sf-express.comInc.Allrightsreserved *娉ㄦ剰锛氭湰鍐呭浠呴檺浜庨『涓伴�熻繍鍏徃鍐呴儴浼犻槄锛岀姝㈠娉勪互鍙婄敤浜庡叾浠栫殑鍟嗕笟鐩殑 */ packagecom.sf.heros.mq.consumer.service; importjava.util.ArrayList; importjava.util.List; importorg.apache.log4j.Logger; importorg.elasticsearch.action.ActionFuture; importorg.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; importorg.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; importorg.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; importorg.elasticsearch.client.Client; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.data.elasticsearch.core.ElasticsearchTemplate; importorg.springframework.data.elasticsearch.core.query.IndexQuery; importorg.springframework.data.elasticsearch.core.query.IndexQueryBuilder; importcom.sf.heros.mq.consumer.utils.APP; importcom.sf.heros.mq.consumer.vo.BrandCaseInfo; importcom.sf.heros.mq.consumer.vo.NewsInfo; importcom.sf.heros.mq.consumer.vo.TaskInfo; importcom.sf.heros.mq.consumer.vo.UserInfo; /** *@authorseaphy *@date2014-5-4 */ publicclassElasticsearchService{ privatestaticfinalLoggerlogger=Logger.getLogger(ElasticsearchService.class); @Autowired privateElasticsearchTemplateelasticsearchTemplate; @Autowired privateClientesClient; publicvoidinit(){ if(!elasticsearchTemplate.indexExists(APP.ESProp.INDEX_NAME)){ elasticsearchTemplate.createIndex(APP.ESProp.INDEX_NAME); } elasticsearchTemplate.putMapping(TaskInfo.class); elasticsearchTemplate.putMapping(NewsInfo.class); } publicbooleanupdate(List<TaskInfo>taskInfoList){ List<IndexQuery>queries=newArrayList<IndexQuery>(); for(TaskInfotaskInfo:taskInfoList){ IndexQueryindexQuery=newIndexQueryBuilder().withId(taskInfo.getTaskId()).withObject(taskInfo).build(); queries.add(indexQuery); } elasticsearchTemplate.bulkIndex(queries); returntrue; } publicbooleaninsertOrUpdateTaskInfo(List<TaskInfo>taskInfoList){ List<IndexQuery>queries=newArrayList<IndexQuery>(); for(TaskInfotaskInfo:taskInfoList){ IndexQueryindexQuery=newIndexQueryBuilder().withId(taskInfo.getTaskId()).withObject(taskInfo).build(); queries.add(indexQuery); } elasticsearchTemplate.bulkIndex(queries); returntrue; } publicbooleaninsertOrUpdateNewsInfo(List<NewsInfo>newsInfos){ List<IndexQuery>queries=newArrayList<IndexQuery>(); for(NewsInfonewsInfo:newsInfos){ IndexQueryindexQuery=newIndexQueryBuilder().withId(newsInfo.getNewsId()).withObject(newsInfo).build(); queries.add(indexQuery); } elasticsearchTemplate.bulkIndex(queries); returntrue; } publicbooleaninsertOrUpdateNewsInfo(NewsInfonewsInfo){ try{ IndexQueryindexQuery=newIndexQueryBuilder().withId(newsInfo.getNewsId()).withObject(newsInfo).build(); elasticsearchTemplate.index(indexQuery); returntrue; }catch(Exceptione){ logger.error("insertorupdatenewsinfoerror.",e); returnfalse; } } publicbooleaninsertOrUpdateTaskInfo(TaskInfotaskInfo){ try{ IndexQueryindexQuery=newIndexQueryBuilder().withId(taskInfo.getTaskId()).withObject(taskInfo).build(); elasticsearchTemplate.index(indexQuery); returntrue; }catch(Exceptione){ logger.error("insertorupdatetaskinfoerror.",e); returnfalse; } } publicbooleaninsertOrUpdateUserInfo(UserInfouserInfo){ try{ IndexQueryindexQuery=newIndexQueryBuilder().withId(userInfo.getUserId()).withObject(userInfo).build(); elasticsearchTemplate.index(indexQuery); returntrue; }catch(Exceptione){ logger.error("insertorupdateuserinfoerror.",e); returnfalse; } } public<T>booleandeleteById(Stringid,Class<T>clzz){ try{ elasticsearchTemplate.delete(clzz,id); returntrue; }catch(Exceptione){ logger.error("delete"+clzz+"byid"+id+"error.",e); returnfalse; } } /** *检查健康状态 *@author高国藩 *@date2015年6月15日下午6:59:47 *@return */ publicbooleanping(){ try{ ActionFuture<ClusterHealthResponse>health=esClient.admin().cluster().health(newClusterHealthRequest()); ClusterHealthStatusstatus=health.actionGet().getStatus(); if(status.value()==ClusterHealthStatus.RED.value()){ thrownewRuntimeException("elasticsearchclusterhealthstatusisred."); } returntrue; }catch(Exceptione){ logger.error("pingelasticsearcherror.",e); returnfalse; } } publicbooleaninsertOrUpdateBrandCaseInfo(BrandCaseInfobrandCaseInfo){ try{ IndexQueryindexQuery=newIndexQueryBuilder() .withId(brandCaseInfo.getId()).withObject(brandCaseInfo).build(); elasticsearchTemplate.index(indexQuery); returntrue; }catch(Exceptione){ logger.error("insertorupdatebrandcaseinfoerror.",e); returnfalse; } } } 查询类 [html] view plain copy packagecom.sf.daidongxi.web.service; importjava.util.ArrayList; importjava.util.Collection; importjava.util.List; importjava.util.Map; importorg.apache.commons.lang.StringUtils; importorg.apache.log4j.Logger; importorg.apache.lucene.queries.TermFilter; importorg.apache.lucene.queryparser.xml.builders.FilteredQueryBuilder; importorg.elasticsearch.action.search.SearchRequestBuilder; importorg.elasticsearch.action.search.SearchResponse; importorg.elasticsearch.action.search.SearchType; importorg.elasticsearch.client.Client; importorg.elasticsearch.index.query.BoolFilterBuilder; importorg.elasticsearch.index.query.FilterBuilder; importorg.elasticsearch.index.query.FilterBuilders; importorg.elasticsearch.index.query.MatchQueryBuilder; importorg.elasticsearch.index.query.QueryBuilder; importorg.elasticsearch.index.query.QueryBuilders; importorg.elasticsearch.index.query.QueryStringQueryBuilder; importorg.elasticsearch.index.query.RangeFilterBuilder; importorg.elasticsearch.index.query.TermsQueryBuilder; importorg.elasticsearch.search.SearchHit; importorg.elasticsearch.search.sort.SortOrder; importorg.springframework.beans.factory.InitializingBean; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.data.elasticsearch.core.ElasticsearchTemplate; importsun.misc.Contended; publicclassElasticsearchServiceimplementsInitializingBean{ privatestaticfinalLoggerlogger=Logger .getLogger(ElasticsearchService.class); @Autowired privateClientclient; privateStringesIndexName="heros"; @Autowired privateElasticsearchTemplateelasticsearchTemplate; @Autowired privateClientesClient; /**查询id*/ publicList<String>queryId(Stringtype,String[]fields,Stringcontent, StringsortField,SortOrderorder,intfrom,intsize){ SearchRequestBuilderreqBuilder=client.prepareSearch(esIndexName) .setTypes(type).setSearchType(SearchType.DEFAULT) .setExplain(true); QueryStringQueryBuilderqueryString=QueryBuilders.queryString("\"" +content+"\""); for(Stringk:fields){ queryString.field(k); } queryString.minimumShouldMatch("10"); reqBuilder.setQuery(QueryBuilders.boolQuery().should(queryString)) .setExplain(true); if(StringUtils.isNotEmpty(sortField)&&order!=null){ reqBuilder.addSort(sortField,order); } if(from>=0&&size>0){ reqBuilder.setFrom(from).setSize(size); } SearchResponseresp=reqBuilder.execute().actionGet(); SearchHit[]hits=resp.getHits().getHits(); ArrayList<String>results=newArrayList<String>(); for(SearchHithit:hits){ results.add(hit.getId()); } returnresults; } /** *查询得到结果为Map集合 * *@author高国藩 *@date2015年6月15日下午8:46:13 *@paramtype *表 *@paramfields *字段索引 *@paramcontent *查询的值 *@paramsortField *排序的字段 *@paramorder *排序的規則 *@paramfrom *分頁 *@paramsize *@return */ publicList<Map<String,Object>>queryForObject(Stringtype, String[]fields,Stringcontent,StringsortField,SortOrderorder, intfrom,intsize){ SearchRequestBuilderreqBuilder=client.prepareSearch(esIndexName) .setTypes(type).setSearchType(SearchType.DEFAULT) .setExplain(true); QueryStringQueryBuilderqueryString=QueryBuilders.queryString("\"" +content+"\""); for(Stringk:fields){ queryString.field(k); } queryString.minimumShouldMatch("10"); reqBuilder.setQuery(QueryBuilders.boolQuery().should(queryString)) .setExplain(true); if(StringUtils.isNotEmpty(sortField)&&order!=null){ reqBuilder.addSort(sortField,order); } if(from>=0&&size>0){ reqBuilder.setFrom(from).setSize(size); } SearchResponseresp=reqBuilder.execute().actionGet(); SearchHit[]hits=resp.getHits().getHits(); List<Map<String,Object>>results=newArrayList<Map<String,Object>>(); for(SearchHithit:hits){ results.add(hit.getSource()); } returnresults; } /** *QueryBuilders所有查询入口 */ publicList<Map<String,Object>>queryForObjectEq(Stringtype, String[]fields,Stringcontent,StringsortField,SortOrderorder, intfrom,intsize){ SearchRequestBuilderreqBuilder=client.prepareSearch(esIndexName) .setTypes(type).setSearchType(SearchType.DEFAULT) .setExplain(true); QueryStringQueryBuilderqueryString=QueryBuilders.queryString("\"" +content+"\""); for(Stringk:fields){ queryString.field(k); } queryString.minimumShouldMatch("10"); reqBuilder.setQuery(QueryBuilders.boolQuery().must(queryString)) .setExplain(true); if(StringUtils.isNotEmpty(sortField)&&order!=null){ reqBuilder.addSort(sortField,order); } if(from>=0&&size>0){ reqBuilder.setFrom(from).setSize(size); } SearchResponseresp=reqBuilder.execute().actionGet(); SearchHit[]hits=resp.getHits().getHits(); List<Map<String,Object>>results=newArrayList<Map<String,Object>>(); for(SearchHithit:hits){ results.add(hit.getSource()); } returnresults; } /** *多个文字记不清是那些字,然后放进去查询 * *@author高国藩 *@date2015年6月16日上午9:56:08 *@paramtype *@paramfield *@paramcountents *@paramsortField *@paramorder *@paramfrom *@paramsize *@return */ publicList<Map<String,Object>>queryForObjectNotEq(Stringtype, Stringfield,Collection<String>countents,StringsortField, SortOrderorder,intfrom,intsize){ SearchRequestBuilderreqBuilder=client.prepareSearch(esIndexName) .setTypes(type).setSearchType(SearchType.DEFAULT) .setExplain(true); List<String>contents=newArrayList<String>(); for(Stringcontent:countents){ contents.add("\""+content+"\""); } TermsQueryBuilderinQuery=QueryBuilders.inQuery(field,contents); inQuery.minimumShouldMatch("10"); reqBuilder.setQuery(QueryBuilders.boolQuery().mustNot(inQuery)) .setExplain(true); if(StringUtils.isNotEmpty(sortField)&&order!=null){ reqBuilder.addSort(sortField,order); } if(from>=0&&size>0){ reqBuilder.setFrom(from).setSize(size); } SearchResponseresp=reqBuilder.execute().actionGet(); SearchHit[]hits=resp.getHits().getHits(); List<Map<String,Object>>results=newArrayList<Map<String,Object>>(); for(SearchHithit:hits){ results.add(hit.getSource()); } returnresults; } /** *Filters查询方式 * *1.1)QueryBuilders.queryString获得基本查询 *2)FilteredQueryBuilderquery=QueryBuilders.filteredQuery(queryString,FilterBuilder) *3)通过上面封装成为查询,将这个query插入到reqBuilder中;完成操作 * *2.在reqBuilder.setQuery(query); * *3.介绍在2)中的FilterBuilder各种构造方式-参数都可以传String类型即可 *FilterBuilders.rangeFilter("taskState").lt(20)小于、lte(20)小于等于 *FilterBuilders.rangeFilter("taskState").gt(20))大于、gte(20)大于等于 *FilterBuilders.rangeFilter("taskState").from(start).to(end))范围,也可以指定日期,用字符串就ok了 *@author高国藩 *@date2015年6月15日下午10:06:05 *@paramtype *@paramfield *@paramcountents *@paramsortField *@paramorder *@paramfrom *@paramsize *@return */ publicList<Map<String,Object>>queryForObjectForElasticSerch(Stringtype, Stringfield,Stringcontent,intstart,intend){ SearchRequestBuilderreqBuilder=client.prepareSearch(esIndexName) .setTypes(type).setSearchType(SearchType.DEFAULT) .setExplain(true); QueryStringQueryBuilderqueryString=QueryBuilders.queryString("\"" +content+"\""); queryString.field(field); queryString.minimumShouldMatch("10"); reqBuilder.setQuery(QueryBuilders.filteredQuery(queryString,FilterBuilders.rangeFilter("taskState").from(start).to(end))) .setExplain(true); SearchResponseresp=reqBuilder.execute().actionGet(); SearchHit[]hits=resp.getHits().getHits(); List<Map<String,Object>>results=newArrayList<Map<String,Object>>(); for(SearchHithit:hits){ results.add(hit.getSource()); } returnresults; } publicvoidafterPropertiesSet()throwsException{ System.out.println("init..."); } } 测试 [html] view plain copy packagecom.sf.heros.mq.consumer; importjava.util.ArrayList; importjava.util.Collection; importjava.util.HashSet; importjava.util.List; importjava.util.Map; importorg.apache.log4j.Logger; importorg.elasticsearch.search.sort.SortOrder; importorg.junit.Test; importorg.springframework.context.support.ClassPathXmlApplicationContext; importcom.sf.heros.mq.consumer.service.ElasticsearchService; importcom.sf.heros.mq.consumer.utils.APP; importcom.sf.heros.mq.consumer.vo.TaskInfo; publicclassAppMain{ privatestaticfinalLoggerlogger=Logger.getLogger(AppMain.class); publicvoidstart(){ ClassPathXmlApplicationContextcontext=null; try{ context=newClassPathXmlApplicationContext("classpath:app.xml"); }catch(Exceptione){ logger.error("Anerroroccurred,applicationContextwillclose.",e); if(context!=null){ context.close(); } context=null; logger.error(APP.CLOSED_MSG); } } /** *插入 *@author高国藩 *@date2015年6月16日上午10:14:21 */ @Test publicvoidinsertNo(){ ClassPathXmlApplicationContextcontext=newClassPathXmlApplicationContext( "classpath:app.xml"); ElasticsearchServiceservice=context .getBean(ElasticsearchService.class); List<TaskInfo>taskInfoList=newArrayList<TaskInfo>(); for(inti=0;i<20;i++){ taskInfoList.add(newTaskInfo(String.valueOf((i+5)),i+5,"高国藩" +i,"taskArea","taskTags",i+5,"1996-02-03","霍华德")); } service.insertOrUpdateTaskInfo(taskInfoList); } /** *查询 *@author高国藩 *@date2015年6月16日上午10:14:21 */ @Test publicvoidserchNo(){ ClassPathXmlApplicationContextcontext=newClassPathXmlApplicationContext( "classpath:app.xml"); com.sf.daidongxi.web.service.ElasticsearchServiceservice=(com.sf.daidongxi.web.service.ElasticsearchService)context .getBean("es"); List<Map<String,Object>>al=service.queryForObject("task_info", newString[]{"taskContent","taskArea"},"高国藩","taskArea",SortOrder.DESC, 0,2); for(inti=0;i<al.size();i++){ System.out.println(al.get(i)); } } /** *filter查询 *@author高国藩 *@date2015年6月16日上午10:14:21 */ @Test publicvoidserchFilter(){ ClassPathXmlApplicationContextcontext=newClassPathXmlApplicationContext( "classpath:app.xml"); com.sf.daidongxi.web.service.ElasticsearchServiceservice=(com.sf.daidongxi.web.service.ElasticsearchService)context .getBean("es"); List<Map<String,Object>>al=service.queryForObjectForElasticSerch("task_info","taskContent","高",19,20); for(inti=0;i<al.size();i++){ System.out.println(al.get(i)); } } }