Elasticsearch
- Java API 操作
- 1.1 引入依赖
- 1.2 客户端对象
- 1.3 索引操作
- 1.3.1 创建索引
- 1.3.2 查看索引
- 1.3.3 删除索引
- 1.4 文档操作
- 1.4.1 新增文档
- 1.4.2 修改文档
- 1.4.3 查询文档
- 1.4.4 删除文档
- 1.4.5 批量新增
- 1.4.6 批量删除
- 1.5 高级查询
- 1.5.1 请求体查询
- 1.5.1.1 查询所有索引数据
- 1.5.1.2 term 查询,查询条件为关键字
- 1.5.1.3 分页查询
- 1.5.1.4 数据排序
- 1.5.1.5 过滤字段
- 1.5.1.6 Bool 查询
- 1.5.1.7 范围查询
- 1.5.1.8 模糊查询
- 1.5.1.9 高亮查询
- 1.5.1.10 聚合查询
Java API 操作
Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对 Elasticsearch
服务进行访问,废话不多说,直接开始。
1.1 引入依赖
<dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.8.0</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.8.0</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.8.2</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.8.2</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.9</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency>
1.2 客户端对象
// 创建客户端RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));// todo// 关闭客户端client.close();
1.3 索引操作
1.3.1 创建索引
// 创建索引CreateIndexRequest request = new CreateIndexRequest("user");// 发送请求,获取响应CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);boolean acknowledged = response.isAcknowledged();// 响应状态System.out.println("操作状态=" + acknowledged);
1.3.2 查看索引
// 查询索引-请求对象GetIndexRequest request = new GetIndexRequest("user");//发送请求GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);System.out.println("aliases:" + response.getAliases());System.out.println("mappings:" + response.getMappings());System.out.println("settings:" + response.getSettings());
响应结果:
1.3.3 删除索引
// 删除索引 - 请求对象DeleteIndexRequest request = new DeleteIndexRequest("user");// 发送请求AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);// 操作结果System.out.println("操作结果:" + response.isAcknowledged());
响应结果:
1.4 文档操作
1.4.1 新增文档
// 新增文档 - 请求对象IndexRequest request = new IndexRequest();// 设置索引及唯一性表示request.index("user").id("1001");User user = new User();user.setName("zhangsan");user.setAge(30);user.setSex("男");ObjectMapper objectMapper = new ObjectMapper();String productJson = objectMapper.writeValueAsString(user);// 提那家文档数据,数据格式为JSON格式request.source(productJson, XContentType.JSON);// 发送请求,获取响应对象IndexResponse response = client.index(request, RequestOptions.DEFAULT);// 打印结果信息System.out.println("_index:" + response.getIndex());System.out.println("_id:" + response.getId());System.out.println("_result:" + response.getResult());
响应结果:
1.4.2 修改文档
// 修改文档 - 请求对象UpdateRequest request = new UpdateRequest();// 配置修改参数request.index("user").id("1001");// 设置请求体,对数据进行修改request.doc(XContentType.JSON, "sex", "女");// 客户端发送请求,获取响应对象UpdateResponse response = client.update(request, RequestOptions.DEFAULT);System.out.println("_index:" + response.getIndex());System.out.println("_id:" + response.getId());System.out.println("_result:" + response.getResult());
响应结果:
1.4.3 查询文档
// 创建请求对象GetRequest request = new GetRequest().index("user").id("1001");// 客户端发送请求,获取响应对象GetResponse response = client.get(request, RequestOptions.DEFAULT);// 打印结果信息System.out.println("_index:" + response.getIndex());System.out.println("_type:" + response.getType());System.out.println("_id:" + response.getId());System.out.println("source:" + response.getSourceAsString());
响应结果:
1.4.4 删除文档
// 创建请求对象DeleteRequest request = new DeleteRequest().index("user").id("1");// 客户端发送请求,获取响应对象DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);// 打印信息System.out.println(response.toString());
响应结果:
1.4.5 批量新增
//创建批量新增请求对象BulkRequest request = new BulkRequest();request.add(newIndexRequest().index("user").id("1001").source(XContentType.JSON, "name","zhangsan"));request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name","lisi"));request.add(newIndexRequest().index("user").id("1003").source(XContentType.JSON, "name","wangwu"));//客户端发送请求,获取响应对象BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);//打印结果信息System.out.println("took:" + responses.getTook());System.out.println("items:" + responses.getItems());
响应结果:
1.4.6 批量删除
//创建批量删除请求对象BulkRequest request = new BulkRequest();request.add(new DeleteRequest().index("user").id("1001"));request.add(new DeleteRequest().index("user").id("1002"));request.add(new DeleteRequest().index("user").id("1003"));//客户端发送请求,获取响应对象BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);//打印结果信息System.out.println("took:" + responses.getTook());System.out.println("items:" + responses.getItems());
响应结果:
1.5 高级查询
1.5.1 请求体查询
1.5.1.1 查询所有索引数据
// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 查询所有数据sourceBuilder.query(QueryBuilders.matchAllQuery());request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");
响应结果:
1.5.1.2 term 查询,查询条件为关键字
// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.termQuery("age", "30"));request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");
响应结果:
1.5.1.3 分页查询
// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchAllQuery());// 分页查询// 当前页其实索引(第一条数据的顺序号),fromsourceBuilder.from(0);// 每页显示多少条 sizesourceBuilder.size(2);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");
响应结果:
1.5.1.4 数据排序
// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchAllQuery());// 排序sourceBuilder.sort("age", SortOrder.ASC);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");
响应结果:
1.5.1.5 过滤字段
// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchAllQuery());//查询字段过滤String[] excludes = {};String[] includes = {"name", "age"};sourceBuilder.fetchSource(includes, excludes);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");
响应结果:
1.5.1.6 Bool 查询
// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();// 必须包含boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));// 一定不含boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));// 可能包含boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));sourceBuilder.query(boolQueryBuilder);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");
响应结果:
1.5.1.7 范围查询
// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");// 大于等于rangeQuery.gte("30");// 小于等于rangeQuery.lte("40");sourceBuilder.query(rangeQuery);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");
响应结果:
1.5.1.8 模糊查询
// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.fuzzyQuery("name","zhangsan").fuzziness(Fuzziness.ONE));request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");
响应结果:
1.5.1.9 高亮查询
// 高亮查询SearchRequest request = new SearchRequest().indices("student");//2.创建查询请求体构建器SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建查询方式:高亮查询TermsQueryBuilder termsQueryBuilder =QueryBuilders.termsQuery("name","zhangsan");//设置查询方式sourceBuilder.query(termsQueryBuilder);//构建高亮字段HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.preTags("<font color='red'>");//设置标签前缀highlightBuilder.postTags("</font>");//设置标签后缀highlightBuilder.field("name");//设置高亮字段//设置高亮构建对象sourceBuilder.highlighter(highlightBuilder);//设置请求体request.source(sourceBuilder);//3.客户端发送请求,获取响应对象SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.打印响应结果SearchHits hits = response.getHits();System.out.println("took::"+response.getTook());System.out.println("time_out::"+response.isTimedOut());System.out.println("total::"+hits.getTotalHits());System.out.println("max_score::"+hits.getMaxScore());System.out.println("hits::::>>");for (SearchHit hit : hits) {String sourceAsString = hit.getSourceAsString();System.out.println(sourceAsString);//打印高亮结果Map<String, HighlightField> highlightFields = hit.getHighlightFields();System.out.println(highlightFields);}System.out.println("<<::::");
响应结果:
1.5.1.10 聚合查询
1.最大年龄
SearchRequest request = new SearchRequest().indices("student");SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));//设置请求体request.source(sourceBuilder);//3.客户端发送请求,获取响应对象SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.打印响应结果SearchHits hits = response.getHits();System.out.println(response);
响应结果:
2.分组统计
SearchRequest request = new SearchRequest().indices("student");SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
//设置请求体request.source(sourceBuilder);
//3.客户端发送请求,获取响应对象SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4.打印响应结果SearchHits hits = response.getHits();System.out.println(response);
响应结果:
到此,基础的语法与应用练习完。不对的地方欢迎批评指正。