Spring Data Elasticsearch
项目清单
elasticsearch服务下载包括其中插件和分词
项目源码
资源文件
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: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://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>
maven
- <project xmlns="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.0 http://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>elasticsearch Maven Webapp</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>
- <!-- spring begin -->
- <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>
- <!-- spring end -->
- <!-- elasticsearch package -->
- <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>
- <!-- quartz job -->
- <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配置
- 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
- }
- }
增删改类
- /**
- *@Pr锛歨eros
- *@Date: 2014-5-4 涓婂崍9:21:27
- *@Author: seaphy
- *@Copyright: 漏 2012 sf-express.com Inc. All rights reserved
- *娉ㄦ剰锛氭湰鍐呭浠呴檺浜庨『涓伴�熻繍鍏徃鍐呴儴浼犻槄锛岀姝㈠娉勪互鍙婄敤浜庡叾浠栫殑鍟嗕笟鐩殑
- */
- package com.sf.heros.mq.consumer.service;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.log4j.Logger;
- import org.elasticsearch.action.ActionFuture;
- import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
- import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
- import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
- import org.elasticsearch.client.Client;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
- import org.springframework.data.elasticsearch.core.query.IndexQuery;
- import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
- import com.sf.heros.mq.consumer.utils.APP;
- import com.sf.heros.mq.consumer.vo.BrandCaseInfo;
- import com.sf.heros.mq.consumer.vo.NewsInfo;
- import com.sf.heros.mq.consumer.vo.TaskInfo;
- import com.sf.heros.mq.consumer.vo.UserInfo;
- /**
- * @author seaphy
- * @date 2014-5-4
- */
- public class ElasticsearchService {
- private static final Logger logger = Logger.getLogger(ElasticsearchService.class);
- @Autowired
- private ElasticsearchTemplate elasticsearchTemplate;
- @Autowired
- private Client esClient;
- public void init() {
- if (!elasticsearchTemplate.indexExists(APP.ESProp.INDEX_NAME)) {
- elasticsearchTemplate.createIndex(APP.ESProp.INDEX_NAME);
- }
- elasticsearchTemplate.putMapping(TaskInfo.class);
- elasticsearchTemplate.putMapping(NewsInfo.class);
- }
- public boolean update(List<TaskInfo> taskInfoList) {
- List<IndexQuery> queries = new ArrayList<IndexQuery>();
- for (TaskInfo taskInfo : taskInfoList) {
- IndexQuery indexQuery = new IndexQueryBuilder().withId(taskInfo.getTaskId()).withObject(taskInfo).build();
- queries.add(indexQuery);
- }
- elasticsearchTemplate.bulkIndex(queries);
- return true;
- }
- public boolean insertOrUpdateTaskInfo(List<TaskInfo> taskInfoList) {
- List<IndexQuery> queries = new ArrayList<IndexQuery>();
- for (TaskInfo taskInfo : taskInfoList) {
- IndexQuery indexQuery = new IndexQueryBuilder().withId(taskInfo.getTaskId()).withObject(taskInfo).build();
- queries.add(indexQuery);
- }
- elasticsearchTemplate.bulkIndex(queries);
- return true;
- }
- public boolean insertOrUpdateNewsInfo(List<NewsInfo> newsInfos) {
- List<IndexQuery> queries = new ArrayList<IndexQuery>();
- for (NewsInfo newsInfo : newsInfos) {
- IndexQuery indexQuery = new IndexQueryBuilder().withId(newsInfo.getNewsId()).withObject(newsInfo).build();
- queries.add(indexQuery);
- }
- elasticsearchTemplate.bulkIndex(queries);
- return true;
- }
- public boolean insertOrUpdateNewsInfo(NewsInfo newsInfo) {
- try {
- IndexQuery indexQuery = new IndexQueryBuilder().withId(newsInfo.getNewsId()).withObject(newsInfo).build();
- elasticsearchTemplate.index(indexQuery);
- return true;
- } catch (Exception e) {
- logger.error("insert or update news info error.", e);
- return false;
- }
- }
- public boolean insertOrUpdateTaskInfo(TaskInfo taskInfo) {
- try {
- IndexQuery indexQuery = new IndexQueryBuilder().withId(taskInfo.getTaskId()).withObject(taskInfo).build();
- elasticsearchTemplate.index(indexQuery);
- return true;
- } catch (Exception e) {
- logger.error("insert or update task info error.", e);
- return false;
- }
- }
- public boolean insertOrUpdateUserInfo(UserInfo userInfo) {
- try {
- IndexQuery indexQuery = new IndexQueryBuilder().withId(userInfo.getUserId()).withObject(userInfo).build();
- elasticsearchTemplate.index(indexQuery);
- return true;
- } catch (Exception e) {
- logger.error("insert or update user info error.", e);
- return false;
- }
- }
- public <T> boolean deleteById(String id, Class<T> clzz) {
- try {
- elasticsearchTemplate.delete(clzz, id);
- return true;
- } catch (Exception e) {
- logger.error("delete " + clzz + " by id " + id + " error.", e);
- return false;
- }
- }
- /**
- * 检查健康状态
- * @author 高国藩
- * @date 2015年6月15日 下午6:59:47
- * @return
- */
- public boolean ping() {
- try {
- ActionFuture<ClusterHealthResponse> health = esClient.admin().cluster().health(new ClusterHealthRequest());
- ClusterHealthStatus status = health.actionGet().getStatus();
- if (status.value() == ClusterHealthStatus.RED.value()) {
- throw new RuntimeException("elasticsearch cluster health status is red.");
- }
- return true;
- } catch (Exception e) {
- logger.error("ping elasticsearch error.", e);
- return false;
- }
- }
- public boolean insertOrUpdateBrandCaseInfo(BrandCaseInfo brandCaseInfo) {
- try {
- IndexQuery indexQuery = new IndexQueryBuilder()
- .withId(brandCaseInfo.getId()).withObject(brandCaseInfo).build();
- elasticsearchTemplate.index(indexQuery);
- return true;
- } catch (Exception e) {
- logger.error("insert or update brandcase info error.", e);
- return false;
- }
- }
- }
查询类
- 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/liyantianmin/9565012
http://blog.csdn.net/liyantianmin/article/details/51801961
Spring Data Elasticsearch的更多相关文章
- elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)
一.ES Client 简介 1. ES是一个服务,采用C/S结构 2. 回顾 ES的架构 3. ES支持的客户端连接方式 3.1 REST API ,端口 9200 这种连接方式对应于架构图中的RE ...
- Elasticsearch基本用法(2)--Spring Data Elasticsearch
Spring Data Elasticsearch是Spring Data项目下的一个子模块. 查看 Spring Data的官网:http://projects.spring.io/spring-d ...
- Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)
elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介.Java REST Client.Java Client.Spri ...
- spring data elasticsearch 使用
很久之前就安装了elasticsearch,一直没用java用过,最近看了一下spring data系列的elasticsearch,这里写一篇心得. 如果尚未安装elasticsearch,可以 参 ...
- Spring Boot + Spring Data + Elasticsearch实例
Spring Boot + Spring Data + Elasticsearch实例 学习了:https://blog.csdn.net/huangshulang1234/article/detai ...
- elasticsearch 拼音+ik分词,spring data elasticsearch 拼音分词
elasticsearch 自定义分词器 安装拼音分词器.ik分词器 拼音分词器: https://github.com/medcl/elasticsearch-analysis-pinyin/rel ...
- How to provide highlighting with Spring data elasticsearch
How to provide highlighting with Spring data elasticsearch @Test public void shouldReturnHighlighted ...
- springboot集成spring data ElasticSearch
ES支持SpringBoot使用类似于Spring Data Jpa的方式查询,使得查询更加方便. 1.依赖引入 compile “org.springframework.boot:spring-bo ...
- 031 Spring Data Elasticsearch学习笔记---重点掌握第5节高级查询和第6节聚合部分
Elasticsearch提供的Java客户端有一些不太方便的地方: 很多地方需要拼接Json字符串,在java中拼接字符串有多恐怖你应该懂的 需要自己把对象序列化为json存储 查询到结果也需要自己 ...
- SpringBoot整合Spring Data Elasticsearch
Spring Data Elasticsearch提供了ElasticsearchTemplate工具类,实现了POJO与elasticsearch文档之间的映射 elasticsearch本质也是存 ...
随机推荐
- Swift开发之 使用系统的TabbarController
使用系统的tabbar解决图片的问题. 用sb使用系统的tabbar,弄好后发现图片始终是蓝色的,并非原来的图片,后经上网查资料,问问同事,有了以下的这些代码,做个标记. AppDelegate中 f ...
- Linux基本配置和管理 3 ---- Linux命令行文本处理工具
1 文件浏览(简单回顾) 1 cat 查看文件的内容 2 more 以翻页的形式查看,但是只能向下翻页 3 less 以翻页的形式查看,但是能够支持向上和向下翻页 4 head 默认是查看前10行,但 ...
- Android中为图标加上数字--用于未读短信数提醒,待更新应用数提醒等
本文属于原创,转载请著名出处:http://flysnow.iteye.com/blog/906770 写道 在我们开发一些如短消息.应用商店等应用时,会考虑在短消息的图标上加上未读短信的数量,在应用 ...
- cocos2d-x 背景音乐播放
Code // on "init" you need to initialize your instance bool HelloWorld::init() { bool ...
- 八皇后问题 lua版
简单来讲就是如何在一个8x8的棋盘中放八个棋,让他们两两不能在同一行,同一列,同一斜线. 直接贴代码(出至:programming in lua 3 ) --棋盘大小 SIZE = --判断棋放在ro ...
- [转] nginx+FastCGI+c++
from: http://www.cnblogs.com/xiaouisme/archive/2012/08/01/2618398.html 一 安装 目的:不需支持php等.就html就行了.步骤: ...
- Android应用程序开发之图片操作(一)——Bitmap,surfaceview,imageview,Canvas
Android应用程序开发之图片操作(一)——Bitmap,surfaceview,imageview,Canvas 1,Bitmap对象的获取 首先说一下Bitmap,Bitmap是Androi ...
- vertical-align各属性对比
测试用代码 <!DOCTYPE html> <html> <head> <style> #dd { //line-height: 300px; back ...
- JavaScript—window对象使用
window对象是JavaScript浏览器对象模型中的顶层对象,包含多个常用方法和属性: 1. 打开新窗口 window.open(pageURL,name,parameters) 其中:pageU ...
- (转)dedecms代码详解 很全面
dedecms代码研究(1)开篇dedecms 相信大家一定都知道这个cms 系统,功能比较强大,有比较完善的内容发布,还有内容静态化系统,还有就是它有自己独特的标签系统和模板系统.而模板系统也是其他 ...