首页 文章 精选 留言 我的

精选列表

搜索[快速入门],共10000篇文章
优秀的个人博客,低调大师

Hexo 入门指南(一) - 简介 & 准备

Hexo是一个开源的静态博客生成器,用node.js开发,作者是台湾大学生tommy351。 为什么是博客 对于个人网站来说,没有比博客更合适的形式了。在博客中,文章才是最主要的,一切都显得主次分明,干净利落。相比之下,论坛中主题和回复鱼龙混杂,阅读体验非常差。同时,博客比论坛的数据库小很多,便于维护。 为什么是静态博客 很多人选择在虚拟主机或vps上面搭建动态博客。但是这些主机商通常“免费的不稳定,稳定的不免费”。前一段时间,我观察了我的个人博客友链上面的几个站点,一部分在十几天之后就销声匿迹了。独立博客如此麻烦的维护工作,能不能减轻一些呢?正如阮一峰前辈所说,blogger分为三个阶段。最开始,是门户博客。之后,是独立博客。最后,觉得独立博客自己管理起来费劲,便找个别人来管的空间,自己负责写就好。如果我们能够找到这样的空间,在自己保留最大控制权前提下,由别人托管,会省去不少事情。 静态博客编译之后是纯html页面,优点就是支持它的环境十分好找,例如github、gitcafe、七牛云存储等站点都支持静态页面托管,自然是我们的首选了。由于github page在国内访问较慢,这篇文章用gitcafe做示范。gitcafe是天朝本地化的github,同样提供展示页和域名绑定功能,不需要备案,就是爽。 但是静态博客并非没有缺点。动态博客更新文章时,脚本是不变的,只需要更新数据库。静态博客要频繁改动文件,不支持增量式上传的东西,比如ftp,就难于管理。此外,还要十分熟悉git各种命令,才能部署页面。 准备工作 git node.js markdown编辑器 gitcafe 域名 markdown编辑器是非必须的,只要你熟悉语法,随便一个编辑器来写都不是问题。 域名也是非必须的,gitcafe pages服务提供免费的二级域名。注册域名的教程这里就不写了。 安装 git git的客户端,本人推荐git-scm。 linux下面,在bash中键入: (Ubuntu, Debian) $ sudo apt-get install git (Fedora, Red Hat, CentOS) $ sudo yum install git windows或mac下,直接到git-scm官网下载安装。 安装 node.js linux下: $ sudo apt-get install nodejs $ sudo apt-get install npm yum同理。 windows或者mac下,直接到node.js官网下载安装。 windows还要设置环境变量,把node.js安装路径写进path里面,用半角分号分隔。 markdown 编辑器 windows下推荐markdown pad。 mac下推荐mou。 gitcafe 首先注册一个账号,之后点击查看如何使用pages服务。 相关网页 Hexo主页 Hexo github 地址 git book

优秀的个人博客,低调大师

