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使用代码的更多相关文章

  1. elasticsearch远程代码执行漏洞告警

    es版本:1.7.2 最近在做es项目的时候出现,启动es一段时间系统就会报警,结果查询了一下,原来是es的漏洞: 官网描述: 大致意思就是: 漏洞出现在脚本查询模块,默认搜索引擎支持使用脚本代码(M ...

  2. Elasticsearch 统计代码例子

    aggs avg 平均数 最近15分钟的平均访问时间,upstream_time_ms是每次访问时间,单位毫秒 { "query": { "filtered": ...

  3. Elasticsearch 的坑爹事——记录一次mapping field修改过程

    Elasticsearch 的坑爹事 本文记录一次Elasticsearch mapping field修改过程 团队使用Elasticsearch做日志的分类检索分析服务,使用了类似如下的_mapp ...

  4. elasticsearch Java API汇总

    http://blog.csdn.net/changong28/article/details/38445805#comments 3.1 集群的连接 3.1.1 作为Elasticsearch节点 ...

  5. Elasticsearch就这么简单

    一.前言 最近有点想弄一个站内搜索的功能,之前学过了Lucene,后来又听过Solr这个名词.接着在了解全文搜索的时候就发现了Elasticsearch这个,他也是以Lucene为基础的. 我去搜了几 ...

  6. 使用PHP操作ElasticSearch

    如何搭建ES环境和使用CURL操作可以参考我的另一篇文章:ElasticSearch尝试 网上很多关于ES的例子都过时了,版本很久,这篇文章的测试环境是ES6.5 通过composer 安装 comp ...

  7. 如何用 Node.js 和 Elasticsearch 构建搜索引擎

    Elasticsearch 是一款开源的搜索引擎,由于其高性能和分布式系统架构而备受关注.本文将讨论其关键特性,并手把手教你如何用它创建 Node.js 搜索引擎. Elasticsearch 概述 ...

  8. Elasticsearch 的坑爹事——记录一次mapping field修改过程(转)

    原文:http://www.cnblogs.com/Creator/p/3722408.html 本文记录一次Elasticsearch mapping field修改过程 团队使用Elasticse ...

  9. (转)Elasticsearch 的坑爹事——记录一次mapping field修改过程

    Elasticsearch 的坑爹事 本文记录一次Elasticsearch mapping field修改过程 团队使用Elasticsearch做日志的分类检索分析服务,使用了类似如下的_mapp ...

随机推荐

  1. System V 共享内存区

    1.概述 系统调用mmap通过映射一个普通文件实现共享内存.System V 则是通过映射特殊文件系统shm中的文件实现进程间的共享内存通信.也就是说,每个共享内存区域对应特殊文件系统shm中的一个文 ...

  2. Android github上开源项目、酷炫的交互动画和视觉效果地址集合

    Android上开源的酷炫的交互动画和视觉效果:http://blog.csdn.net/u013278099/article/details/50323689 Awesome-android-ui: ...

  3. C# 动态获取代码所在行号

    通过System.Diagnostics.StackTrace获取代码所在行号和文件信息 获取行号信息 /// <summary> /// Get line number of code ...

  4. es6编写generator报错

    首先babel基础包(不安装额外东西)并不是支持完整的es6语言 自己写的如下代码 let generator = function* () { ; ,,]; ; }; var gen = gener ...

  5. ny655 光棍的yy 大数处理

    光棍的yy 时间限制:1000 ms  |  内存限制:65535 KB 难度:2 描述 yy经常遇见一个奇怪的事情,每当他看时间的时候总会看见11:11,这个很纠结啊. 现在给你m个1,你可以把2个 ...

  6. gulp-uglify的使用

    gulp教程之gulp-uglify 简介: 使用gulp-uglify压缩javascript文件,减小文件大小. 1.安装nodejs/全局安装gulp/项目安装gulp/创建package.js ...

  7. 技术blog链接

    http://www.cnblogs.com/anrainie/ 蔡羽 基础知识漫谈 http://blog.csdn.net/ioio_jy 姜晔的技术专栏 从苏宁电器到卡巴斯基

  8. 国际化的工具类ognl utils

    package yycg.util; import java.io.Serializable;import java.text.MessageFormat;import java.util.Array ...

  9. 将struts的jar包拷贝到WEB-INF/lib导致eclipse中配置好的javadoc失效

    我通过这个步骤导入了struts的jar包并且配置好了javadoc,且亲测可用: http://www.cnblogs.com/qrlozte/p/3173805.html 但是当我把struts的 ...

  10. flask中的g、add_url_rule、send_from_directory、static_url_path、static_folder的用法

    Flask中的g对象是个很好的东西,主要用于在一个请求的过程中共享数据.可以随意给g对象添加属性来保存数据,非常的方便,下面的代码是一个使用g对象的例子.下面的这个例子会使用random随机产生一个0 ...