项目清单
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:
- 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>
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)
- 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...");
-
- }
-
- }
测试
- 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/51801961
Spring Data Elasticsearch
原文:http://www.cnblogs.com/softidea/p/5862844.html