Elasticsearch 编程API入门系列---入门1(Java Client类型、连接es集群、添加json格式的数据、添加map格式...

https://www.elastic.co/guide/en/elasticsearch/client/java-api/index.html 我这里,elasticsearch用的是2.4.X版本。 https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.4/java-docs.html 第一步:删除默认的App.java 第二步:选中后,再ctrl + n ,记住,要求自己能用快捷键,就用快捷键! 第三步:输入class,直接回车,再回车 第四步:我这里,以TestEs.java为例 第五步: 第六步:输入代码,这里不多说 通过TransportClient这个类,指定es集群中其中一台或多台机的ip地址和端口 TransportClient client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress (InetAddress.getByName("host1"), 9300)).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300)); 如果需要使用其他名称的集群(默认是elasticsearch),需要如下设置 Settings settings = Settings.settingsBuilder().put("cluster.name", "myClusterName").build(); TransportClientclient = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress (InetAddress.getByName("host1"), 9300)); 通过TransportClient这个接口,自动嗅探整个集群的状态,es会自动把集群中其它机器的ip地址加到客户端中 Settings settings = Settings.settingsBuilder().put("client.transport.sniff", true).build(); TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress (InetAddress.getByName("host1"), 9300)); 更详细,请见 Elasticsearch的Java Client类型 索引index(四种json,map,bean,es helper) IndexResponse response = client.prepareIndex("zhouls", "emp", "1").setSource().get() 查询get GetResponse response = client.prepareGet("zhouls", "emp", "1").get(); 更新update 删除delete DeleteResponse response = client.prepareDelete("zhouls", "emp", "1").execute().actionGet(); 总数count long count = client.prepareCount("zhouls").get().getCount(); 附上代码 前提 准备,开启3台机器组建的es集群进程 test1测试(连接192.168.80.10和192.168.80.11) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } test2测试(连接192.168.80.10、192.168.80.11和192.168.80.12)(即es集群) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } test3测试(连接192.168.80.10、192.168.80.11和192.168.80.12)(生产环境下建议) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } test4测试(添加json格式的数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 然后,在浏览器里,输入http://192.168.80.10:9200/_plugin/head/ test5测试(添加map格式的数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 test6测试(添加bean格式的数据) 需要引入对象,这里新建Person.java实体类 1 package zhouls.bigdata.myElasticsearch; 2 3 4 5 public class Person {//实体类 6 7 private String name; 8 private int age; 9 public String getName() { 10 return name; 11 } 12 public void setName(String name) { 13 this.name = name; 14 } 15 public int getAge() { 16 return age; 17 } 18 public void setAge(int age) { 19 this.age = age; 20 } 21 22 23 24 } 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 166 167 168 169 /** 170 * index-3 bean 171 * 实际工作中使用 172 * 使用对象的时候需要把对象中的属性转化成json字符串 173 * @throws Exception 174 */ 175 176 // <dependency> 177 // <groupId>com.fasterxml.jackson.core</groupId> 178 // <artifactId>jackson-databind</artifactId> 179 // <version>2.1.3</version> 180 // </dependency> 181 182 183 @Test 184 public void test6() throws Exception {//传入一个对象到index索引库,这里是Person对象 185 Person person = new Person(); 186 person.setName("mack"); 187 person.setAge(20); 188 189 //如果直接传入一个person对象会报错,java.lang.IllegalArgumentException,必须把对象转换成一个Json字符串,使用jackson依赖 190 //IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(person).get(); 191 192 193 ObjectMapper objectMapper = new ObjectMapper(); 194 String writeValueAsString = objectMapper.writeValueAsString(person); 195 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3") 196 .setSource(writeValueAsString) 197 .get(); 198 // IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3").setSource(objectMapper.writeValueAsString(person)).get(); 199 200 System.out.println(indexResponse.getVersion()); 201 } test7测试(添加helper格式的数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 166 167 168 169 /** 170 * index-3 bean 171 * 实际工作中使用 172 * 使用对象的时候需要把对象中的属性转化成json字符串 173 * @throws Exception 174 */ 175 176 // <dependency> 177 // <groupId>com.fasterxml.jackson.core</groupId> 178 // <artifactId>jackson-databind</artifactId> 179 // <version>2.1.3</version> 180 // </dependency> 181 182 183 @Test 184 public void test6() throws Exception {//传入一个对象到index索引库,这里是Person对象 185 Person person = new Person(); 186 person.setName("mack"); 187 person.setAge(20); 188 189 //如果直接传入一个person对象会报错,java.lang.IllegalArgumentException,必须把对象转换成一个Json字符串,使用jackson依赖 190 //IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(person).get(); 191 192 193 ObjectMapper objectMapper = new ObjectMapper(); 194 String writeValueAsString = objectMapper.writeValueAsString(person); 195 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3") 196 .setSource(writeValueAsString) 197 .get(); 198 // IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3").setSource(objectMapper.writeValueAsString(person)).get(); 199 200 System.out.println(indexResponse.getVersion()); 201 } 202 203 /** 204 * index -4 es helper 205 * 测试数据这样使用 206 * @throws Exception 207 */ 208 @Test 209 public void test7() throws Exception { 210 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 211 .startObject() 212 .field("name", "jessic") 213 .field("age", 28) 214 .endObject(); 215 216 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "4") 217 .setSource(builder) 218 .get(); 219 System.out.println(indexResponse.getVersion()); 220 } test8测试(通过id get查询数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 166 167 168 169 /** 170 * index-3 bean 171 * 实际工作中使用 172 * 使用对象的时候需要把对象中的属性转化成json字符串 173 * @throws Exception 174 */ 175 176 // <dependency> 177 // <groupId>com.fasterxml.jackson.core</groupId> 178 // <artifactId>jackson-databind</artifactId> 179 // <version>2.1.3</version> 180 // </dependency> 181 182 183 @Test 184 public void test6() throws Exception {//传入一个对象到index索引库,这里是Person对象 185 Person person = new Person(); 186 person.setName("mack"); 187 person.setAge(20); 188 189 //如果直接传入一个person对象会报错,java.lang.IllegalArgumentException,必须把对象转换成一个Json字符串,使用jackson依赖 190 //IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(person).get(); 191 192 193 ObjectMapper objectMapper = new ObjectMapper(); 194 String writeValueAsString = objectMapper.writeValueAsString(person); 195 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3") 196 .setSource(writeValueAsString) 197 .get(); 198 // IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3").setSource(objectMapper.writeValueAsString(person)).get(); 199 200 System.out.println(indexResponse.getVersion()); 201 } 202 203 /** 204 * index -4 es helper 205 * 测试数据这样使用 206 * @throws Exception 207 */ 208 @Test 209 public void test7() throws Exception { 210 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 211 .startObject() 212 .field("name", "jessic") 213 .field("age", 28) 214 .endObject(); 215 216 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "4") 217 .setSource(builder) 218 .get(); 219 System.out.println(indexResponse.getVersion()); 220 } 221 222 223 /** 224 * get 查询 225 * 通过id查询 226 * @throws Exception 227 */ 228 @Test 229 public void test8() throws Exception { 230 GetResponse getResponse = transportClient.prepareGet(index, type, "4")//查询id为4的数据 231 .get(); 232 System.out.println(getResponse.getSourceAsString()); 233 } test9测试(局部更新数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 166 167 168 169 /** 170 * index-3 bean 171 * 实际工作中使用 172 * 使用对象的时候需要把对象中的属性转化成json字符串 173 * @throws Exception 174 */ 175 176 // <dependency> 177 // <groupId>com.fasterxml.jackson.core</groupId> 178 // <artifactId>jackson-databind</artifactId> 179 // <version>2.1.3</version> 180 // </dependency> 181 182 183 @Test 184 public void test6() throws Exception {//传入一个对象到index索引库,这里是Person对象 185 Person person = new Person(); 186 person.setName("mack"); 187 person.setAge(20); 188 189 //如果直接传入一个person对象会报错,java.lang.IllegalArgumentException,必须把对象转换成一个Json字符串,使用jackson依赖 190 //IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(person).get(); 191 192 193 ObjectMapper objectMapper = new ObjectMapper(); 194 String writeValueAsString = objectMapper.writeValueAsString(person); 195 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3") 196 .setSource(writeValueAsString) 197 .get(); 198 // IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3").setSource(objectMapper.writeValueAsString(person)).get(); 199 200 System.out.println(indexResponse.getVersion()); 201 } 202 203 /** 204 * index -4 es helper 205 * 测试数据这样使用 206 * @throws Exception 207 */ 208 @Test 209 public void test7() throws Exception { 210 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 211 .startObject() 212 .field("name", "jessic") 213 .field("age", 28) 214 .endObject(); 215 216 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "4") 217 .setSource(builder) 218 .get(); 219 System.out.println(indexResponse.getVersion()); 220 } 221 222 223 /** 224 * get 查询 225 * 通过id查询 226 * @throws Exception 227 */ 228 @Test 229 public void test8() throws Exception { 230 GetResponse getResponse = transportClient.prepareGet(index, type, "4")//查询id为4的数据 231 .get(); 232 System.out.println(getResponse.getSourceAsString()); 233 } 234 235 /** 236 * 局部更新 237 * @throws Exception 238 */ 239 @Test 240 public void test9() throws Exception { 241 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 242 .startObject() 243 .field("age", 29) 244 .endObject(); 245 246 UpdateResponse updateResponse = transportClient.prepareUpdate(index, type, "4")//更新id为4的数据 247 .setDoc(builder) 248 .get(); 249 System.out.println(updateResponse.getVersion());//version打印2 数据更新 250 } test10测试(通过id来删除数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 166 167 168 169 /** 170 * index-3 bean 171 * 实际工作中使用 172 * 使用对象的时候需要把对象中的属性转化成json字符串 173 * @throws Exception 174 */ 175 176 // <dependency> 177 // <groupId>com.fasterxml.jackson.core</groupId> 178 // <artifactId>jackson-databind</artifactId> 179 // <version>2.1.3</version> 180 // </dependency> 181 182 183 @Test 184 public void test6() throws Exception {//传入一个对象到index索引库,这里是Person对象 185 Person person = new Person(); 186 person.setName("mack"); 187 person.setAge(20); 188 189 //如果直接传入一个person对象会报错,java.lang.IllegalArgumentException,必须把对象转换成一个Json字符串,使用jackson依赖 190 //IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(person).get(); 191 192 193 ObjectMapper objectMapper = new ObjectMapper(); 194 String writeValueAsString = objectMapper.writeValueAsString(person); 195 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3") 196 .setSource(writeValueAsString) 197 .get(); 198 // IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3").setSource(objectMapper.writeValueAsString(person)).get(); 199 200 System.out.println(indexResponse.getVersion()); 201 } 202 203 /** 204 * index -4 es helper 205 * 测试数据这样使用 206 * @throws Exception 207 */ 208 @Test 209 public void test7() throws Exception { 210 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 211 .startObject() 212 .field("name", "jessic") 213 .field("age", 28) 214 .endObject(); 215 216 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "4") 217 .setSource(builder) 218 .get(); 219 System.out.println(indexResponse.getVersion()); 220 } 221 222 223 /** 224 * get 查询 225 * 通过id查询 226 * @throws Exception 227 */ 228 @Test 229 public void test8() throws Exception { 230 GetResponse getResponse = transportClient.prepareGet(index, type, "4")//查询id为4的数据 231 .get(); 232 System.out.println(getResponse.getSourceAsString()); 233 } 234 235 /** 236 * 局部更新 237 * @throws Exception 238 */ 239 @Test 240 public void test9() throws Exception { 241 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 242 .startObject() 243 .field("age", 29) 244 .endObject(); 245 246 UpdateResponse updateResponse = transportClient.prepareUpdate(index, type, "4")//更新id为4的数据 247 .setDoc(builder) 248 .get(); 249 System.out.println(updateResponse.getVersion());//version打印2 数据更新 250 } 251 252 /** 253 * 删除 254 * 通过id删除 255 * @throws Exception 256 */ 257 @Test 258 public void test10() throws Exception { 259 transportClient.prepareDelete(index, type, "4")//删除id为4的数据 260 .get(); 261 } test11测试(求数据行总数) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 166 167 168 169 /** 170 * index-3 bean 171 * 实际工作中使用 172 * 使用对象的时候需要把对象中的属性转化成json字符串 173 * @throws Exception 174 */ 175 176 // <dependency> 177 // <groupId>com.fasterxml.jackson.core</groupId> 178 // <artifactId>jackson-databind</artifactId> 179 // <version>2.1.3</version> 180 // </dependency> 181 182 183 @Test 184 public void test6() throws Exception {//传入一个对象到index索引库,这里是Person对象 185 Person person = new Person(); 186 person.setName("mack"); 187 person.setAge(20); 188 189 //如果直接传入一个person对象会报错,java.lang.IllegalArgumentException,必须把对象转换成一个Json字符串,使用jackson依赖 190 //IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(person).get(); 191 192 193 ObjectMapper objectMapper = new ObjectMapper(); 194 String writeValueAsString = objectMapper.writeValueAsString(person); 195 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3") 196 .setSource(writeValueAsString) 197 .get(); 198 // IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3").setSource(objectMapper.writeValueAsString(person)).get(); 199 200 System.out.println(indexResponse.getVersion()); 201 } 202 203 /** 204 * index -4 es helper 205 * 测试数据这样使用 206 * @throws Exception 207 */ 208 @Test 209 public void test7() throws Exception { 210 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 211 .startObject() 212 .field("name", "jessic") 213 .field("age", 28) 214 .endObject(); 215 216 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "4") 217 .setSource(builder) 218 .get(); 219 System.out.println(indexResponse.getVersion()); 220 } 221 222 223 /** 224 * get 查询 225 * 通过id查询 226 * @throws Exception 227 */ 228 @Test 229 public void test8() throws Exception { 230 GetResponse getResponse = transportClient.prepareGet(index, type, "4")//查询id为4的数据 231 .get(); 232 System.out.println(getResponse.getSourceAsString()); 233 } 234 235 /** 236 * 局部更新 237 * @throws Exception 238 */ 239 @Test 240 public void test9() throws Exception { 241 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 242 .startObject() 243 .field("age", 29) 244 .endObject(); 245 246 UpdateResponse updateResponse = transportClient.prepareUpdate(index, type, "4")//更新id为4的数据 247 .setDoc(builder) 248 .get(); 249 System.out.println(updateResponse.getVersion());//version打印2 数据更新 250 } 251 252 /** 253 * 删除 254 * 通过id删除 255 * @throws Exception 256 */ 257 @Test 258 public void test10() throws Exception { 259 transportClient.prepareDelete(index, type, "4")//删除id为4的数据 260 .get(); 261 } 262 263 /** 264 * count 取总数 类似于sql中的 select count(1) from table; 265 * 求总数 266 * 类似于mysql中的select count(*) 267 */ 268 @Test 269 public void test11() throws Exception { 270 long count = transportClient.prepareCount(index)//查找索引库中的数据个数 271 .setTypes(type) 272 .get() 273 .getCount(); 274 System.out.println(count); 275 } test12测试(批量 bulk操作数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 166 167 168 169 /** 170 * index-3 bean 171 * 实际工作中使用 172 * 使用对象的时候需要把对象中的属性转化成json字符串 173 * @throws Exception 174 */ 175 176 // <dependency> 177 // <groupId>com.fasterxml.jackson.core</groupId> 178 // <artifactId>jackson-databind</artifactId> 179 // <version>2.1.3</version> 180 // </dependency> 181 182 183 @Test 184 public void test6() throws Exception {//传入一个对象到index索引库,这里是Person对象 185 Person person = new Person(); 186 person.setName("mack"); 187 person.setAge(20); 188 189 //如果直接传入一个person对象会报错,java.lang.IllegalArgumentException,必须把对象转换成一个Json字符串,使用jackson依赖 190 //IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(person).get(); 191 192 193 ObjectMapper objectMapper = new ObjectMapper(); 194 String writeValueAsString = objectMapper.writeValueAsString(person); 195 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3") 196 .setSource(writeValueAsString) 197 .get(); 198 // IndexResponse indexResponse = transportClient.prepareIndex(index, type, "3").setSource(objectMapper.writeValueAsString(person)).get(); 199 200 System.out.println(indexResponse.getVersion()); 201 } 202 203 /** 204 * index -4 es helper 205 * 测试数据这样使用 206 * @throws Exception 207 */ 208 @Test 209 public void test7() throws Exception { 210 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 211 .startObject() 212 .field("name", "jessic") 213 .field("age", 28) 214 .endObject(); 215 216 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "4") 217 .setSource(builder) 218 .get(); 219 System.out.println(indexResponse.getVersion()); 220 } 221 222 223 /** 224 * get 查询 225 * 通过id查询 226 * @throws Exception 227 */ 228 @Test 229 public void test8() throws Exception { 230 GetResponse getResponse = transportClient.prepareGet(index, type, "4")//查询id为4的数据 231 .get(); 232 System.out.println(getResponse.getSourceAsString()); 233 } 234 235 /** 236 * 局部更新 237 * @throws Exception 238 */ 239 @Test 240 public void test9() throws Exception { 241 XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 这个是ES官方提供的可以构建Json字符串的工具类. 242 .startObject() 243 .field("age", 29) 244 .endObject(); 245 246 UpdateResponse updateResponse = transportClient.prepareUpdate(index, type, "4")//更新id为4的数据 247 .setDoc(builder) 248 .get(); 249 System.out.println(updateResponse.getVersion());//version打印2 数据更新 250 } 251 252 /** 253 * 删除 254 * 通过id删除 255 * @throws Exception 256 */ 257 @Test 258 public void test10() throws Exception { 259 transportClient.prepareDelete(index, type, "4")//删除id为4的数据 260 .get(); 261 } 262 263 /** 264 * count 取总数 类似于sql中的 select count(1) from table; 265 * 求总数 266 * 类似于mysql中的select count(*) 267 */ 268 @Test 269 public void test11() throws Exception { 270 long count = transportClient.prepareCount(index)//查找索引库中的数据个数 271 .setTypes(type) 272 .get() 273 .getCount(); 274 System.out.println(count); 275 } 276 277 278 /** 279 * bulk 批量操作 适合初始化数据的时候使用,提高效率 280 * 批量操作 bulk 281 * @throws Exception 282 */ 283 @Test 284 public void test12() throws Exception { 285 BulkRequestBuilder prepareBulk = transportClient.prepareBulk(); 286 287 //for循环执行---- 288 //index请求 289 IndexRequest indexRequest = new IndexRequest(index, type, "10"); 290 indexRequest.source("{\"name\":\"zhangsan\",\"age\":17}"); 291 //delete请求 292 DeleteRequest deleteRequest = new DeleteRequest(index, type, "1"); 293 294 295 prepareBulk.add(indexRequest );//bulkBuilder中可以添加多个操作,这里一个是建立索引的操作. 296 prepareBulk.add(deleteRequest);//一个是删除的操作 297 298 //执行 bulk 299 BulkResponse bulkResponse = prepareBulk.get(); 300 if(bulkResponse.hasFailures()){//批量操作中可能有的操作会出现问题,这个地方对操作失败的处理 301 //有执行失败的 302 BulkItemResponse[] items = bulkResponse.getItems(); 303 for (BulkItemResponse bulkItemResponse : items) { 304 //获取失败信息,并打印 305 System.out.println(bulkItemResponse.getFailureMessage()); 306 } 307 }else{ 308 System.out.println("全部执行成功!"); 309 } 310 } https://www.elastic.co/guide/en/elasticsearch/client/java-api/index.html 我这里,elasticsearch用的是2.4.X版本。 https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.4/java-docs.html 第一步:删除默认的App.java 第二步:选中后,再ctrl + n ,记住,要求自己能用快捷键,就用快捷键! 第三步:输入class,直接回车,再回车 第四步:我这里,以TestEs.java为例 第五步: 第六步:输入代码,这里不多说 通过TransportClient这个类,指定es集群中其中一台或多台机的ip地址和端口 TransportClient client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress (InetAddress.getByName("host1"), 9300)).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300)); 如果需要使用其他名称的集群(默认是elasticsearch),需要如下设置 Settings settings = Settings.settingsBuilder().put("cluster.name", "myClusterName").build(); TransportClientclient = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress (InetAddress.getByName("host1"), 9300)); 通过TransportClient这个接口,自动嗅探整个集群的状态,es会自动把集群中其它机器的ip地址加到客户端中 Settings settings = Settings.settingsBuilder().put("client.transport.sniff", true).build(); TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress (InetAddress.getByName("host1"), 9300)); 更详细,请见 Elasticsearch的Java Client类型 索引index(四种json,map,bean,es helper) IndexResponse response = client.prepareIndex("zhouls", "emp", "1").setSource().get() 查询get GetResponse response = client.prepareGet("zhouls", "emp", "1").get(); 更新update 删除delete DeleteResponse response = client.prepareDelete("zhouls", "emp", "1").execute().actionGet(); 总数count long count = client.prepareCount("zhouls").get().getCount(); 附上代码 前提 准备,开启3台机器组建的es集群进程 test1测试(连接192.168.80.10和192.168.80.11) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } test2测试(连接192.168.80.10、192.168.80.11和192.168.80.12)(即es集群) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } test3测试(连接192.168.80.10、192.168.80.11和192.168.80.12)(生产环境下建议) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } test4测试(添加json格式的数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 然后,在浏览器里,输入http://192.168.80.10:9200/_plugin/head/ test5测试(添加map格式的数据) 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 test6测试(添加bean格式的数据) 需要引入对象,这里新建Person.java实体类 1 package zhouls.bigdata.myElasticsearch; 2 3 4 5 public class Person {//实体类 6 7 private String name; 8 private int age; 9 public String getName() { 10 return name; 11 } 12 public void setName(String name) { 13 this.name = name; 14 } 15 public int getAge() { 16 return age; 17 } 18 public void setAge(int age) { 19 this.age = age; 20 } 21 22 23 24 } 1 package zhouls.bigdata.myElasticsearch; 2 3 import static org.junit.Assert.*; 4 5 import java.net.InetAddress; 6 import java.util.HashMap; 7 import java.util.List; 8 9 import org.elasticsearch.action.bulk.BulkItemResponse; 10 import org.elasticsearch.action.bulk.BulkRequestBuilder; 11 import org.elasticsearch.action.bulk.BulkResponse; 12 import org.elasticsearch.action.delete.DeleteRequest; 13 import org.elasticsearch.action.get.GetResponse; 14 import org.elasticsearch.action.index.IndexRequest; 15 import org.elasticsearch.action.index.IndexResponse; 16 import org.elasticsearch.action.search.SearchResponse; 17 import org.elasticsearch.action.search.SearchType; 18 import org.elasticsearch.action.update.UpdateResponse; 19 import org.elasticsearch.client.transport.TransportClient; 20 import org.elasticsearch.cluster.node.DiscoveryNode; 21 import org.elasticsearch.common.settings.Settings; 22 import org.elasticsearch.common.transport.InetSocketTransportAddress; 23 import org.elasticsearch.common.transport.TransportAddress; 24 import org.elasticsearch.common.xcontent.XContentBuilder; 25 import org.elasticsearch.common.xcontent.XContentFactory; 26 import org.elasticsearch.index.query.MatchQueryBuilder.Operator; 27 import org.elasticsearch.index.query.QueryBuilders; 28 import org.elasticsearch.search.SearchHit; 29 import org.elasticsearch.search.SearchHits; 30 import org.elasticsearch.search.aggregations.Aggregation; 31 import org.elasticsearch.search.aggregations.AggregationBuilders; 32 import org.elasticsearch.search.aggregations.bucket.terms.Terms; 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; 34 import org.elasticsearch.search.aggregations.metrics.sum.Sum; 35 import org.elasticsearch.search.sort.SortOrder; 36 import org.junit.Before; 37 import org.junit.Test; 38 39 import com.fasterxml.jackson.databind.ObjectMapper; 40 import com.google.common.collect.ImmutableList; 41 42 public class TestEs { 43 44 //es和hadoop没关系啊,获取一个transportclient就可以操作es了 45 46 47 private TransportClient transportClient; 48 @Before//@Before和@Test的区别:每次执行都要先经过@Before,好比是,它是一个模板。 49 //before表示在执行每个test方法之前运行,常与@Test搭配使用 50 public void test0() throws Exception { 51 //获取TransportClient,来操作es 52 transportClient = TransportClient.builder().build(); 53 //需要使用9300端口 54 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 55 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 56 transportClient.addTransportAddress(transportAddress); 57 } 58 59 /** 60 * 用java代码测试的时候这样写是没有问题的,比较简单 61 * @throws Exception 62 */ 63 @Test 64 public void test1() throws Exception { 65 //获取TransportClient,来操作es 66 TransportClient transportClient = TransportClient.builder().build(); 67 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 68 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 69 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 70 transportClient.addTransportAddress(transportAddress); 71 System.out.println(transportClient.toString()); 72 } 73 74 /** 75 * 可以这样写,防止代码中指定的链接失效 76 * 但是写起来比较麻烦 77 * 在实际工作中这样写不是很靠谱,需要完善,做测试可以 78 * @throws Exception 79 */ 80 @Test 81 public void test2() throws Exception { 82 //获取TransportClient,来操作es,通过TransportClient可以和es集群交互 83 TransportClient transportClient = TransportClient.builder().build(); 84 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 85 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 86 TransportAddress transportAddress1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.11"), 9300); 87 TransportAddress transportAddress2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.12"), 9300); 88 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 89 transportClient.addTransportAddresses(transportAddress,transportAddress1,transportAddress2);//加入多个地址 90 System.out.println(transportClient.toString()); 91 } 92 93 /** 94 * 实际生产环境下面,建议这样用,加上下面这些配置信息 95 * @throws Exception 96 */ 97 @Test 98 public void test3() throws Exception { 99 //指定es的配置信息 100 Settings settings = Settings.settingsBuilder() 101 .put("cluster.name", "elasticsearch")//集群名称 102 //如果集群名称在配置文件中被修改了,那么在这需要显式定义一下 103 //es集群名称默认是 elasticsearch sniff嗅; 发现; 104 .put("client.transport.sniff", true)//开启集群的嗅探功能,只需要指定集群中一个节点信息即可获取到集群中的所有节点信息 105 //开启集群的嗅探功能,这样可以保证es会自动把集群中的其他节点信息添加到transportClient里面 106 //开启嗅探功能后 只要指定集群中的任意一个可用节点就可以了.当把代码运行之后TransportClient里面会把集群中所有节点的信息都拿到,能识别集群中的所有节点. 107 .build(); 108 109 //获取TransportClient,来操作es,//通过TransportClient可以和es集群交互 110 TransportClient transportClient = TransportClient.builder().settings(settings).build(); 111 //需要使用9300端口,指定es集群中的节点信息, 这个地方指定的端口是节点和节点之间的通信端口是9300,不是Http请求的端口9200. 112 TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.80.10"), 9300); 113 //添加节点信息,最少指定集群内的某一个节点即可操作这个es集群 114 transportClient.addTransportAddress(transportAddress); 115 116 //获取client链接到的节点信息, //获取当前transportClient连接到了集群多少个节点 117 List<DiscoveryNode> connectedNodes = transportClient.connectedNodes(); 118 for (DiscoveryNode discoveryNode : connectedNodes) {//for星型循环,将connectedNodes的值,一一传给DiscoveryNode discoveryNode 119 System.out.println(discoveryNode.getHostName());//打印192.168.80.10;192.168.80.11;192.168.80.12 120 //如果加入transportClient.addTransportAddresses(transportAddress) 只有一个ip,打印的就只有一个. 121 } 122 } 123 124 125 String index = "zhouls";//设置索引库 126 String type = "emp";//设置类型 127 128 //索引index(四种格式:json,map,bean,es helper) 129 130 /** 131 * index-1 json 132 * 实际工作中使用 133 * @throws Exception 134 */ 135 @Test 136 public void test4() throws Exception { 137 String jsonStr = "{\"name\":\"tom zhang\",\"age\":19}";//需要转义下 //向索引库中传入一个String字符串,还可以接受其他类型 138 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "1")//添加一个id=1的数据 139 .setSource(jsonStr)//设值,这是json格式的 140 .get(); 141 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 142 System.out.println(indexResponse.getVersion()); 143 //得到这个数据的version,如果version=1代表是新添加的数据 144 } 145 146 147 148 /** 149 * index-2 hashmap 150 * 实际工作中使用 151 * @throws Exception 152 */ 153 @Test 154 public void test5() throws Exception {//把hashmap类型的数据放入index库 155 HashMap<String, Object> hashMap = new HashMap<String, Object>(); 156 //HashMap<String, Object> hashMap是迭代器变量 157 hashMap.put("name", "tom"); 158 hashMap.put("age", 15); 159 IndexResponse indexResponse = transportClient.prepareIndex(index, type, "2")//添加一个id=2的数据 160 .setSource(hashMap)//设值 161 .get(); 162 //.execute().actionGet(); 这个和上面的get()方法是一样的,get()就是对.execute().actionGet() 进行了封装 163 System.out.println(indexResponse.getVersion()); 164 } 165 166 167 168 169 /** 170 * index-3 bean 171 * 实际工作中使用 172 * 使用对象的时候需要把对象中的属性转化成json字符串 173 * @throws Exception 174 */ 175 176 // <dependency> 177 // <groupId>com.fasterxml.jackson.core</groupId> 178 //

优秀的个人博客,低调大师

uni-ai:让你的App快速接入AI

不管你的App是原生开发,还是基于某个跨端框架,都可以试试uni-ai。 uni-ai让你的 App 1 天接入 DeepSeek等AI模型,2 天上线全平台原生 AI 聊天功能! 在 AI时代,每个App都在思考AI化。 内置AI聊天(AI问答)成为众多App的基本需求。但当你准备动手打造一个像 ChatGPT、DeepSeek 那样流畅的AI客户端时,很快就会发现,技术挑战层出不穷,比如:webview 集成AI聊天虽然快捷,但体验相比原生,着实有差距。 如果不基于webview,采用原生开发,那么需要在Android、iOS、鸿蒙等平台解决如下问题: (1)流式网络请求:大模型流式返回的token,需要在手机端流式接收。 (2)缺少全平台效果一致的markdown解析器 (3)markdown流式解析复杂:传统应用场景下 markdown 解析都是全文解析。而随着 ai 的发展,流式回复的内容越来越长,需要持续跟踪上下文状态,判断当前内容是否在代码块/表格/列表等元素中,解析速度必须跟上流式传输速度,否则会明显卡顿; (4)全编程语言代码高亮:当AI回复编程语言时,几十种编程语言的代码如何高亮?当代码内容逐token更新时,如何局部重绘避免整体闪烁? (5)table的解析渲染:table对原生历来就是挑战。虽然大模型返回的表格不会特别大。但仍然要处理动态计算表格宽度,根据响应内容调整列宽,还需处理emoji/中文混合排版等情况。 (6)流式网络、流式markdown解析、流式排版,全程流式,且不能影响用户的UI操作,比如流式期间滚动操作不能掉帧。 (7)开发量大,尤其是鸿蒙平台缺少成熟库。 (8)以上问题,在每个平台都很难,如果要全平台支持,就更难。如果在全平台都保持高性能,那难度和工作量真是让人却步。 所以,DCloud提供了uni-aix。上述问题全部解决且开源免费。 什么是uni-ai x? uni-aix是一个开源、免费、全平台支持的原生 AI 聊天套件,基于DCloud 的新一代跨平台原生框架uni-app x开发,故Android、iOS、鸿蒙、Web、微信小程序全支持,一套代码、多端运行。 uni-ai在Web平台支持响应式布局: 在下载运行源码前,您可以安装apk到手机上,亲身体验下它的效果(demo不能连接计费模型) uni-aix成功解决上述痛点: 全平台一致的markdown流式渲染器 纯原生的体验而非webview 高性能的流式网络、流式markdown解析、流式排版,不卡滚动等用户交互。 动态响应宽度的原生表格 几十种编程语言高亮 开源、免费 除上述痛点外,uni-ai x还有更多完善的特性: 多屏适配与主题适配:适配 PC 浏览器宽屏和移动设备,适配pad、折叠屏,并提供浅色和暗黑两种主题模式 消息与会话管理。支持多轮对话和历史会话管理,具备会话切换、删除、自动创建等功能,提供完整的 AI 聊天体验 内置了uniCloud的AI能力,可以免开发直接接入deepseek、阿里通义、minimax、GPT-4、讯飞ifly。当然也可以不使用uniCloud,切换到自己的AI服务器。 uniCloud的AI能力,支持客户端安全直连大模型,大幅减少服务器压力和成本。否则在流式响应期间,服务器需要持续消耗。 内置了uni-id,自带账户体系。当然也可以不使用uni-id,接入已有的账户体系。 可以把uni-ai x当做独立的AI客户端,它具备DeepSeek客户端的极高仿真度;也可以把uni-ai x当做一个SDK,接入到已有的App中,成为一个AI聊天模块。不管是原生App还是其他跨平台框架开发的App,都可以以原生SDK接入的方式接入uni-ai x。uni-app x开发的App也可以接入。但uni-app开发的App需接入基于webview的uni-ai,而不是本次推出的uni-ai x。 开源可定制:前后端代码全开源,便于二次开发,适合各种 AI 应用场景 uni-aix全部代码开源,源码托管地址:gitcode.com、github.com 为什么 uni-ai x 能做到这些? uni-ai x的底层基于uni-app x原生跨端框架、uniCloud云开发框架。 使用uni-ai x,需要了解这些技术。 uni-app x 是 DCloud 的新一代原生跨平台框架,开发者使用UTS语言编写App代码,UTS是类似TS的语言,但它在原生平台会编译为原生语言。UTS语言在不同平台会编译为不同目标语言: Web/小程序平台:编译为JavaScript Android平台:编译为Kotlin iOS平台:编译为Swift 鸿蒙平台:编译为ArkTS uni-ai x的客户端部分,正是基于uni-app x,所以编写一套代码,就可以全平台覆盖。更多uni-app x的介绍,详见:uni-app-x uni-ai x里还集成了uniCloud云开发,从客户端到服务器,提供了整套源码。uniCloud是基于js的serverless云服务。除了基本的数据库、云函数、云存储,还提供了AI能力集成、uni-id账户体系等。更多uniCloud的介绍,详见:uniCloud 当然,uniCloud是可选的,您也可以不使用uniCloud,改用自己的服务器。 uni-ai x 如何集成? 如果你的App本来就是基于uni-app x开发的,那集成uni-aix非常简单,只需从DCloud插件市场下载uni-ai x插件到自己的uni-app x项目工程即可,uni-ai x是一个标准的uni_modules插件。 如果你的App是基于原生开发,或者使用的是业内其它跨端框架,那么集成uni-aix,主要有4步: (1)在uni-ai x 插件页面,点击“使用 HBuilderX 导入示例项目” (2)如使用uniCloud,需根据文档注册并配置相关的AI服务 key (3)在HBuilderX中导出应用原生资源,生成一批kotlin/swift/arkTS/js代码及相关图片字体等附件资源 (4)在你的原生工程中,引入uni-app x 原生SDK,合并入上一步导出的应用原生资源,整体运行编译。 参考资料: uni-ai x插件地址为:DCloud 插件市场 uni-app x 原生SDK集成及下载参考:uni-app x 原生SDK App如何AI化? 您可能早就想在App中引入AI能力,但又不知道如何把AI与App现有业务结合。下面列举部分常见的AI使用场景。 1.餐饮推荐: 用户:我想请同事吃饭,2人是回族; AI:预算多少? 用户:人均150元 AI:好的,如下是给你推荐的餐馆/菜品。。。 2.购物助手: 用户:我想买一个华为Mate 70 Pro,黑色; AI:内存要求多大? 用户:512G AI:对到货时间有要求吗? 用户:越快越好 AI:如下是支持京东物流、且符合您需求的商品清单 3.CRM培训: 销售新人:客户抱怨“太贵了”,该怎么回复? AI教练:您对比过哪些同类产品呢? 4.生活工具 用户:明天出差深圳,需要带什么东西? AI:几点到达深圳? 用户:下午3点。 AI:明日深圳气温28℃→推荐透气衣物;明日下午3点在深圳机场附近有暴雨预警→提醒带伞; 5.旅行助手 用户:计划暑假带孩子到新疆玩,帮我做个攻略。 AI:你想自驾还是报团? 用户:自驾 AI:预计几天时间? 用户:5天 AI:其它问题,多轮问答 还有很多场景,像客服、教育、医疗等,都需要AI基于多轮对话获取完整信息,从而给用户提供更精准的服务。 你的App是什么业务场景,你是如何使用AI的?也欢迎在评论区留言参与讨论。 欢迎大家使用uni-ai x,更欢迎大家 star、fork、提issue,共同完善这个开源项目! 开源地址:gitcode.com/dcloud/uni-… 技术交流群:更多问题欢迎加入uni-ai官方交流群。此群非微信群,而是DCloud的uni-im群。 手机端请使用 DCloud App扫码,或点击链接:uni-im 交流群

优秀的个人博客,低调大师

🔥 前端开发三大神器助你快速进入

还记得那些熬夜调试、满屏红色报错的日子吗?MCP(Model Context Protocol)正在让这一切成为历史。看看这三个神器如何把我们从"代码搬砖工"升级为"AI协作大师"! 三大核心模块深度解析 🧠 context7 - 你的专属项目大脑 自动记录项目架构、依赖关系、命名规范 跨会话保持上下文,AI永远记得你项目的"个性" 基于Upstash云存储,毫秒级访问项目历史 ⚡ sequential-thinking - 逻辑推理引擎 将复杂开发任务拆解为可执行步骤 支持链式思考:需求分析 → 技术选型 → 代码实现 → 测试验证 可视化展示推理过程,每一步都清晰可控 🔄 mcp-feedback-enhanced - 智能反馈优化器 实时分析代码运行结果和用户反馈 自动调整代码风格和实现策略 构建个人化的最佳实践知识库 💻 写代码场景实战演示 场景一:从零搭建React项目 以前的你: # 各种配置文件手动创建 npx create-react-app my-app # 反复查文档配置webpack、eslint、prettier... # 花费2-3小时才能开始写业务代码 现在的你: "帮我搭建一个带TypeScript的React项目,集成Tailwind和Zustand" 🧠 context7: 记住你偏好的技术栈和项目结构 ⚡ sequential-thinking: 1. 分析需求 → 2. 选择最佳实践 → 3. 生成配置文件 → 4. 创建基础组件 🔄 mcp-feedback-enhanced: 根据你的使用习惯调整代码风格 结果:5分钟完整项目脚手架,代码风格完全符合你的习惯! 场景二:复杂组件开发 以前的你: 在Stack Overflow翻找解决方案 复制粘贴代码后各种调试 花一天时间实现一个表格组件 现在的你: "基于我们项目的设计系统,创建一个支持排序、筛选、分页的数据表格" 🧠 context7: 自动获取项目的UI组件库、主题配置、已有组件 ⚡ sequential-thinking: 1. 分析设计系统 → 2. 复用已有组件 → 3. 实现新功能 → 4. 添加类型支持 🔄 mcp-feedback-enhanced: 基于项目中类似组件的实现模式优化代码 结果:30分钟完成,代码风格统一,性能优化到位! 场景四:大型电商项目重构 - 三模块完美协作演示 背景:你接手一个有着200+组件的老旧电商项目,需要从Vue2+Webpack迁移到Vue3+Vite,同时重构状态管理和优化性能。 第一阶段:项目诊断与规划 "分析这个电商项目,制定Vue2到Vue3的完整迁移方案" 🧠 context7 启动: - 扫描项目结构,发现208个.vue文件、34个Vuex store模块 - 记录项目依赖:vue-router@3.x、vuex@3.x、element-ui@2.x - 识别关键业务模块:用户系统、商品管理、订单流程、支付集成 - 建立项目知识图谱,标记高风险重构点 ⚡ sequential-thinking 接管: Step 1: 依赖兼容性分析 → 发现23个不兼容依赖 Step 2: 业务模块优先级排序 → 核心支付流程优先 Step 3: 迁移策略制定 → 渐进式迁移,保证系统稳定 Step 4: 风险评估 → 识别可能的breaking changes Step 5: 时间规划 → 3周迁移计划,每周一个里程碑 🔄 mcp-feedback-enhanced 预警: - 基于历史类似项目数据,预测迁移过程中的常见问题 - 建议优先处理element-ui到element-plus的组件迁移 - 推荐使用@vue/compat作为过渡方案 第二阶段:核心模块迁移 "开始迁移用户登录和商品列表模块" 🧠 context7 提供支持: - 调取用户模块的完整调用链:Login.vue → UserStore → AuthAPI - 识别商品列表的性能瓶颈:无虚拟滚动,一次加载1000+商品 - 记住你偏好的新架构:Composition API + Pinia + TypeScript ⚡ sequential-thinking 执行迁移: Step 1: 创建新的用户store(Pinia) └─ 保持原有API兼容,确保其他模块不受影响 Step 2: Login.vue重写为Composition API └─ 重构表单验证逻辑,使用VueUse工具库 Step 3: 商品列表性能优化 └─ 引入virtual-list,实现10000+商品秒级渲染 Step 4: TypeScript类型定义 └─ 为用户和商品数据创建完整类型体系 🔄 mcp-feedback-enhanced 实时优化: - 监测迁移后的性能指标:页面加载时间从3.2s降至0.8s - 发现新的TypeScript类型错误,自动修复 - 根据团队成员的code review反馈,调整代码风格 第三阶段:状态管理重构 "重构整个状态管理架构,从Vuex迁移到Pinia" 🧠 context7 深度分析: - 绘制完整的数据流图:34个store模块的依赖关系 - 识别冗余状态:发现12个重复的用户信息存储 - 记录异步操作模式:支付流程的复杂状态机 ⚡ sequential-thinking 系统重构: Step 1: 核心store优先迁移 └─ user、cart、order三大核心store Step 2: 状态合并与优化 └─ 消除重复状态,建立统一的数据源 Step 3: 异步操作标准化 └─ 统一错误处理、loading状态、缓存策略 Step 4: 跨组件通信优化 └─ 使用provide/inject替代事件总线 🔄 mcp-feedback-enhanced 质量保证: - 检测到订单状态更新存在race condition - 自动生成状态管理的单元测试用例 - 根据性能监控数据,优化状态持久化策略 第四阶段:性能优化与部署 "优化构建配置,准备生产环境部署" 🧠 context7 历史回顾: - 对比迁移前后的bundle size:从2.3MB降至1.1MB - 记录优化过程中的所有配置变更 - 保存性能基准数据,用于后续对比 ⚡ sequential-thinking 最终优化: Step 1: 代码分割优化 → 路由级别的懒加载 Step 2: 资源压缩 → Gzip + Brotli双重压缩 Step 3: CDN配置 → 静态资源分离部署 Step 4: 缓存策略 → 强缓存 + 协商缓存 🔄 mcp-feedback-enhanced 持续监控: - 部署后性能监控:首页加载时间稳定在800ms以内 - 用户反馈收集:页面响应速度提升73% - 建立性能告警机制,异常时自动通知 协作成果: 开发效率:原本需要2个月的重构工作,3周完成 代码质量:TypeScript覆盖率100%,单元测试覆盖率85% 性能提升:页面加载速度提升75%,bundle size减少52% 团队协作:标准化的代码风格,详细的重构文档 三模块协作的精髓: context7像项目的"记忆大师",记住每一个细节 sequential-thinking是"策略规划师",系统性解决复杂问题 mcp-feedback-enhanced是"质量监督员",确保每一步都是最优解 🚀 开发效率革命性提升 量化对比: 学习成本:从查文档2小时 → AI对话5分钟 代码质量:从个人经验 → 最佳实践沉淀 调试时间:从盲目试错 → 精准定位 知识传承:从零散笔记 → 结构化知识库 真实感受: // 以前写代码的心情 const mood = useState('焦虑') const energy = useState('疲惫') const confidence = useState('不确定') // 现在写代码的心情 const mood = useState('轻松') const energy = useState('专注') const confidence = useState('胸有成竹') 💡 未来编程新范式 从"写代码"到"聊需求": 自然语言描述需求,AI生成最佳实现 专注业务逻辑,告别重复性工作 代码质量自动优化,性能问题提前预防 个人化开发助手: 学习你的编码习惯和偏好 记住项目的历史演进和决策背景 提供定制化的技术建议和解决方案 🎯 立即体验MCP 如果你还在手动配置开发环境、复制粘贴Stack Overflow代码、为调试bug熬夜,那你真的out了! MCP不是在替代程序员,而是在解放程序员 - 让我们从重复性劳动中解脱,专注于真正有创造性的工作。 这就是2025年前端开发的标配! #MCP #前端开发 #AI编程 #开发效率 #React #TypeScript #Vue3 已经体验MCP的前端er们,在评论区分享你们的"爽点"时刻!还没体验的赶紧上车,别让AI时代的红利从指缝溜走~

优秀的个人博客,低调大师

Jmix 2.1 发布 - 企业级 Web 快速开发框架

我们最近发布了 Jmix 的 2.1 版本。下面我们将介绍这个新版本中增加的新功能和改进。 有关完整的详细信息和升级说明,请参阅官方文档中的最近更新页面。 新的扩展组件 我们将一些之前在 Jmix v.1 中基于经典 UI 的扩展组件迁移了过来。Jmix 2.1 中也能很容易集成这些组件,并且基于 Vaadin 24 提供的现代 Flow UI。 地图 地图扩展组件已经能支持 Jmix 2+,且具有新的 API,Studio 也能提供出色的支持。 下面的示例演示了如何在指定位置显示一个地图标记的 OpenStreetMap: <maps:geoMapid="map"width="100%"height="100%"> <maps:layers> <maps:tile> <maps:osmSource/> </maps:tile> <maps:vectorid="pointsLayer"> <maps:vectorSource/> </maps:vector> </maps:layers> </maps:geoMap> @ViewComponent privateGeoMapmap; @Subscribe publicvoidonInit(InitEventevent){ VectorLayervectorLayer=map.getLayer("pointsLayer"); VectorSourcevectorSource=vectorLayer.getSource(); vectorSource.addFeature(newMarkerFeature( GeometryUtils.createPoint(12.496176,41.902695))); } 这个示例属于 “hello world” 级别,显然没有涵盖组件的所有功能。事实上,地图可以包含瓦片层、图像层和矢量层,每个图层都支持不同的数据供应商。可以显示标记、点、折线和多边形。该组件的工作尚未完成,我们将在下一个版本中提供更多功能。 动态属性 动态属性 扩展组件支持在运行时为实体定义新的属性,而无需修改数据库结构和重启应用程序。这些动态属性可以拆分为不同的类别。 例如,Book 实体可以分为两类:电子和纸质。电子书具有“可用格式”和“文件大小”属性,而纸质书具有“封面类型”、“重量”和“尺寸”属性。可以在应用程序 UI 中定义动态属性: 在配置了属性之后,用户可以在已有的视图中查看并输入属性值: 动态属性会自动显示在特殊的 dynamicAttributesPanel 组件(如上所示)或任何现有的 formLayout 和 dataGrid 中。 通知组件 通知组件支持向用户发送应用内通知或电子邮件通知。可以通过 API 或使用附加组件提供的视图发送通知: 应用程序的 UI 需要包含 notificationsIndicator 组件,例如在 main-view.xml 中: <appLayout> <navigationBar> <header...> ... <ntf:notificationsIndicatorclassNames="ms-autome-m"/> </header> </navigationBar> 然后,收件人能在指示标记看到未读通知的数量,并通过简洁的 UI 直接打开: 搜索组件 搜索 扩展组件支持与 ElasticSearch 进行集成,为应用程序中的数据和上传文件提供全文搜索功能。通过几个简单的步骤就能使用该组件: 定义 ElasticSearch 的连接: jmix.search.elasticsearch.url = http://localhost:9200 创建一个带注解的 Java 接口,用于定义哪些内容需要进行索引: @JmixEntitySearchIndex(entity=Book.class) publicinterfaceBookIndexDef{ @AutoMappedField(includeProperties= {"title","author","publisher","genre.name"}) voidbookMapping(); } 在应用程序 UI 中添加 searchField 组件: <drawerLayout> <section...> <search:searchField/> 这样就可以了。系统将为 Book 实体的数据自动创建索引(并在每次变动时重新索引),用户能使用索引进行全文搜索: 搜索结果会根据当前用户的数据访问权限自动过滤,消除任何信息泄露的风险。 WebDAV WebDAV 扩展组件通过 WebDAV 协议提供对文件存储中文件的访问。用户可以使用桌面应用程序(Word、Excel、LibreOffice 等)无缝打开和编辑文件,而无需从应用程序进行上传和下载的操作。在 UI 层,组件提供了一个特殊的上传控件和管理页面,用于管理文件及其版本: 批量编辑器 批量编辑器 扩展组件支持用户一次更改多个实体实例的属性值,并提供了一个可以添加到任何 dataGrid 的操作: <dataGridid="booksDataGrid"...> <actions> ... <actionid="bulkEdit"type="bulked_edit"/> </actions> 此操作将打开一个对话框,用户可以输入属性的值。所有选定的实体实例都将更新这些属性: JMX 控制台 JMX 控制台 扩展组件为 Java JMX API 提供了 Web 页面。系统管理员可以直接在应用程序 UI 中检查 JMX bean、编辑属性和调用操作: BPM 改进 在应用程序 UI 中现在可以使用 DMN 表建模器了: 流程表单向导现在可以生成功能完备的视图,用于编辑流程变量和选择输出结果。 向导能显示流程中定义的变量: 并支持定义输出: 根据你的选择,向导会在视图中生成代码,将流程变量注入 UI 组件,并使用所选的输出完成任务: @ProcessForm(outcomes={ @Outcome(id="submit"), @Outcome(id="reject") }) //... publicclassBpmProcessFormextendsStandardView{ @Autowired privateProcessFormContextprocessFormContext; @ProcessVariable @ViewComponent privateEntityPicker<Book>book; //... @Subscribe("submitBtn") protectedvoidonSubmitBtnClick(ClickEvent<JmixButton>event){ processFormContext.taskCompletion() .withOutcome("submit") .saveInjectedProcessVariables() .complete(); closeWithDefaultAction(); } dataGrid改进 该版本中,对 dataGrid 组件进行了增强,dataGrid 主要用于展示表格数据。 现在,用户可以对 dataGrid 进行多列排序。列排序的顺序由排序箭头旁边显示的数字表示: 排序由 dataGrid 组件的 multiSort、multiSortOnShiftClickOnly 和 multiSortPriority 属性定义。 另一个新功能是可以在行内计算聚合值。需要配置聚合列时,请将 dataGrid 组件的 aggregatable 属性设置为 true,将 aggregation 元素添加到列中并选择聚合类型。聚合值将显示在单独的行中: 下一个改进是能够声明式地将渲染器分配给 dataGrid 列。如果你熟悉 Jmix Classic UI,那你可能会发现带有声明式渲染器的列与 Classic UI 中的“生成列”非常相似。在 XML 中定义某个列,然后创建一个返回渲染器的处理方法: @Supply(to="stepsDataGrid.completed",subject="renderer") privateRenderer<UserStep>stepsDataGridCompletedRenderer(){ returnnewComponentRenderer<>(userStep->{ //... returncheckbox; }); } 框架中预定义了几个用于设置日期和数字格式的渲染器,可以在 XML 的列中使用。还有,现在可以在 XML 中定义不绑定实体属性的列,仅用于为其声明渲染器。 也许数据网格的改进中最令人兴奋的新功能是表头过滤器。可以使用 column XML 元素的 filterable 属性来定义哪些列支持过滤。可过滤列的标题中带有“漏斗”图标。如果用户单击此图标,则会显示一个包含属性过滤器的弹窗: 如果设置了过滤条件,表头的图标将高亮显示: 表头过滤器这个概念,对于使用包括 Excel 在内的许多流行产品的用户都很熟悉,所以这个功能非常容易被发现和使用。我们认为,这种过滤数据的方式是对其他两个过滤组件的极好补充:genericFilter 和 propertyFilter。genericFilter 组件在运行时是完全可自定义的,并提供高级条件,但可能不是特别容易使用。而 propertyFilter 对用户来说很简单,但需要开发人员事先配置。数据网格的表头过滤器在功能上类似于 propertyFilter,但不占用任何额外的屏幕空间,因此可以成为大多数视图的默认过滤选择。 值的一提的是,这三个过滤功能可以在同一视图和数据加载器上一起使用,而不会发生任何冲突。所有过滤器的条件都将使用逻辑 AND 运算符进行简单组合。 新的 UI 组件和 Facets VirtualList 新的 virtualList 组件用于展示任意内容的列表。在页面中,该组件仅渲染当前可见的部分,因此,无论内容多复杂,都能保证有良好的性能。 virtualList 可以在视图中替换 dataGrid 使用。在 XML 中定义组件并将与集合数据容器连接: <virtualListid="stepsVirtualList"itemsContainer="stepsDc"/> 与数据加载器关联的过滤和分页组件(如 genericFilter 和 simplePagination)将直接影响 virtualList 展示的内容,这一点与 dataGrid 一样。 然后,需要创建一个展示列表每项内容的处理方法: @Supply(to="stepsVirtualList",subject="renderer") privateRenderer<Step>stepsVirtualListRenderer(){ returnnewComponentRenderer<>(step->{ //... returnhbox; }); } 花费一些精力对 virtualList 内容的布局进行编码后,可以获得类似于以下示例的视图: Html html 组件支持将任意 HTML 内容插入到视图中。内容可以定义在内部的 content 元素、项目资源中的文件,或者是消息包中,而以消息包的方式定义可以方便地支持国际化。 Settings settings facet 支持保存和恢复当前用户的可视化组件的设置,能自动保存 dataGrid 列的参数、详细信息和 genericFilter 的打开状态,以及 simplePagination 选定的页面大小。只需将 facet 拖放到视图并设置其 auto=“true” 属性,facet 将能管理视图中具有标识符的所有支持保存设置的组件。 settings facet 还提供处理方法,可以保存和还原视图及其组件的任何属性。 Timer timer facet 支持以特定的时间间隔运行某些视图代码,其工作在一个可以处理用户界面事件并能更新视图组件的线程中。使用时,在 XML 中定义参数,并为 TimerActionEvent 创建处理方法: <timerid="timer"delay="2000"repeating="true"autostart="true"/> @Subscribe("timer") publicvoidonTimerTimerAction(finalTimer.TimerActionEventevent){ //... } 加载下拉列表选项 新版本中引入了一种将数据加载到下拉组件中的高效方法,支持 comboBox、entityComboBox 和 multiSelectComboBox。现在,可以不用为组件定义选项的集合数据容器,也无需提前加载完整的选项列表。新的方法是,需要在下拉列表组件中定义 itemsQuery 嵌套标签,并编写类似下面的查询语句: <entityComboBoxid="departmentField"property="department"pageSize="30"> <itemsQueryclass="com.company.onboarding.entity.Department" fetchPlan="_instance_name" searchStringFormat="(?i)%${inputString}%"> <query> <![CDATA[selectefromDepartmente wheree.namelike:searchStringorderbye.name]]> </query> </itemsQuery> </entityComboBox> 当用户打开下拉列表时,将执行查询语句,并返回最多 pageSize 行(默认为 50)数据作为选项。当用户滚动选项列表时,将分页加载数据。如果用户在控件中输入一些文本,还可以按文本过滤选项。 除了在 XML 中编写 JPQL 查询语句外,还可以定义 itemsFetchCallback 处理方法并通过编程的方式从任何源加载数据。 与使用单独的集合数据容器的旧方法相比,itemsQuery 可以在数据量比较大的时候提供更好的性能。itemsQuery 支持分批加载选项,从而可以减少内存的使用量,并支持在数据存储级别进行数据过滤。因此,这种方法可以支持几乎任何大小的数据集作为下拉列表中的选项来源。 话又说回来,对于较小的数据集,使用单独的预加载集合容器仍然是更好的选择,因为响应更快。 视图设计器的改进 下面我们看一下 Studio 中的新功能和改进。 Studio 中最明显的变化可能是包含了组件的层次结构和属性的 Jmix UI 工具窗口。这个窗口现在支持与页面的 Java controller 同时打开并使用各种操作,而无需打开页面的 XML。 这样一来,在控制器中编写 Java 代码时,查看组件树、更改组件属性甚至添加新组件都非常方便。 另外,对 Preview(预览)面板也进行了改进。 我们都知道,显示页面的预览效果需要构建前端并启动 Vaadin 服务的开发模式,这个过程可能非常耗时。为了节省打开项目的时间,现在只有在 XML 编辑器顶部面板中点击 Start Preview 按钮时,才会打开预览面板。面板打开后,项目中后续所有打开的视图都将展示在预览面板中。要停止预览,只需单击 Stop Preview。 我们还做了大量工作,将预览功能与其他可视化设计器机制进行拆分。因为预览面板使用 JCEF 嵌入式浏览器,该浏览器对项目、IDE和操作系统的非标准配置的细微差别很敏感,容易出现问题。现在,即使预览面板出问题也不会影响 Jmix UI 工具窗口和代码生成功能。 代码辅助 在此版本中,我们引入了在视图类和 Spring bean 中注入依赖和 UI 组件的全新方法。 一旦你在方法体中开始输入字符,则会出现一个代码自动完成的下拉列表,其中显示了可用的 bean、UI 组件、局部变量和类字段。尚未注入到类中的 Bean 和 UI 组件将以斜体字显示。如果选择其中一项,则将自动注入到构造函数或使用特定注解(@Autowired 或 @ViewComponent)的字段中,于是能立即在当前光标位置使用。 有了这个功能,查找和注入可用的 bean 和 UI 组件就变得非常容易了。希望你喜欢这个小改进 😄 支持 Data Repositories Studio 现在能对创建和管理 Spring Data repositories 提供完整的支持。 通过点击 Jmix 窗口工具栏中的 New → Data Repository 创建 repository。Studio 将创建 repository 的接口并将其显示在实体节点下。 使用 repository 代码编辑器操作面板中的 Add Derived Method 和 Add Query Method 按钮可以创建具有派生查询或显式查询的方法: 对于 repository 的已有方法,Studio 会显示一个侧边栏图标,支持调整方法参数,例如添加排序或 fetch plan: 数据模型备注 本文中想强调的另一个功能是支持为实体及其属性添加备注。 实体设计器现在包含实体和每个属性的 Comment 字段。可以设置备注,备注将显示在字段中: 在设计器中输入的文本存储在实体类及其字段的 @Comment 注解中: @Comment(""" Storesinformationaboutbooks. HasreferencetoGenre.""") @JmixEntity @Table(name="BOOK") @Entity publicclassBook{ //... @Comment("Booktitle") @Column(name="TITLE",nullable=false) privateStringtitle; Studio 会生成 setTableRemarks 和 setColumnRemarks Liquibase 变更日志操作,可以将备注保存在数据库结构中(适用于除 HSQL 之外的所有数据库)。这样可以通过任何数据库工具查看备注。还可以从元数据中提取备注或直接从类注解中提取备注,以便在应用程序 UI 中显示或生成文档。 下一步? 在计划于 2024 年 2 月发布的下一个功能版本中,我们将实现新的 Charts 扩展组件,并完成 Maps 扩展组件中的剩余功能。UI 层方面,我们将添加 RichTextArea、水平主菜单以及搜索主菜单的功能。我们还将简化在 UI 视图中使用 Data Repository。 在 Studio 方面,我们将提供 BPMN 业务流程定义的热部署、生成自定义 REST controller,以及提供实体和视图集成测试的样板代码。 我们未来版本的详细路线图在 GitHub 项目 中。针对 2.1 的补丁版本将大约每月发布一次,以保持定期更新。 感谢所有提供想法、建议和错误报告的亲们!

资源下载

更多资源
Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册