怎么查elasticseach 配置内存使用情况

“上善若水,水善利万物而不争。
水行者欢迎您
在Elasticsearch中,文档归属于一种类型(type),而这些类型存在于索引(index)中,我们可以画一些简单的对比图来类比传统关系型数据库
Relational DB -& Databases -& Tables -& Rows -& Columns
Elasticsearch -& Indices&& -& Types& -& Documents -& Fields
Elasticsearch集群可以包含多个索引(indices)(数据库),每一个索引可以包含多个类型(types)(表),每一个类型包含多个文档(documents)(行),然后每个文档包含多个字段(Fields)(列)。
GET /megacorp/employee/_search
&&& "query" : {
&&&&&&& "match" : {
&&&&&&&&&&& "last_name" : "Smith"
查询结果 :
查询出字段last_name中包含 Smith的全部数据
过滤器(range filter)
GET /megacorp/employee/_search
&&& "query" : {
&&&&&&& "filtered" : {
&&&&&&&&&&& "filter" : {
&&&&&&&&&&&&&&& "range" : {
&&&&&&&&&&&&&&&&&&& "age" : { "gt" : 30 } &1&
&&&&&&&&&&&&&&& }
&&&&&&&&&&& },
&&&&&&&&&&& "query" : {
&&&&&&&&&&&&&&& "match" : {
&&&&&&&&&&&&&&&&&&& "last_name" : "smith" &2&
&&&&&&&&&&&&&&& }
&&&&&&&&&&& }
&1& 这部分查询属于区间过滤器(range filter),它用于查找所有年龄大于30岁的数据&&gt为"greater than"的缩写。
&2& 这部分查询与之前的match语句(query)一致。
常用的过滤语句
term主要用于精确匹配哪些值,比如数字,日期,布尔值或&not_analyzed的字符串(未经分析的文本数据类型):
{ "term": { "age":&&& 26&&&&&&&&&& }}
&&& { "term": { "date":&& "" }}
&&& { "term": { "public": true&&&&&&&& }}
&&& { "term": { "tag":&&& "full_text"& }}
terms&过滤
&&& "terms": {
&&&&&&& "tag": [ "search", "full_text", "nosql" ]
range&过滤
&&& "range": {
&&&&&&& "age": {
&&&&&&&&&&& "gte":& 20,
&&&&&&&&&&& "lt":&& 30
exists&和&missing&过滤
&&& "exists":&& {
&&&&&&& "field":&&& "title"
&&& "bool": {
&&&&&&& "must":&&&& { "term": { "folder": "inbox" }},
&&&&&&& "must_not": { "term": { "tag":&&& "spam"& }},
&&&&&&& "should": [
&&&&&&&&&&&&&&&&&&& { "term": { "starred": true&& }},
&&&&&&&&&&&&&&&&&&& { "term": { "unread":& true&& }}
match_all&查询
&&& "match_all": {}
match&查询
&&& "match": {
&&&&&&& "tweet": "About Search"
{ "match": { "age":&&& 26&&&&&&&&&& }}
{ "match": { "date":&& "" }}
{ "match": { "public": true&&&&&&&& }}
{ "match": { "tag":&&& "full_text"& }}
multi_match&查询
&&& "multi_match": {
&&&&&&& "query":&&& "full text search",
&&&&&&& "fields":&& [ "title", "body" ]
&&& "bool": {
&&&&&&& "must":&&&& { "match": { "title": "how to make millions" }},
&&&&&&& "must_not": { "match": { "tag":&& "spam" }},
&&&&&&& "should": [
&&&&&&&&&&& { "match": { "tag": "starred" }},
&&&&&&&&&&& { "range": { "date": { "gte": "" }}}
阅读(...) 评论()elasticseach日常维护之shard治理 - 数据库当前位置:& &&&elasticseach日常维护之shard治理elasticseach日常维护之shard治理&&网友分享于:&&浏览:0次elasticseach日常维护之shard管理转自我自己的博客:/archives/687.html
elasticseach的数据分片shard,在创建索引之后,在生命周期内就不可改变了,所以在索引开始创建的时候,要根据预估的数据规模合理的设置shard数目。在集群中让shard分布均匀,可以有效的均衡集群负载,所以我们要尽量保证shard的在集群中分布均匀。
每个shard都有自己的编号,从1往后数。你可以通过
curl -XGET ‘http://192.168.1.1:9200/_cat/shards’
来查看shard分布情况:
index_1 100 p STARTED .3gb 192.168.1.1 Strongarm
index_1 100 r STARTED .3gb 192.168.1.2 Agony
index_1 109 p STARTED .7gb 192.168.1.3 Captain America
index_1 109 r STARTED .6gb 192.168.1.1 Smuggler
index_1 103 p STARTED .9gb 192.168.1.2 Alyssa Moy
index_1 103 r STARTED .9gb 192.168.1.1 Chi Demon
index_1 169 r STARTED .4gb 192.168.1.2 Milos Masaryk
index_1 169 p STARTED .3gb 192.168.1.1 Sergeant Fury
index_1 55 r STARTED .2gb 192.168.1.3 Milos Masaryk
index_1 55 p STARTED .1gb 192.168.1.3 Whiteout
index_1 214 r STARTED gb 192.168.1.1 Mekano
index_1 214 p STARTED gb 192.168.1.2 Sergeant Fury
index_1 97 r STARTED .7gb 192.168.1.1 Pathway
index_1 97 p STARTED .7gb 192.168.1.2 Mekano
p 就表示是主分片 primary shard
r 就表示是副本分片 replica shard
分片数和副本个数在创建索引的时候都可以设置,副本的个数在创建索引之后可以随时更改。
elasticsearch的shard分布是根据集群设置的比重进行分配的,你可以设置:
curl -XPUT ‘http://192.168.1.1:9200/_cluster/settings?pretty=true’ -d ‘{
“transient” : {
“cluster.routing.allocation.balance.shard” : 0.33
“cluster.routing.allocation.balance.index” : 0.33
“cluster.routing.allocation.balance.primary” : 0.34
“cluster.routing.allocation.balance.threshold” : 1
elasticsearch内部计算公式是:
weightindex(node, index) = indexBalance * (node.numShards(index) – avgShardsPerNode(index))
weightnode(node, index) = shardBalance * (node.numShards() – avgShardsPerNode)
weightprimary(node, index) = primaryBalance * (node.numPrimaries() – avgPrimariesPerNode)
weight(node, index) = weightindex(node, index) + weightnode(node, index) + weightprimary(node, index)
如果计算最后的weight(node, index)大于threshold, 就会发生shard迁移。
注:cluster.routing.allocation.balance.primary 在1.3.8版本之后被废弃了。
在一个已经创立的集群里,shard的分布总是均匀的。但是当你扩容节点的时候,你会发现,它总是先移动replica shard到新节点。
这样就导致新节点全部分布的全是副本,主shard几乎全留在了老的节点上。
cluster.routing.allocation.balance参数,比较难找到合适的比例。
建议一种方式是在扩容的时候,设置cluster.routing.allocation.enable=primaries。指只允许移动主shard。
当你发现shard数已经迁移了一半的时候,改回cluster.routing.allocation.enable=all。这样后面的全迁移的是副本shard。
扩容之后,shard和主shard的分布还是均匀的。
curl -XPUT ‘http://192.168.1.1:9200/_cluster/settings’ -d ‘{
“transient” : {
“cluster.routing.allocation.enable” : “primaries”
那如果shard分布已经不均匀了,也可以手动进行shard迁移。
curl -XPOST ‘http://192.168.1.1:9200/_cluster/reroute’ -d ‘{
“commands” : [ {
“move” :
“index” : “index_1″, “shard” : 23,
“from_node” : “192.168.1.1”, “to_node” : “192.168.1.2”
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 1234567891011 Copyright & &&版权所有ElasticSearch使用教程四(ElasticSearch查询详解)
王军华的个人博客
90后,专注于.NET下的Web开发技术。擅长EF、MVC、WebApi、ElasticSearch、Mongodb。热爱互联网行业!
ElasticSearch使用教程四(ElasticSearch查询详解)
编辑:王军华浏览(31014)
关键字词:
邮箱(不会被公开,如果有回复内容会发送到你的邮箱)
评论时间: 17:34:29
评论内容:term使用不了,请问可能是什么原因呢
评论时间: 17:37:13
评论内容:初学者,知道原因了,应该是分词里面没有对应的值得原因。不过还是谢谢您的文章
回复时间: 17:03:41
回复内容:嗯嗯,不用客气,愿我的文章能给您带来点滴的帮助。elasticsearch(10)
Spring(25)
elasticsearch服务下载包括其中插件和分词
http://download.csdn.net/detail/u09619
app.properties
elasticsearch.esNodes=localhost:9300
elasticsearch.cluster.name=heroscluster
&?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& /&
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 name=&elasticsearchService& class=&com.sf.heros.mq.consumer.service.ElasticsearchService&
init-method=&init& /&
&bean name=&es& class=&com.sf.daidongxi.web.service.ElasticsearchService&&&/bean&
&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&
&finalName&elasticsearch&/finalName&
&/project&
Java.class
package com.sf.heros.mq.consumer.
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.D
import org.springframework.data.elasticsearch.annotations.F
import org.springframework.data.elasticsearch.annotations.FieldI
import org.springframework.data.elasticsearch.annotations.FieldT
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 {
@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 taskC
@Field(type = FieldType.String, indexAnalyzer=&ik&, searchAnalyzer=&ik&, store = true)
private String taskA
@Field(type = FieldType.String, indexAnalyzer=&ik&, searchAnalyzer=&ik&, store = true)
private String taskT
@Field(type = FieldType.Integer, index = FieldIndex.not_analyzed, store = true)
private Integer taskS
@Field(type = FieldType.String, index = FieldIndex.not_analyzed, store = true)
private String updateT
@Field(type = FieldType.String, indexAnalyzer=&ik&, searchAnalyzer=&ik&, store = true)
private String userNickN
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 taskC
public void setTaskContent(String taskContent) {
this.taskContent = taskC
public String getTaskArea() {
return taskA
public void setTaskArea(String taskArea) {
this.taskArea = taskA
public String getTaskTags() {
return taskT
public void setTaskTags(String taskTags) {
this.taskTags = taskT
public Integer getTaskState() {
return taskS
public void setTaskState(Integer taskState) {
this.taskState = taskS
public String getUpdateTime() {
return updateT
public void setUpdateTime(String updateTime) {
this.updateTime = updateT
public String getUserNickName() {
return userNickN
public void setUserNickName(String userNickName) {
this.userNickName = userNickN
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 = taskC
this.taskArea = taskA
this.taskTags = taskT
this.taskState = taskS
this.updateTime = updateT
this.userNickName = userNickN
public TaskInfo() {
// TODO Auto-generated constructor stub
*@Pr锛歨eros
涓婂崍9:21:27
*@Author: seaphy
*@Copyright: 漏 2012
Inc. All rights reserved
*娉ㄦ剰锛氭湰鍐呭?浠呴檺浜庨『涓伴?熻繍鍏?徃鍐呴儴浼犻槄锛岀?姝㈠?娉勪互鍙婄敤浜庡叾浠栫殑鍟嗕笟鐩?殑
package com.sf.heros.mq.consumer.
import java.util.ArrayL
import java.util.L
import org.apache.log4j.L
import org.elasticsearch.action.ActionF
import org.elasticsearch.action.admin.cluster.health.ClusterHealthR
import org.elasticsearch.action.admin.cluster.health.ClusterHealthR
import org.elasticsearch.action.admin.cluster.health.ClusterHealthS
import org.elasticsearch.client.C
import org.springframework.beans.factory.annotation.A
import org.springframework.data.elasticsearch.core.ElasticsearchT
import org.springframework.data.elasticsearch.core.query.IndexQ
import org.springframework.data.elasticsearch.core.query.IndexQueryB
import com.sf.heros.mq.consumer.utils.APP;
import com.sf.heros.mq.consumer.vo.BrandCaseI
import com.sf.heros.mq.consumer.vo.NewsI
import com.sf.heros.mq.consumer.vo.TaskI
import com.sf.heros.mq.consumer.vo.UserI
* @author seaphy
public class ElasticsearchService {
private static final Logger logger = Logger.getLogger(ElasticsearchService.class);
@Autowired
private ElasticsearchTemplate elasticsearchT
@Autowired
private Client esC
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);
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);
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);
public boolean insertOrUpdateNewsInfo(NewsInfo newsInfo) {
IndexQuery indexQuery = new IndexQueryBuilder().withId(newsInfo.getNewsId()).withObject(newsInfo).build();
elasticsearchTemplate.index(indexQuery);
} catch (Exception e) {
logger.error(&insert or update news info error.&, e);
public boolean insertOrUpdateTaskInfo(TaskInfo taskInfo) {
IndexQuery indexQuery = new IndexQueryBuilder().withId(taskInfo.getTaskId()).withObject(taskInfo).build();
elasticsearchTemplate.index(indexQuery);
} catch (Exception e) {
logger.error(&insert or update task info error.&, e);
public boolean insertOrUpdateUserInfo(UserInfo userInfo) {
IndexQuery indexQuery = new IndexQueryBuilder().withId(userInfo.getUserId()).withObject(userInfo).build();
elasticsearchTemplate.index(indexQuery);
} catch (Exception e) {
logger.error(&insert or update user info error.&, e);
public &T& boolean deleteById(String id, Class&T& clzz) {
elasticsearchTemplate.delete(clzz, id);
} catch (Exception e) {
logger.error(&delete & + clzz + & by id & + id + & error.&, e);
* 检查健康状态
* @author 高国藩
* @date 日 下午6:59:47
public boolean ping() {
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.&);
} catch (Exception e) {
logger.error(&ping elasticsearch error.&, e);
public boolean insertOrUpdateBrandCaseInfo(BrandCaseInfo brandCaseInfo) {
IndexQuery indexQuery = new IndexQueryBuilder()
.withId(brandCaseInfo.getId()).withObject(brandCaseInfo).build();
elasticsearchTemplate.index(indexQuery);
} catch (Exception e) {
logger.error(&insert or update brandcase info error.&, e);
package com.sf.daidongxi.web.
import java.util.ArrayL
import java.util.C
import java.util.L
import java.util.M
import mons.lang.StringU
import org.apache.log4j.L
import org.apache.lucene.queries.TermF
import org.apache.lucene.queryparser.xml.builders.FilteredQueryB
import org.elasticsearch.action.search.SearchRequestB
import org.elasticsearch.action.search.SearchR
import org.elasticsearch.action.search.SearchT
import org.elasticsearch.client.C
import org.elasticsearch.index.query.BoolFilterB
import org.elasticsearch.index.query.FilterB
import org.elasticsearch.index.query.FilterB
import org.elasticsearch.index.query.MatchQueryB
import org.elasticsearch.index.query.QueryB
import org.elasticsearch.index.query.QueryB
import org.elasticsearch.index.query.QueryStringQueryB
import org.elasticsearch.index.query.RangeFilterB
import org.elasticsearch.index.query.TermsQueryB
import org.elasticsearch.search.SearchH
import org.elasticsearch.search.sort.SortO
import org.springframework.beans.factory.InitializingB
import org.springframework.beans.factory.annotation.A
import org.springframework.data.elasticsearch.core.ElasticsearchT
import sun.misc.C
public class ElasticsearchService implements InitializingBean {
private static final Logger logger = Logger
.getLogger(ElasticsearchService.class);
@Autowired
private String esIndexName = &heros&;
@Autowired
private ElasticsearchTemplate elasticsearchT
@Autowired
private Client esC
/** 查询 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());
* 查询得到结果为Map集合
* @author 高国藩
* @date 日 下午8:46:13
* @param type
* @param fields
* @param content
* @param sortField
排序的字段
* @param order
排序的規則
* @param from
* @param size
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());
* 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());
* 多个文字记不清是那些字,然后放进去查询
* @author 高国藩
* @date 日 上午9:56:08
* @param type
* @param field
* @param countents
* @param sortField
* @param order
* @param from
* @param size
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());
* Filters 查询方式
* 1. 1)QueryBuilders.queryString 获得基本查询
2)FilteredQueryBuilder query = QueryBuilders.filteredQuery(queryString,FilterBuilder)
3)通过上面封装成为查询,将这个query插入到reqBuilder中;完成操作
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 日 下午10:06:05
* @param type
* @param field
* @param countents
* @param sortField
* @param order
* @param from
* @param size
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());
public void afterPropertiesSet() throws Exception {
System.out.println(&init...&);
package com.sf.heros.mq.
import java.util.ArrayL
import java.util.C
import java.util.HashS
import java.util.L
import java.util.M
import org.apache.log4j.L
import org.elasticsearch.search.sort.SortO
import org.junit.T
import org.springframework.context.support.ClassPathXmlApplicationC
import com.sf.heros.mq.consumer.service.ElasticsearchS
import com.sf.heros.mq.consumer.utils.APP;
import com.sf.heros.mq.consumer.vo.TaskI
public class AppMain {
private static final Logger logger = Logger.getLogger(AppMain.class);
public void start() {
ClassPathXmlApplicationContext context =
context = new ClassPathXmlApplicationContext(&classpath:app.xml&);
} catch (Exception e) {
logger.error(&An error occurred, applicationContext will close.&, e);
if (context != null) {
context.close();
logger.error(APP.CLOSED_MSG);
* @author 高国藩
* @date 日 上午10:14:21
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, &&, &霍华德&));
service.insertOrUpdateTaskInfo(taskInfoList);
* @author 高国藩
* @date 日 上午10:14:21
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,
for (int i = 0; i & al.size(); i++) {
System.out.println(al.get(i));
* filter查询
* @author 高国藩
* @date 日 上午10:14:21
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
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:72755次
积分:2095
积分:2095
排名:第18617名
原创:105篇
转载:227篇
(1)(2)(1)(8)(6)(17)(41)(11)(15)(6)(11)(12)(19)(20)(11)(22)(7)(1)(43)(37)(24)(1)(2)(1)(1)(1)(5)(4)(1)

我要回帖

更多关于 royal elastics 的文章

 

随机推荐