API操作
新建工程并导入依赖:
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.3.6</version></dependency><dependency><groupId>io.searchbox</groupId><artifactId>jest</artifactId><version>5.3.3</version></dependency><dependency><groupId>net.java.dev.jna</groupId><artifactId>jna</artifactId><version>4.5.2</version></dependency><dependency><groupId>org.codehaus.janino</groupId><artifactId>commons-compiler</artifactId><version>2.7.8</version></dependency><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>6.6.0</version></dependency>
写数据
1)单条数据写入
//1.创建ES客户端构建器JestClientFactory factory = new JestClientFactory();//2.创建ES客户端连接地址HttpClientConfig httpClientConfig = new HttpClientConfig.Builder("http://hadoop102:9200").build();//3.设置ES连接地址factory.setHttpClientConfig(httpClientConfig);//4.获取ES客户端连接JestClient jestClient = factory.getObject();//5.构建ES插入数据对象Index index = new Index.Builder("{\n" +" \"id\":\"1002\",\n" +" \"movie_name\":\”姜子牙\”\n" +"}").index("movie_test1").type("_doc").id("1002").build();//6.执行插入数据操作jestClient.execute(index);//7.关闭连接jestClient.shutdownClient();2)批量数据写入//1.创建客户端对象JestClientFactory jestClientFactory = new JestClientFactory();//2.设置连接参数HttpClientConfig httpClientConfig = new HttpClientConfig.Builder("http://hadoop102:9200").build();jestClientFactory.setHttpClientConfig(httpClientConfig);//3.获取客户端对象JestClient jestClient = jestClientFactory.getObject();Movie movie1 = new Movie("1005", "二十不惑");Movie movie2 = new Movie("1006", "三十而立");Movie movie3 = new Movie("1007", "寄生虫");Index index1 = new Index.Builder(movie1).id("1005").build();Index index2 = new Index.Builder(movie2).id("1006").build();Index index3 = new Index.Builder(movie3).id("1007").build();Bulk bulk = new Bulk.Builder().defaultIndex("movie_test1").defaultType("_doc").addAction(index1).addAction(index2).addAction(index3).build();jestClient.execute(bulk);jestClient.shutdownClient();
读数据
//1.创建ES客户端连接池JestClientFactory factory = new JestClientFactory();//2.创建ES客户端连接地址HttpClientConfig httpClientConfig = new HttpClientConfig.Builder("http://hadoop102:9200").build();//3.设置ES连接地址factory.setHttpClientConfig(httpClientConfig);//4.获取ES客户端连接JestClient jestClient = factory.getObject();//5.构建查询数据对象Search search = new Search.Builder("{\n" +" \"query\": {\n" +" \"match\": {\n" +" \"name\": \"zhangsan\"\n" +" }\n" +" }\n" +"}").addIndex("test5").addType("_doc").build();//6.执行查询操作SearchResult searchResult = jestClient.execute(search);//7.解析查询结果System.out.println(searchResult.getTotal());List<SearchResult.Hit<Map, Void>> hits = searchResult.getHits(Map.class);for (SearchResult.Hit<Map, Void> hit : hits) {System.out.println(hit.index + "--" + hit.id);}//8.关闭连接jestClient.shutdownClient();
