elasticsearch spring 集成html
項目清單
elasticsearch服務下載包括其中插件和分詞
http://download.csdn.net/detail/u014201191/8809619
項目源碼
資源文件
app.properties
- elasticsearch.esNodes=localhost:9300
- elasticsearch.cluster.name=heroscluster
app.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
- http://www.pilato.fr/schema/elasticsearch http://www.pilato.fr/schema/elasticsearch/elasticsearch-0.3.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
- <context:annotation-config />
-
-
- <context:property-placeholder location="classpath:/app.properties" />
-
- <import resource="elasticseach.xml" />
- </beans>
elasticseach.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
- http://www.pilato.fr/schema/elasticsearch http://www.pilato.fr/schema/elasticsearch/elasticsearch-0.3.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
-
- <util:map id="esproperties">
- <entry key="cluster.name" value="${elasticsearch.cluster.name}" />
- </util:map>
-
- <elasticsearch:client id="client" properties="esproperties"
- esNodes="${elasticsearch.esNodes}" />
-
- <bean name="elasticsearchTemplate"
- class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
- <constructor-arg name="client" ref="client" />
- </bean>
-
- <bean name="elasticsearchService" class="com.sf.heros.mq.consumer.service.ElasticsearchService"
- init-method="init" />
-
- <bean name="es" class="com.sf.daidongxi.web.service.ElasticsearchService"></bean>
- </beans>
log4j.properties
- ### \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-dd HH: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-dd HH:mm:ss,SSS} - %m%n
maven管理
Java.class
Bean配置
- package com.sf.heros.mq.consumer.vo;
-
- 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.FieldIndex;
- import org.springframework.data.elasticsearch.annotations.FieldType;
-
- import com.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)
- public class TaskInfo {
- @Id
- @Field(index = FieldIndex.not_analyzed, store = true)
- private String taskId;
-
- @Field(type = FieldType.Integer, index = FieldIndex.not_analyzed, store = true)
- private Integer userId;
-
- @Field(type = FieldType.String, indexAnalyzer="ik", searchAnalyzer="ik", store = true)
- private String taskContent;
-
- @Field(type = FieldType.String, indexAnalyzer="ik", searchAnalyzer="ik", store = true)
- private String taskArea;
-
- @Field(type = FieldType.String, indexAnalyzer="ik", searchAnalyzer="ik", store = true)
- private String taskTags;
-
- @Field(type = FieldType.Integer, index = FieldIndex.not_analyzed, store = true)
- private Integer taskState;
-
- @Field(type = FieldType.String, index = FieldIndex.not_analyzed, store = true)
- private String updateTime;
-
- @Field(type = FieldType.String, indexAnalyzer="ik", searchAnalyzer="ik", store = true)
- private String userNickName;
-
- public String getTaskId() {
- return taskId;
- }
-
- public void setTaskId(String taskId) {
- this.taskId = taskId;
- }
-
- public Integer getUserId() {
- return userId;
- }
-
- public void setUserId(Integer userId) {
- this.userId = userId;
- }
-
- public String getTaskContent() {
- return taskContent;
- }
-
- public void setTaskContent(String taskContent) {
- this.taskContent = taskContent;
- }
-
- public String getTaskArea() {
- return taskArea;
- }
-
- public void setTaskArea(String taskArea) {
- this.taskArea = taskArea;
- }
-
- public String getTaskTags() {
- return taskTags;
- }
-
- public void setTaskTags(String taskTags) {
- this.taskTags = taskTags;
- }
-
- public Integer getTaskState() {
- return taskState;
- }
-
- public void setTaskState(Integer taskState) {
- this.taskState = taskState;
- }
-
- public String getUpdateTime() {
- return updateTime;
- }
-
- public void setUpdateTime(String updateTime) {
- this.updateTime = updateTime;
- }
-
- public String getUserNickName() {
- return userNickName;
- }
-
- public void setUserNickName(String userNickName) {
- this.userNickName = userNickName;
- }
-
- @Override
- public String toString() {
- return "TaskInfo [taskId=" + taskId + ", userId=" + userId
- + ", taskContent=" + taskContent + ", taskArea=" + taskArea
- + ", taskState=" + taskState
- + ", updateTime=" + updateTime + ", userNickName="
- + userNickName + "]";
- }
-
- public TaskInfo(String taskId, Integer userId, String taskContent,
- String taskArea, String taskTags, Integer taskState,
- String updateTime, String userNickName) {
- this.taskId = taskId;
- this.userId = userId;
- this.taskContent = taskContent;
- this.taskArea = taskArea;
- this.taskTags = taskTags;
- this.taskState = taskState;
- this.updateTime = updateTime;
- this.userNickName = userNickName;
- }
- public TaskInfo() {
- // TODO Auto-generated constructor stub
- }
- }
其他的類在源碼中下載,此處不列出了...
常量管理
- package com.sf.heros.mq.consumer.utils;
-
- import java.util.HashMap;
- import java.util.Map;
-
- public interface APP {
- public static final Map<String, String> map = new HashMap<String, String>();
- public static final String CLOSED_MSG = "#################closed####################";
- public static final long DELIVERIED_TAG = -1;
-
- class ESProp {
- public static final String INDEX_NAME = "heros";
- public static final String DAIDONGXI_INDEX_NAME = "daidongxi";
- public static final String TYPE_NEWS_INFO = "news_info";
- public static final String TYPE_PRODUCT_INFO = "product_info";
- public static final String TYPE_STORY_INFO = "story_info";
- public static final String TYPE_TASK_INFO = "task_info";
- public static final String TYPE_USER_INFO = "user_info";
- public static final String TYPE_BRANDCASE_INFO = "brandcase_info";
- public static final String INDEX_STORE_TYPE = "memory";
- public static final int SHARDS = 2;
- public static final int REPLICAS = 1;
- public static final String REFRESH_INTERVAL = "-1";
- }
-
- }
增刪改類
查詢類
- package com.sf.daidongxi.web.service;
-
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.commons.lang.StringUtils;
- import org.apache.log4j.Logger;
- import org.apache.lucene.queries.TermFilter;
- import org.apache.lucene.queryparser.xml.builders.FilteredQueryBuilder;
- import org.elasticsearch.action.search.SearchRequestBuilder;
- import org.elasticsearch.action.search.SearchResponse;
- import org.elasticsearch.action.search.SearchType;
- import org.elasticsearch.client.Client;
- import org.elasticsearch.index.query.BoolFilterBuilder;
- import org.elasticsearch.index.query.FilterBuilder;
- import org.elasticsearch.index.query.FilterBuilders;
- import org.elasticsearch.index.query.MatchQueryBuilder;
- import org.elasticsearch.index.query.QueryBuilder;
- import org.elasticsearch.index.query.QueryBuilders;
- import org.elasticsearch.index.query.QueryStringQueryBuilder;
- import org.elasticsearch.index.query.RangeFilterBuilder;
- import org.elasticsearch.index.query.TermsQueryBuilder;
- import org.elasticsearch.search.SearchHit;
- import org.elasticsearch.search.sort.SortOrder;
- import org.springframework.beans.factory.InitializingBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
-
- import sun.misc.Contended;
-
- public class ElasticsearchService implements InitializingBean {
-
- private static final Logger logger = Logger
- .getLogger(ElasticsearchService.class);
-
- @Autowired
- private Client client;
-
- private String esIndexName = "heros";
-
- @Autowired
- private ElasticsearchTemplate elasticsearchTemplate;
-
- @Autowired
- private Client esClient;
-
- /** 查詢 id */
- public List<String> queryId(String type, String[] fields, String content,
- String sortField, SortOrder order, int from, int size) {
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- QueryStringQueryBuilder queryString = QueryBuilders.queryString("\""
- + content + "\"");
- for (String k : 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);
- }
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
- ArrayList<String> results = new ArrayList<String>();
- for (SearchHit hit : hits) {
- results.add(hit.getId());
- }
- return results;
- }
-
- /**
- * 查詢獲得結果爲Map集合
- *
- * @author 高國藩
- * @date 2015年6月15日 下午8:46:13
- * @param type
- * 表
- * @param fields
- * 字段索引
- * @param content
- * 查詢的值
- * @param sortField
- * 排序的字段
- * @param order
- * 排序的規則
- * @param from
- * 分頁
- * @param size
- * @return
- */
- public List<Map<String, Object>> queryForObject(String type,
- String[] fields, String content, String sortField, SortOrder order,
- int from, int size) {
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- QueryStringQueryBuilder queryString = QueryBuilders.queryString("\""
- + content + "\"");
- for (String k : 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);
- }
-
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
-
- List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
- for (SearchHit hit : hits) {
- results.add(hit.getSource());
- }
- return results;
- }
-
- /**
- * QueryBuilders 全部查詢入口
- */
- public List<Map<String, Object>> queryForObjectEq(String type,
- String[] fields, String content, String sortField, SortOrder order,
- int from, int size) {
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- QueryStringQueryBuilder queryString = QueryBuilders.queryString("\""
- + content + "\"");
- for (String k : 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);
- }
-
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
-
- List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
- for (SearchHit hit : hits) {
- results.add(hit.getSource());
- }
- return results;
- }
-
- /**
- * 多個文字記不清是那些字,而後放進去查詢
- *
- * @author 高國藩
- * @date 2015年6月16日 上午9:56:08
- * @param type
- * @param field
- * @param countents
- * @param sortField
- * @param order
- * @param from
- * @param size
- * @return
- */
- public List<Map<String, Object>> queryForObjectNotEq(String type,
- String field, Collection<String> countents, String sortField,
- SortOrder order, int from, int size) {
-
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- List<String> contents = new ArrayList<String>();
- for (String content : countents) {
- contents.add("\"" + content + "\"");
- }
- TermsQueryBuilder inQuery = 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);
- }
-
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
-
- List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
- for (SearchHit hit : hits) {
- results.add(hit.getSource());
- }
- return results;
- }
-
- /**
- * Filters 查詢方式
- *
- * 1. 1)QueryBuilders.queryString 得到基本查詢
- * 2)FilteredQueryBuilder query = 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 高國藩
- * @date 2015年6月15日 下午10:06:05
- * @param type
- * @param field
- * @param countents
- * @param sortField
- * @param order
- * @param from
- * @param size
- * @return
- */
- public List<Map<String, Object>> queryForObjectForElasticSerch(String type,
- String field, String content,int start,int end) {
-
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- QueryStringQueryBuilder queryString = QueryBuilders.queryString("\""
- + content + "\"");
- queryString.field(field);
- queryString.minimumShouldMatch("10");
-
- reqBuilder.setQuery(QueryBuilders.filteredQuery(queryString, FilterBuilders.rangeFilter("taskState").from(start).to(end)))
- .setExplain(true);
-
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
-
- List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
- for (SearchHit hit : hits) {
- results.add(hit.getSource());
- }
- return results;
- }
-
- public void afterPropertiesSet() throws Exception {
- System.out.println("init...");
-
- }
-
- }
測試
- package com.sf.heros.mq.consumer;
-
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.log4j.Logger;
- import org.elasticsearch.search.sort.SortOrder;
- import org.junit.Test;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import com.sf.heros.mq.consumer.service.ElasticsearchService;
- import com.sf.heros.mq.consumer.utils.APP;
- import com.sf.heros.mq.consumer.vo.TaskInfo;
-
- public class AppMain {
-
- private static final Logger logger = Logger.getLogger(AppMain.class);
-
- public void start() {
- ClassPathXmlApplicationContext context = null;
- try {
- context = new ClassPathXmlApplicationContext("classpath:app.xml");
- } catch (Exception e) {
- logger.error("An error occurred, applicationContext will close.", e);
- if (context != null) {
- context.close();
- }
- context = null;
- logger.error(APP.CLOSED_MSG);
- }
- }
-
- /**
- * 插入
- * @author 高國藩
- * @date 2015年6月16日 上午10:14:21
- */
- @Test
- public void insertNo() {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- "classpath:app.xml");
- ElasticsearchService service = context
- .getBean(ElasticsearchService.class);
- List<TaskInfo> taskInfoList = new ArrayList<TaskInfo>();
- for (int i = 0; i < 20; i++) {
- taskInfoList.add(new TaskInfo(String.valueOf((i + 5)), i + 5, "高國藩"
- + i, "taskArea", "taskTags", i + 5, "1996-02-03", "霍華德"));
- }
- service.insertOrUpdateTaskInfo(taskInfoList);
- }
-
- /**
- * 查詢
- * @author 高國藩
- * @date 2015年6月16日 上午10:14:21
- */
- @Test
- public void serchNo() {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- "classpath:app.xml");
- com.sf.daidongxi.web.service.ElasticsearchService service = (com.sf.daidongxi.web.service.ElasticsearchService) context
- .getBean("es");
- List<Map<String, Object>> al = service.queryForObject("task_info",
- new String[] { "taskContent", "taskArea" }, "高國藩", "taskArea", SortOrder.DESC,
- 0, 2);
-
- for (int i = 0; i < al.size(); i++) {
- System.out.println(al.get(i));
- }
-
- }
-
- /**
- * filter查詢
- * @author 高國藩
- * @date 2015年6月16日 上午10:14:21
- */
- @Test
- public void serchFilter() {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- "classpath:app.xml");
- com.sf.daidongxi.web.service.ElasticsearchService service = (com.sf.daidongxi.web.service.ElasticsearchService) context
- .getBean("es");
- List<Map<String, Object>> al = service.queryForObjectForElasticSerch("task_info", "taskContent", "高",19,20);
-
- for (int i = 0; i < al.size(); i++) {
- System.out.println(al.get(i));
- }
-
- }
- }
源碼項目下載
http://download.csdn.net/detail/u014201191/8812073
http://blog.csdn.net/u014201191/article/details/46508311java
項目清單
elasticsearch服務下載包括其中插件和分詞
http://download.csdn.net/detail/u014201191/8809619
項目源碼
資源文件
app.propertiesweb
- elasticsearch.esNodes=localhost:9300
- elasticsearch.cluster.name=heroscluster
app.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="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:
- http:
- http:
- http:
- <context:annotation-config />
- <!-- 自動掃描全部註解該路徑 -->
- <!-- <context:component-scan base-package="com.sf.heros.mq.*" /> -->
- <context:property-placeholder location="classpath:/app.properties" />
-
- <import resource="elasticseach.xml" />
- </beans>
elasticseach.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="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:
- http:
- http:
- http:
-
- <util:map id="esproperties">
- <entry key="cluster.name" value="${elasticsearch.cluster.name}" />
- </util:map>
-
- <elasticsearch:client id="client" properties="esproperties"
- esNodes="${elasticsearch.esNodes}" />
-
- <bean name="elasticsearchTemplate"
- class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
- <constructor-arg name="client" ref="client" />
- </bean>
-
- <bean name="elasticsearchService" class="com.sf.heros.mq.consumer.service.ElasticsearchService"
- init-method="init" />
-
- <bean name="es" class="com.sf.daidongxi.web.service.ElasticsearchService"></bean>
- </beans>
mavenspring
Java.class
Bean配置
- package com.sf.heros.mq.consumer.vo;
-
- 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.FieldIndex;
- import org.springframework.data.elasticsearch.annotations.FieldType;
-
- import com.sf.heros.mq.consumer.utils.APP;
-
- @Document(indexName = APP.ESProp.INDEX_NAME, type = APP.ESProp.TYPE_TASK_INFO)
- public class TaskInfo {
- @Id
- @Field(index = FieldIndex.not_analyzed, store = true)
- private String taskId;
-
- @Field(type = FieldType.Integer, index = FieldIndex.not_analyzed, store = true)
- private Integer userId;
-
- @Field(type = FieldType.String, indexAnalyzer="ik", searchAnalyzer="ik", store = true)
- private String taskContent;
-
- @Field(type = FieldType.String, indexAnalyzer="ik", searchAnalyzer="ik", store = true)
- private String taskArea;
-
- @Field(type = FieldType.String, indexAnalyzer="ik", searchAnalyzer="ik", store = true)
- private String taskTags;
-
- @Field(type = FieldType.Integer, index = FieldIndex.not_analyzed, store = true)
- private Integer taskState;
-
- @Field(type = FieldType.String, index = FieldIndex.not_analyzed, store = true)
- private String updateTime;
-
- @Field(type = FieldType.String, indexAnalyzer="ik", searchAnalyzer="ik", store = true)
- private String userNickName;
-
- public String getTaskId() {
- return taskId;
- }
-
- public void setTaskId(String taskId) {
- this.taskId = taskId;
- }
-
- public Integer getUserId() {
- return userId;
- }
-
- public void setUserId(Integer userId) {
- this.userId = userId;
- }
-
- public String getTaskContent() {
- return taskContent;
- }
-
- public void setTaskContent(String taskContent) {
- this.taskContent = taskContent;
- }
-
- public String getTaskArea() {
- return taskArea;
- }
-
- public void setTaskArea(String taskArea) {
- this.taskArea = taskArea;
- }
-
- public String getTaskTags() {
- return taskTags;
- }
-
- public void setTaskTags(String taskTags) {
- this.taskTags = taskTags;
- }
-
- public Integer getTaskState() {
- return taskState;
- }
-
- public void setTaskState(Integer taskState) {
- this.taskState = taskState;
- }
-
- public String getUpdateTime() {
- return updateTime;
- }
-
- public void setUpdateTime(String updateTime) {
- this.updateTime = updateTime;
- }
-
- public String getUserNickName() {
- return userNickName;
- }
-
- public void setUserNickName(String userNickName) {
- this.userNickName = userNickName;
- }
-
- @Override
- public String toString() {
- return "TaskInfo [taskId=" + taskId + ", userId=" + userId
- + ", taskContent=" + taskContent + ", taskArea=" + taskArea
- + ", taskState=" + taskState
- + ", updateTime=" + updateTime + ", userNickName="
- + userNickName + "]";
- }
-
- public TaskInfo(String taskId, Integer userId, String taskContent,
- String taskArea, String taskTags, Integer taskState,
- String updateTime, String userNickName) {
- this.taskId = taskId;
- this.userId = userId;
- this.taskContent = taskContent;
- this.taskArea = taskArea;
- this.taskTags = taskTags;
- this.taskState = taskState;
- this.updateTime = updateTime;
- this.userNickName = userNickName;
- }
- public TaskInfo() {
-
- }
- }
增刪改類
查詢類
- package com.sf.daidongxi.web.service;
-
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.commons.lang.StringUtils;
- import org.apache.log4j.Logger;
- import org.apache.lucene.queries.TermFilter;
- import org.apache.lucene.queryparser.xml.builders.FilteredQueryBuilder;
- import org.elasticsearch.action.search.SearchRequestBuilder;
- import org.elasticsearch.action.search.SearchResponse;
- import org.elasticsearch.action.search.SearchType;
- import org.elasticsearch.client.Client;
- import org.elasticsearch.index.query.BoolFilterBuilder;
- import org.elasticsearch.index.query.FilterBuilder;
- import org.elasticsearch.index.query.FilterBuilders;
- import org.elasticsearch.index.query.MatchQueryBuilder;
- import org.elasticsearch.index.query.QueryBuilder;
- import org.elasticsearch.index.query.QueryBuilders;
- import org.elasticsearch.index.query.QueryStringQueryBuilder;
- import org.elasticsearch.index.query.RangeFilterBuilder;
- import org.elasticsearch.index.query.TermsQueryBuilder;
- import org.elasticsearch.search.SearchHit;
- import org.elasticsearch.search.sort.SortOrder;
- import org.springframework.beans.factory.InitializingBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
-
- import sun.misc.Contended;
-
- public class ElasticsearchService implements InitializingBean {
-
- private static final Logger logger = Logger
- .getLogger(ElasticsearchService.class);
-
- @Autowired
- private Client client;
-
- private String esIndexName = "heros";
-
- @Autowired
- private ElasticsearchTemplate elasticsearchTemplate;
-
- @Autowired
- private Client esClient;
-
-
- public List<String> queryId(String type, String[] fields, String content,
- String sortField, SortOrder order, int from, int size) {
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- QueryStringQueryBuilder queryString = QueryBuilders.queryString("\""
- + content + "\"");
- for (String k : 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);
- }
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
- ArrayList<String> results = new ArrayList<String>();
- for (SearchHit hit : hits) {
- results.add(hit.getId());
- }
- return results;
- }
-
-
- public List<Map<String, Object>> queryForObject(String type,
- String[] fields, String content, String sortField, SortOrder order,
- int from, int size) {
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- QueryStringQueryBuilder queryString = QueryBuilders.queryString("\""
- + content + "\"");
- for (String k : 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);
- }
-
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
-
- List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
- for (SearchHit hit : hits) {
- results.add(hit.getSource());
- }
- return results;
- }
-
-
- public List<Map<String, Object>> queryForObjectEq(String type,
- String[] fields, String content, String sortField, SortOrder order,
- int from, int size) {
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- QueryStringQueryBuilder queryString = QueryBuilders.queryString("\""
- + content + "\"");
- for (String k : 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);
- }
-
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
-
- List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
- for (SearchHit hit : hits) {
- results.add(hit.getSource());
- }
- return results;
- }
-
-
- public List<Map<String, Object>> queryForObjectNotEq(String type,
- String field, Collection<String> countents, String sortField,
- SortOrder order, int from, int size) {
-
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- List<String> contents = new ArrayList<String>();
- for (String content : countents) {
- contents.add("\"" + content + "\"");
- }
- TermsQueryBuilder inQuery = 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);
- }
-
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
-
- List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
- for (SearchHit hit : hits) {
- results.add(hit.getSource());
- }
- return results;
- }
-
-
- public List<Map<String, Object>> queryForObjectForElasticSerch(String type,
- String field, String content,int start,int end) {
-
- SearchRequestBuilder reqBuilder = client.prepareSearch(esIndexName)
- .setTypes(type).setSearchType(SearchType.DEFAULT)
- .setExplain(true);
- QueryStringQueryBuilder queryString = QueryBuilders.queryString("\""
- + content + "\"");
- queryString.field(field);
- queryString.minimumShouldMatch("10");
-
- reqBuilder.setQuery(QueryBuilders.filteredQuery(queryString, FilterBuilders.rangeFilter("taskState").from(start).to(end)))
- .setExplain(true);
-
- SearchResponse resp = reqBuilder.execute().actionGet();
- SearchHit[] hits = resp.getHits().getHits();
-
- List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
- for (SearchHit hit : hits) {
- results.add(hit.getSource());
- }
- return results;
- }
-
- public void afterPropertiesSet() throws Exception {
- System.out.println("init...");
-
- }
-
- }
測試express
- package com.sf.heros.mq.consumer;
-
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.log4j.Logger;
- import org.elasticsearch.search.sort.SortOrder;
- import org.junit.Test;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import com.sf.heros.mq.consumer.service.ElasticsearchService;
- import com.sf.heros.mq.consumer.utils.APP;
- import com.sf.heros.mq.consumer.vo.TaskInfo;
-
- public class AppMain {
-
- private static final Logger logger = Logger.getLogger(AppMain.class);
-
- public void start() {
- ClassPathXmlApplicationContext context = null;
- try {
- context = new ClassPathXmlApplicationContext("classpath:app.xml");
- } catch (Exception e) {
- logger.error("An error occurred, applicationContext will close.", e);
- if (context != null) {
- context.close();
- }
- context = null;
- logger.error(APP.CLOSED_MSG);
- }
- }
-
-
- @Test
- public void insertNo() {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- "classpath:app.xml");
- ElasticsearchService service = context
- .getBean(ElasticsearchService.class);
- List<TaskInfo> taskInfoList = new ArrayList<TaskInfo>();
- for (int i = 0; i < 20; i++) {
- taskInfoList.add(new TaskInfo(String.valueOf((i + 5)), i + 5, "高國藩"
- + i, "taskArea", "taskTags", i + 5, "1996-02-03", "霍華德"));
- }
- service.insertOrUpdateTaskInfo(taskInfoList);
- }
-
-
- @Test
- public void serchNo() {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- "classpath:app.xml");
- com.sf.daidongxi.web.service.ElasticsearchService service = (com.sf.daidongxi.web.service.ElasticsearchService) context
- .getBean("es");
- List<Map<String, Object>> al = service.queryForObject("task_info",
- new String[] { "taskContent", "taskArea" }, "高國藩", "taskArea", SortOrder.DESC,
- 0, 2);
-
- for (int i = 0; i < al.size(); i++) {
- System.out.println(al.get(i));
- }
-
- }
-
-
- @Test
- public void serchFilter() {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- "classpath:app.xml");
- com.sf.daidongxi.web.service.ElasticsearchService service = (com.sf.daidongxi.web.service.ElasticsearchService) context
- .getBean("es");
- List<Map<String, Object>> al = service.queryForObjectForElasticSerch("task_info", "taskContent", "高",19,20);
-
- for (int i = 0; i < al.size(); i++) {
- System.out.println(al.get(i));
- }
-
- }
- }
http://download.csdn.net/detail/liyantianmin/9565012
http://blog.csdn.net/liyantianmin/article/details/51801961apache