在Elasticsearch中,为java提供了2种客户端,一种是REST风格的客户端,另一种是Java API的客户端。
REST客户端:
Elasticsearch提供了2种REST客户端,一种是低级客户端,一种是高级客户端。
Java Low Level REST Client:官方提供的低级客户端。该客户端通过http来连接Elasticsearch集群。用户在使用该客户端时需要将请求数据手动拼接成Elasticsearch所需JSON格式进行发送,收到响应时同样也需要将返回的JSON数据手动封装成对象。虽然麻烦,不过该客户端兼容所有的Elasticsearch版本。
Java High Level REST Client:官方提供的高级客户端。该客户端基于低级客户端实现,它提供了很多便捷的API来解决低级客户端需要手动转换数据格式的问题。
1.构造数据
POST /haoke/house/_bulk
{"index":{"_index":"haoke","_type":"house"}} {"id":"1001","title":"整租 · 南丹大楼 1居室 7500","price":"7500"} {"index":{"_index":"haoke","_type":"house"}} {"id":"1002","title":"陆家嘴板块,精装设计一室一厅,可拎包入住诚意租。","price":"8500"} {"index":{"_index":"haoke","_type":"house"}} {"id":"1003","title":"整租 · 健安坊 1居室 4050","price":"7500"} {"index":{"_index":"haoke","_type":"house"}} {"id":"1004","title":"整租 · 中凯城市之光+视野开阔+景色秀丽+拎包入住","price":"6500"} {"index":{"_index":"haoke","_type":"house"}} {"id":"1005","title":"整租 · 南京西路品质小区 21213三轨交汇 配套齐* 拎包入住","price":"6000"} {"index":{"_index":"haoke","_type":"house"}} {"id":"1006","title":"祥康里 简约风格 *南户型 拎包入住 看房随时","price":"7000"}
2.REST低级客户端
创建工程,引入依赖:
<dependencies> <!-- elasticsearch rest客户端 --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>6.5.4</version> </dependency> <!-- json格式化工具 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.4</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
编写测试用例:
public class ESRestTest { private static final ObjectMapper MAPPER = new ObjectMapper(); private RestClient restClient; @Before public void init() { RestClientBuilder restClientBuilder = RestClient.builder( new HttpHost("192.168.43.182", 9200, "http"), new HttpHost("192.168.43.182", 9201, "http"), new HttpHost("192.168.43.182", 9202, "http")); restClientBuilder.setFailureListener(new RestClient.FailureListener() { @Override public void onFailure(Node node) { System.out.println("出错了 -> " + node); } }); this.restClient = restClientBuilder.build(); } @After public void after() throws IOException { restClient.close(); } // 查询集群状态 @Test public void testGetInfo() throws IOException { Request request = new Request("GET", "/_cluster/state"); request.addParameter("pretty", "true"); // 格式化json数据 Response response = this.restClient.performRequest(request); System.out.println(response.getStatusLine()); // 状态行 System.out.println(EntityUtils.toString(response.getEntity())); // 响应体 } // 新增数据 @Test public void testCreateData() throws IOException { Request request = new Request("POST", "/haoke/house"); Map<String, Object> data = new HashMap<>(); data.put("id", "2001"); data.put("title", "张江高科"); data.put("price", "3500"); request.setJsonEntity(MAPPER.writeValueAsString(data)); Response response = this.restClient.performRequest(request); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); } // 根据id查询数据 @Test public void testQueryData() throws IOException { Request request = new Request("GET", "/haoke/house/at6XFXEBO18vQ71rkF2P"); Response response = this.restClient.performRequest(request); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); } // 搜索数据 @Test public void testSearchData() throws IOException { Request request = new Request("POST", "/haoke/house/_search"); String searchJson = "{"query": {"match": {"title": "拎包入住"}}}"; request.setJsonEntity(searchJson); request.addParameter("pretty", "true"); Response response = this.restClient.performRequest(request); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); } }
从使用中,可以看出,基本和我们使用RESTful api使用几乎是一致的。
3.REST高级客户端
引入依赖:
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>6.5.4</version> </dependency>
编写测试用例:
public class RestHighLevelTest { private RestHighLevelClient client; @Before public void init() { RestClientBuilder restClientBuilder = RestClient.builder( new HttpHost("192.168.43.182", 9200, "http"), new HttpHost("192.168.43.182", 9201, "http"), new HttpHost("192.168.43.182", 9202, "http")); restClientBuilder.setFailureListener(new RestClient.FailureListener() { @Override public void onFailure(Node node) { System.out.println("出错了 -> " + node); } }); this.client = new RestHighLevelClient(restClientBuilder); } @After public void after() throws Exception { this.client.close(); } /** * 新增文档,同步操作 * * @throws Exception */ @Test public void testCreate() throws Exception { Map<String, Object> data = new HashMap<>(); data.put("id", "2002"); data.put("title", "南京西路 拎包入住 一室一厅"); data.put("price", "4500"); IndexRequest indexRequest = new IndexRequest("haoke", "house").source(data); IndexResponse indexResponse = this.client.index(indexRequest, RequestOptions.DEFAULT); System.out.println("id->" + indexResponse.getId()); System.out.println("index->" + indexResponse.getIndex()); System.out.println("type->" + indexResponse.getType()); System.out.println("version->" + indexResponse.getVersion()); System.out.println("result->" + indexResponse.getResult()); System.out.println("shardInfo->" + indexResponse.getShardInfo()); } /** * 新增文档,异步操作 * * @throws Exception */ @Test public void testCreateAsync() throws Exception { Map<String, Object> data = new HashMap<>(); data.put("id", "2003"); data.put("title", "南京东路 最新房源 二室一厅"); data.put("price", "5500"); IndexRequest indexRequest = new IndexRequest("haoke", "house").source(data); this.client.indexAsync(indexRequest, RequestOptions.DEFAULT, new ActionListener<IndexResponse>() { @Override public void onResponse(IndexResponse indexResponse) { System.out.println("id->" + indexResponse.getId()); System.out.println("index->" + indexResponse.getIndex()); System.out.println("type->" + indexResponse.getType()); System.out.println("version->" + indexResponse.getVersion()); System.out.println("result->" + indexResponse.getResult()); System.out.println("shardInfo->" + indexResponse.getShardInfo()); } @Override public void onFailure(Exception e) { System.out.println(e); } }); System.out.println("ok"); Thread.sleep(20000); } /** * 根据id查询数据 * * @throws Exception */ @Test public void testQuery() throws Exception { GetRequest getRequest = new GetRequest("haoke", "house", "bd7GFXEBO18vQ71roF3y"); // 指定返回的字段 String[] includes = new String[]{"title", "id"}; String[] excludes = Strings.EMPTY_ARRAY; FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes); getRequest.fetchSourceContext(fetchSourceContext); GetResponse response = this.client.get(getRequest, RequestOptions.DEFAULT); System.out.println("数据 -> " + response.getSource()); } /** * 判断是否存在 * * @throws Exception */ @Test public void testExists() throws Exception { GetRequest getRequest = new GetRequest("haoke", "house", "bd7GFXEBO18vQ71roF3y"); // 不返回的字段 getRequest.fetchSourceContext(new FetchSourceContext(false)); boolean exists = this.client.exists(getRequest, RequestOptions.DEFAULT); System.out.println("exists -> " + exists); } /** * 删除数据 * * @throws Exception */ @Test public void testDelete() throws Exception { DeleteRequest deleteRequest = new DeleteRequest("haoke", "house", "bd7GFXEBO18vQ71roF3y"); DeleteResponse response = this.client.delete(deleteRequest, RequestOptions.DEFAULT); System.out.println(response.status());// OK 或者 NOT_FOUND } /** * 更新数据 * * @throws Exception */ @Test public void testUpdate() throws Exception { UpdateRequest updateRequest = new UpdateRequest("haoke", "house", "at6XFXEBO18vQ71rkF2P"); Map<String, Object> data = new HashMap<>(); data.put("title", "张江高科2"); data.put("price", "5000"); updateRequest.doc(data); UpdateResponse response = this.client.update(updateRequest, RequestOptions.DEFAULT); System.out.println("version -> " + response.getVersion()); } /** * 全文搜索 * * @throws Exception */ @Test public void testSearch() throws Exception { SearchRequest searchRequest = new SearchRequest("haoke"); searchRequest.types("house"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("title", "拎包入住")); // 设置分页 sourceBuilder.from(0); sourceBuilder.size(5); // 设置搜索的超时时间 sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); searchRequest.source(sourceBuilder); SearchResponse search = this.client.search(searchRequest, RequestOptions.DEFAULT); System.out.println("搜索到 " + search.getHits().totalHits + " 条数据."); SearchHits hits = search.getHits(); for (SearchHit hit : hits) { System.out.println(hit.getSourceAsString()); } } }