转自:http://www.cnblogs.com/zhangdong92/p/5192867.html
2.0之后ES的java api用法有了很大变化。在此记录一些。
java应用程序连接ES集群,笔者使用的是TransportClient,获取TransportClient的代码设计为单例模式(见getClient方法)。同时包含了设置自动提交文档的代码。注释比较详细,不再赘述。
下方另有提交文档、提交搜索请求的代码。
1、连接ES集群代码如下:
package elasticsearch;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import java.net.InetAddress;
import java.util.Date;
/**
* Created by ZhangDong on 2015/12/25.
*/
public class EsClient {
static Log log = LogFactory.getLog(EsClient.class);
// 用于提供单例的TransportClient BulkProcessor
static public TransportClient tclient = null;
static BulkProcessor staticBulkProcessor = null;
//【获取TransportClient 的方法】
public static TransportClient getClient() {
try {
if (tclient == null) {
String EsHosts = "10.10.2.1:9300,10.10.2.2:9300";
Settings settings = Settings.settingsBuilder()
.put("cluster.name", "wshare_es")//设置集群名称
.put("tclient.transport.sniff", true).build();//自动嗅探整个集群的状态,把集群中其它机器的ip地址加到客户端中
tclient = TransportClient.builder().settings(settings).build();
String[] nodes = EsHosts.split(",");
for (String node : nodes) {
if (node.length() > 0) {//跳过为空的node(当开头、结尾有逗号或多个连续逗号时会出现空node)
String[] hostPort = node.split(":");
tclient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostPort[0]), Integer.parseInt(hostPort[1])));
}
}
}//if
} catch (Exception e) {
e.printStackTrace();
}
return tclient;
}
//【设置自动提交文档】
public static BulkProcessor getBulkProcessor() {
//自动批量提交方式
if (staticBulkProcessor == null) {
try {
staticBulkProcessor = BulkProcessor.builder(getClient(),
new BulkProcessor.Listener() {
@Override
public void beforeBulk(long executionId, BulkRequest request) {
//提交前调用
// System.out.println(new Date().toString() + " before");
}
@Override
public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
//提交结束后调用(无论成功或失败)
// System.out.println(new Date().toString() + " response.hasFailures=" + response.hasFailures());
log.info( "提交" + response.getItems().length + "个文档,用时"
+ response.getTookInMillis() + "MS" + (response.hasFailures() ? " 有文档提交失败!" : ""));
// response.hasFailures();//是否有提交失败
}
@Override
public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
//提交结束且失败时调用
log.error( " 有文档提交失败!after failure=" + failure);
}
})
.setBulkActions(1000)//文档数量达到1000时提交
.setBulkSize(new ByteSizeValue(5, ByteSizeUnit.MB))//总文档体积达到5MB时提交 //
.setFlushInterval(TimeValue.timeValueSeconds(5))//每5S提交一次(无论文档数量、体积是否达到阈值)
.setConcurrentRequests(1)//加1后为可并行的提交请求数,即设为0代表只可1个请求并行,设为1为2个并行
.build();
// staticBulkProcessor.awaitClose(10, TimeUnit.MINUTES);//关闭,如有未提交完成的文档则等待完成,最多等待10分钟
} catch (Exception e) {//关闭时抛出异常
e.printStackTrace();
}
}//if
return staticBulkProcessor;
}
}
package elasticsearch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.elasticsearch.action.index.IndexRequest;
/**
* Created by ZhangDong on 2015/12/25.
*/
public class EsInsert2 {
static Log log = LogFactory.getLog(EsInsert2.class);
public static void add(String json) {
try { //EsClient.getBulkProcessor()是位于上方EsClient类中的方法
EsClient.getBulkProcessor().add(new IndexRequest("设置的index name", "设置的type name","要插入的文档的ID").source(json));//添加文档,以便自动提交
} catch (Exception e) {
log.error("add文档时出现异常:e=" + e + " json=" + json);
}
}
}
//手动 批量更新
// BulkRequestBuilder bulkRequest = tclient.prepareBulk();
// for(int i=500;i<1000;i++){
// //业务对象
// String json = "";
// IndexRequestBuilder indexRequest = tclient.prepareIndex("twitter", "tweet")
// //指定不重复的ID
// .setSource(json).setId(String.valueOf(i));
// //添加到builder中
// bulkRequest.add(indexRequest);
// }
//
// BulkResponse bulkResponse = bulkRequest.execute().actionGet();
// if (bulkResponse.hasFailures()) {
// // process failures by iterating through each bulk response item
// System.out.println(bulkResponse.buildFailureMessage());
// }
//单个文档提交
// String json = "{\"relationship\":{},\"tags\":[\"camera\",\"video\"]}";
// IndexResponse response = getClient().prepareIndex("dots", "scan", JSON.parseObject(json).getString("rid")).setSource(json).get();
// return response.toString();
3、进行搜索的代码,其中有适用于复杂搜索逻辑的BoolQuery用法,以及关键词高亮的配置、在某个字段精确搜索、全文搜索、匹配全部文档、搜索同时返回聚类信息的用法:
package service;
import elasticsearch.EsClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.springframework.stereotype.Service;
/**
* Created by ZhangDong on 2016/1/5.
*/
@Service
public class SearchService2 {
Log log = LogFactory.getLog(getClass());
public SearchResponse getSimpleSearchResponse( int page, int pagesize){
BoolQueryBuilder mustQuery = QueryBuilders.boolQuery();
mustQuery.must(QueryBuilders.matchAllQuery()); // 添加第1条must的条件 此处为匹配所有文档
mustQuery.must(QueryBuilders.matchPhraseQuery("title", "时间简史"));//添加第2条must的条件 title字段必须为【时间简史】
// ↑ 放入筛选条件(termQuery为精确搜索,大小写敏感且不支持*) 实验发现matchPhraseQuery可对中文精确匹配term
mustQuery.must(QueryBuilders.matchQuery("auther", "霍金")); // 添加第3条must的条件
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("物理")//.escape(true)//escape 转义 设为true,避免搜索[]、结尾为!的关键词时异常 但无法搜索*
.defaultOperator(QueryStringQueryBuilder.Operator.AND);//不同关键词之间使用and关系
mustQuery.must(queryBuilder);//添加第4条must的条件 关键词全文搜索筛选条件
SearchRequestBuilder searchRequestBuilder = EsClient.getClient().prepareSearch("index name").setTypes("type name")
.setQuery(mustQuery)
.addHighlightedField("*")/*星号表示在所有字段都高亮*/.setHighlighterRequireFieldMatch(false)//配置高亮显示搜索结果
.setHighlighterPreTags("<高亮前缀标签>").setHighlighterPostTags("<高亮后缀标签>");//配置高亮显示搜索结果
searchRequestBuilder = searchRequestBuilder.addAggregation(AggregationBuilders.terms("agg1(聚类返回时根据此key获取聚类结果)")
.size(1000)/*返回1000条聚类结果*/.field("要在文档中聚类的字段,如果是嵌套的则用点连接父子字段,如【person.company.name】"));
SearchResponse searchResponse = searchRequestBuilder.setFrom((page - 1) * pagesize)//分页起始位置(跳过开始的n个)
.setSize(pagesize)//本次返回的文档数量
.execute().actionGet();//执行搜索
log.info("response="+searchResponse);
return searchResponse;
}
}
4、ES中使用delete-by-query插件,DSL方式按条件删除数据的方法:
ES2.1中,默认的文档删除方式只有按ID删除方法:
curl -XDELETE 'localhost:9200/customer/external/2?pretty'
(参考:Deleting Documents | Elasticsearch Reference [2.1] | Elastic https://www.elastic.co/guide/en/elasticsearch/reference/2.1/_deleting_documents.html)
按条件删除需要安装delete-by-query插件,在线安装方式可使用命令
plugin install delete-by-query
随后会从https://download.elastic.co/elasticsearch/release/org/elasticsearch/plugin/delete-by-query/2.1.0/delete-by-query-2.1.0.zip处下载插件安装包。但是本人使用的某个ES环境是离线的,需要手动下载上述URL对应的ZIP,放置于elasticsearch-2.1.0文件夹下,与bin、config等文件夹同级,同时还要下载 https://download.elastic.co/elasticsearch/release/org/elasticsearch/plugin/delete-by-query/2.1.0/delete-by-query-2.1.0.zip.md5 校验文件放于同一位置(XXX.sha1应该也可以),使用以下命令离线安装:
bin/plugin install file:delete-by-query-2.1.0.zip
其中delete-by-query-2.1.0.zip是相对路径,绝对路径应该也可以,随后便安装成功了。
安装成功后查看,发现其实就是解压delete-by-query-2.1.0.zip的内容放置于elasticsearch-2.1.0/plugins/delete-by-query 文件夹下,猜测手动解压也可以使用。
注意:如果是ES集群,需要对每个节点都安装这个插件,而且每个节点安装后要重启ES。
使用DSL方式按条件删除文档的方法:
DELETE方式,请求 http://localhost:9200/index_name/type_name/_query http payload内容: { "query":{ "match_all":{} } } 上述query为匹配全部文档。