ElasticSearch使用代码
package elasticsearch01; import static org.junit.Assert.*; import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.collect.ImmutableList;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Before;
import org.junit.Test; import com.fasterxml.jackson.databind.ObjectMapper; public class EsTest { String index = "crxy";
String type = "emp";
TransportClient transportClient;
/**
* 相当于初始化方法,在执行其他测试类之前会首先被调用
* @throws Exception
*/
@Before
public void before() throws Exception {
transportClient = new TransportClient();
TransportAddress transportAddress = new InetSocketTransportAddress("192.168.1.170", 9300);
transportClient.addTransportAddress(transportAddress);
} /**
* 自己写测试类的时候可以用这个
* @throws Exception
*/
@Test
public void test1() throws Exception { GetResponse response = transportClient.prepareGet(index , type , "1").execute().actionGet();
String sourceAsString = response.getSourceAsString();
System.out.println(sourceAsString);
} /**
* 工作中使用-1
* @throws Exception
*/
@Test
public void test2() throws Exception {
Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elasticsearch").build();
TransportClient transportClient = new TransportClient(settings);
TransportAddress transportAddress = new InetSocketTransportAddress("192.168.1.170", 9300);
TransportAddress transportAddress1 = new InetSocketTransportAddress("192.168.1.171", 9300);
transportClient.addTransportAddresses(transportAddress,transportAddress1);
GetResponse response = transportClient.prepareGet(index , type , "1").execute().actionGet();
String sourceAsString = response.getSourceAsString();
System.out.println(sourceAsString);
} /**
* 工作中使用-2
* @throws Exception
*/
@Test
public void test3() throws Exception {
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", "elasticsearch")
.put("client.transport.sniff", true)//自动嗅探机制,可以自动链接集群中的其他节点
.build();
TransportClient transportClient = new TransportClient(settings);
TransportAddress transportAddress = new InetSocketTransportAddress("192.168.1.170", 9300);
TransportAddress transportAddress1 = new InetSocketTransportAddress("192.168.1.171", 9300);
transportClient.addTransportAddresses(transportAddress,transportAddress1); ImmutableList<DiscoveryNode> connectedNodes = transportClient.connectedNodes();
for (DiscoveryNode discoveryNode : connectedNodes) {
System.out.println(discoveryNode.getHostAddress());
} } /**
* index -json格式
* @throws Exception
*/
@Test
public void test4() throws Exception {
String source = "{\"name\":\"mm\",\"age\":\"19\"}";
IndexResponse response = transportClient.prepareIndex(index, type, "2").setSource(source).execute().actionGet();
String id = response.getId();
System.out.println(id);
} /**
* index - map
* @throws Exception
*/
@Test
public void test5() throws Exception {
HashMap<String, Object> source = new HashMap<String, Object>();
source.put("name", "ww");
source.put("age", 20); IndexResponse response = transportClient.prepareIndex(index, type).setSource(source).execute().actionGet();
String id = response.getId();
System.out.println(id); } /**
* index - 对象
* @throws Exception
*/
@Test
public void test6() throws Exception {
User user = new User();
user.setAge(29);
user.setName("nn"); ObjectMapper objectMapper = new ObjectMapper();
IndexResponse response = transportClient.prepareIndex(index, type, "4").setSource(objectMapper.writeValueAsString(user)).execute().actionGet();
String id = response.getId();
System.out.println(id); } /**
* index -eshelp
* @throws Exception
*/
@Test
public void test7() throws Exception {
XContentBuilder endObject = XContentFactory.jsonBuilder().startObject().field("name", "lk").field("age", 28).endObject();
IndexResponse response = transportClient.prepareIndex(index, type, "5").setSource(endObject).get();
String id = response.getId();
System.out.println(id);
} /**
* get
* @throws Exception
*/
@Test
public void test8() throws Exception {
GetResponse response = transportClient.prepareGet(index, type, "5").get();
System.out.println(response.getSourceAsString());
} /**
* update
* @throws Exception
*/
@Test
public void test9() throws Exception {
XContentBuilder endObject = XContentFactory.jsonBuilder().startObject().field("name","zs").endObject(); UpdateResponse response = transportClient.prepareUpdate(index, type, "5").setDoc(endObject).get();
System.out.println(response.getVersion()); } /**
* upsert
* @throws Exception
*/
@Test
public void test10() throws Exception {
UpdateRequest request = new UpdateRequest();
request.index(index);
request.type(type);
request.id("6"); XContentBuilder endObject = XContentFactory.jsonBuilder().startObject().field("name", "aa").endObject();
request.doc(endObject); XContentBuilder endObject2 = XContentFactory.jsonBuilder().startObject().field("name", "crxy").field("age", 10).endObject();
request.upsert(endObject2); UpdateResponse response = transportClient.update(request ).get(); System.out.println(response.getVersion());
} /**
* 删除
* @throws Exception
*/
@Test
public void test11() throws Exception {
DeleteResponse response = transportClient.prepareDelete(index, type, "6").get();
System.out.println(response.getVersion());
} /**
* 删除
* @throws Exception
*/
@Test
public void test11_1() throws Exception {
DeleteByQueryResponse response = transportClient.prepareDeleteByQuery(index).setQuery(QueryBuilders.matchAllQuery()).get();
} /**
* 查询索引库中数据的总量,类似于sql中的select *
* @throws Exception
*/
@Test
public void test12() throws Exception {
CountResponse response = transportClient.prepareCount(index).get();
System.out.println(response.getCount());
} /**
* 批量操作 bulk
* @throws Exception
*/
@Test
public void test13() throws Exception {
BulkRequestBuilder bulkBuilder = transportClient.prepareBulk();
IndexRequest indexrequest = new IndexRequest(index,type,"6");
XContentBuilder endObject = XContentFactory.jsonBuilder().startObject().field("name", "sss").field("age111", 001).endObject();
indexrequest.source(endObject);
//TODO--- bulkBuilder.add(indexrequest );
DeleteRequest deleteRequest = new DeleteRequest(index,type,"5");
bulkBuilder.add(deleteRequest); BulkResponse bulkResponse = bulkBuilder.get(); if(bulkResponse.hasFailures()){
System.out.println("执行失败:");
BulkItemResponse[] items = bulkResponse.getItems();
for (BulkItemResponse bulkItemResponse : items) {
String failureMessage = bulkItemResponse.getFailureMessage();
System.out.println(failureMessage);
}
}else{
System.out.println("正常执行");
} }
/**
* 查询,排序,分页,高亮,过滤
* lt:小于
* lte:小于等于
* gt:大于
* gte:大于等于
* @throws Exception
*/
@Test
public void test14() throws Exception {
SearchResponse searchResponse = transportClient.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(QueryBuilders.matchQuery("name", "zs"))
//.setPostFilter(FilterBuilders.rangeFilter("age").gt(20).lte(28))
.setFrom(0)
.setSize(10)
.addHighlightedField("name")
.setHighlighterPreTags("<font color='red'>")
.setHighlighterPostTags("</font>")
.addSort("age", SortOrder.DESC)
.get(); SearchHits hits = searchResponse.getHits();
long totalHits = hits.getTotalHits();
System.out.println("总数:"+totalHits); for (SearchHit searchHit : hits) {
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField highlightField = highlightFields.get("name");
Text[] fragments = highlightField.fragments();
System.out.println(searchHit.getSourceAsString());
for (Text text : fragments) {
System.out.println("高亮内容"+text);
}
}
} /**
* 类似于这个select count(*),name from table group by name;
* @throws Exception
*/
@Test
public void test15() throws Exception {
SearchResponse searchResponse = transportClient.prepareSearch(index)
.setTypes(type)
.addAggregation(AggregationBuilders.terms("nameterm").field("name").size(0)).get(); Terms terms = searchResponse.getAggregations().get("nameterm"); List<Bucket> buckets = terms.getBuckets();
for (Bucket bucket : buckets) {
System.out.println(bucket.getKey()+"--->"+bucket.getDocCount());
}
} /**
* 类似于select sum(age),name from table group by name;
* @throws Exception
*/
@Test
public void test16() throws Exception {
SearchResponse searchResponse = transportClient.prepareSearch(index)
.setTypes(type)
.addAggregation(AggregationBuilders.terms("nameterm").field("name").
subAggregation(AggregationBuilders.sum("agesum").field("age")).size(0)).get(); Terms terms = searchResponse.getAggregations().get("nameterm"); List<Bucket> buckets = terms.getBuckets();
for (Bucket bucket : buckets) {
Sum sum = bucket.getAggregations().get("agesum"); System.out.println(bucket.getKey()+"--->"+sum.getValue());
}
} }
ElasticSearch使用代码的更多相关文章
- elasticsearch远程代码执行漏洞告警
es版本:1.7.2 最近在做es项目的时候出现,启动es一段时间系统就会报警,结果查询了一下,原来是es的漏洞: 官网描述: 大致意思就是: 漏洞出现在脚本查询模块,默认搜索引擎支持使用脚本代码(M ...
- Elasticsearch 统计代码例子
aggs avg 平均数 最近15分钟的平均访问时间,upstream_time_ms是每次访问时间,单位毫秒 { "query": { "filtered": ...
- Elasticsearch 的坑爹事——记录一次mapping field修改过程
Elasticsearch 的坑爹事 本文记录一次Elasticsearch mapping field修改过程 团队使用Elasticsearch做日志的分类检索分析服务,使用了类似如下的_mapp ...
- elasticsearch Java API汇总
http://blog.csdn.net/changong28/article/details/38445805#comments 3.1 集群的连接 3.1.1 作为Elasticsearch节点 ...
- Elasticsearch就这么简单
一.前言 最近有点想弄一个站内搜索的功能,之前学过了Lucene,后来又听过Solr这个名词.接着在了解全文搜索的时候就发现了Elasticsearch这个,他也是以Lucene为基础的. 我去搜了几 ...
- 使用PHP操作ElasticSearch
如何搭建ES环境和使用CURL操作可以参考我的另一篇文章:ElasticSearch尝试 网上很多关于ES的例子都过时了,版本很久,这篇文章的测试环境是ES6.5 通过composer 安装 comp ...
- 如何用 Node.js 和 Elasticsearch 构建搜索引擎
Elasticsearch 是一款开源的搜索引擎,由于其高性能和分布式系统架构而备受关注.本文将讨论其关键特性,并手把手教你如何用它创建 Node.js 搜索引擎. Elasticsearch 概述 ...
- Elasticsearch 的坑爹事——记录一次mapping field修改过程(转)
原文:http://www.cnblogs.com/Creator/p/3722408.html 本文记录一次Elasticsearch mapping field修改过程 团队使用Elasticse ...
- (转)Elasticsearch 的坑爹事——记录一次mapping field修改过程
Elasticsearch 的坑爹事 本文记录一次Elasticsearch mapping field修改过程 团队使用Elasticsearch做日志的分类检索分析服务,使用了类似如下的_mapp ...
随机推荐
- Redis监控技巧总结
Redis 监控最直接的方法当然就是使用系统提供的 info 命令来做了,你只需要执行下面一条命令,就能获得 Redis 系统的状态报告. redis-cli info 内存使用 如果 Redis 使 ...
- [svc]免费证书认证
1.申请免费域名(12个月) freenom.com 2.申请免费证书(3个月) git clone https://github.com/letsencrypt/letsencrypt cd let ...
- [Linux] 一次SSH认证失败引发的关于通过日志查错误的思考
一.缘由: 早上在用SSH公钥认证打通所有的机器,有一台机器在完成一些列操作后密钥登陆失败,其他机器一切正常. 错误如下:Public-key authentication with the serv ...
- The DiskSpd Storage Performance Tool
https://enterpriseitnotes.wordpress.com/2013/05/31/understanding-ios-iops-and-outstanding-ios/ https ...
- <实战> 通过分析Heap Dump 来了解 Memory Leak ,Retained Heap,Shallow Heap
引入: 最近在和别的团队的技术人员聊天,发现很多人对于堆的基本知识都不太熟悉,所以他们不能很好的检测出memory leak问题,这里就用一个专题来讲解如何通过分析heap dump文件来查找memo ...
- Windows mobile 下读取手机SIM卡信息(转)
Windows mobile 下读取手机SIM卡信息 c#改善 Windows mobile 下读取手机SIM卡信息
- Echart的基础开发模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- MySQL修改root密码的多种方法(转)
http://jingyan.baidu.com/article/0320e2c198ad5f1b87507bc8.html ********************************* 方法1 ...
- LeetCode: Letter Combinations of a Phone Number 解题报告
Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations ...
- FreeRTOS 低功耗之待机模式
STM32F103 如何进入待机模式在 FreeRTOS 系统中,让 STM32 进入待机模式比较容易,调用固件库函数PWR_EnterSTANDBYMode 即可. STM32F103 如何退出待机 ...