ElasticSearch基础篇-Java API操作

ElasticSearch基础-Java API操作

在这里插入图片描述

演示代码

创建连接

POM依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.vmware</groupId><artifactId>spring-custom</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.8.0</version></dependency><!-- elasticsearch 的客户端 --><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.8.0</version></dependency><!-- elasticsearch 依赖 2.x 的 log4j --><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><!-- junit 单元测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.9</version></dependency></dependencies>
</project>
建立连接
package com.vmware.elastic;import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;import java.io.IOException;/*** @apiNote 演示创建elastic客户端,与关闭连接*/public class HelloElasticSearch {public static void main(String[] args) throws IOException {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));client.close();}
}

索引操作

创建索引
package com.vmware.elastic.index;import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;import java.io.IOException;/*** @apiNote 演示创建索引*/
public class IndexCreate {public static void main(String[] args) throws IOException {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));CreateIndexRequest request = new CreateIndexRequest("vmware");CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);System.out.println("索引操作:" + response.isAcknowledged());client.close();}
}
删除索引
package com.vmware.elastic.index;import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;/*** @apiNote 演示删除索引*/
public class IndexDelete {public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));DeleteIndexRequest request = new DeleteIndexRequest("vmware");AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);System.out.println(response.isAcknowledged());//acknowledged表示操作是否成功client.close();}
}
查询索引
package com.vmware.elastic.index;import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;/*** @apiNote 演示查询索引*/
public class IndexQuery {public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));GetIndexRequest request = new GetIndexRequest("vmware");GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);System.out.println(response.getAliases());//获取别名//{vmware=[]}System.out.println(response.getMappings());//获取索引映射//{vmware=org.elasticsearch.cluster.metadata.MappingMetadata@9b2cfd3c}System.out.println(response.getSettings());//获取索引设置//{vmware={"index.creation_date":"1690635515922","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"vmware","index.uuid":"HtIuUNNnTTyz9CT2oz0Lww","index.version.created":"7060299"}}client.close();}
}

文档操作

创建文档
package com.vmware.elastic.document;import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.vmware.elastic.entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;/*** @apiNote 演示创建文档*/
public class DocumentCreate {private static Gson gson = new Gson();public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));IndexRequest request = new IndexRequest();request.index("vmware");request.id("1001");User user = new User();user.setName("张三");user.setAge(18);user.setSex("男");//es client操作索引需要将java对象转为json格式String json = gson.toJson(user);request.source(json, XContentType.JSON);IndexResponse response = client.index(request, RequestOptions.DEFAULT);DocWriteResponse.Result result = response.getResult();System.out.println(result);//CREATEDclient.close();}
}
删除文档
package com.vmware.elastic.document;import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;/*** @apiNote 演示删除文档*/
public class DocumentDelete {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));DeleteRequest request=new DeleteRequest("vmware","1001");DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);System.out.println(response.getResult());//DELETEDclient.close();}
}
更新文档
package com.vmware.elastic.document;import com.google.gson.Gson;
import com.vmware.elastic.entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;/*** @apiNote 演示更新文档*/
public class DocumentUpdate {public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));UpdateRequest request = new UpdateRequest();request.index("vmware");request.id("1001");request.doc(XContentType.JSON,"name","李四");UpdateResponse response = client.update(request, RequestOptions.DEFAULT);DocWriteResponse.Result result = response.getResult();System.out.println(result);//UPDATEDclient.close();}
}
查询文档
package com.vmware.elastic.document;import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;/*** @apiNote 演示查询文档*/
public class DocumentQuery {public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));GetRequest request = new GetRequest("vmware", "1001");GetResponse response = client.get(request, RequestOptions.DEFAULT);System.out.println(response.getSourceAsString());//{"name":"李四","age":18,"sex":"男"}client.close();}
}

批量操作

批量新增
package com.vmware.elastic.batch;import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;/*** @apiNote 批量创建文档*/
public class DocumentBatchCreate {public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));BulkRequest request = new BulkRequest("vmware");//bulk:大批的request.add(new IndexRequest().id("1005").source(XContentType.JSON,"name","wangwu","age",30));request.add(new IndexRequest().id("1006").source(XContentType.JSON,"name","wangwu2","age",40));request.add(new IndexRequest().id("1007").source(XContentType.JSON,"name","wangwu33","age",50));BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);System.out.println(response.getTook());//6msSystem.out.println(response.getItems());//[Lorg.elasticsearch.action.bulk.BulkItemResponse;@6bb4dd34client.close();}
}
批量删除
package com.vmware.elastic.batch;import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;/*** @apiNote 批量删除*/
public class DocumentBatchDelete {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));BulkRequest request = new BulkRequest("vmware");//bulk:大批的request.add(new DeleteRequest().id("1005"));request.add(new DeleteRequest().id("1006"));request.add(new DeleteRequest().id("1007"));BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);System.out.println(response.getTook());//8msSystem.out.println(response.getItems());//[Lorg.elasticsearch.action.bulk.BulkItemResponse;@624ea235client.close();}
}

高级操作

聚合查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;import java.util.List;/*** @apiNote 聚合查询*/
public class DocumentAggregateQuery {public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");//最大值查询
//        MaxAggregationBuilder maxAggregationBuilder = AggregationBuilders.max("maxAge").field("age");TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");//分组查询request.source(new SearchSourceBuilder().aggregation(termsAggregationBuilder));//构建查询,设置为全量查询SearchResponse response = client.search(request, RequestOptions.DEFAULT);for (Aggregation aggregation : response.getAggregations()) {ParsedLongTerms terms = (ParsedLongTerms) aggregation;List<? extends Terms.Bucket> buckets = terms.getBuckets();for (Terms.Bucket bucket : buckets) {System.out.println(bucket.getKeyAsString() + ":" + bucket.getDocCount());}}client.close();}
}
组合查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;/*** @apiNote 组合查询*/
public class DocumentCombinationQuery {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//构建组合查询条件 must:全部满足
//        boolQuery.must(QueryBuilders.matchQuery("name","王五"));
//        boolQuery.must(QueryBuilders.matchQuery("age",30));//构建组合条件 should:满足任意一个条件即可
//        boolQuery.should(QueryBuilders.matchQuery("age",30));
//        boolQuery.should(QueryBuilders.matchQuery("age",50));//构建组合查询条件 mushNot:不满足条件boolQuery.mustNot(QueryBuilders.matchQuery("age",30));request.source(new SearchSourceBuilder().query(boolQuery));SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);}client.close();}
}
条件查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;/*** @apiNote 条件查询** 响应时间:0s* {*   "_index" : "vmware",*   "_type" : "_doc",*   "_id" : "1005",*   "_score" : 1.0,*   "_source" : {*     "name" : "王五",*     "age" : 30*   }* }*/
public class DocumentConditionalQuery {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age","30")));//设置查询条件为name=王五SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);//}client.close();}
}
过滤查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;/*** @apiNote 过滤查询*/
public class DocumentFilterQuery {public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");String[] includes = {"name","age"};//需要包含的字段String[] excludes = {};            //需要排除的字段request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).fetchSource(includes, excludes)//添加过滤条件);SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);}client.close();}
}
模糊查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;/*** @apiNote 模糊查询*/
public class DocumentFuzzyQuery {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");//设置模糊查询 Fuzziness.ONE:差一个字也可以查询出来  注意:需要字段设置为keyword类型,否则es会对查询条件进行分词导致模糊查询失效FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "王五").fuzziness(Fuzziness.ONE);request.source(new SearchSourceBuilder().query(fuzzyQueryBuilder));//构建查询,设置为全量查询SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);}client.close();}
}
高亮查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;/*** @apiNote 高亮查询*/
public class DocumentHighLightQuery {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wangwu");//注意:高亮不支持中文searchSourceBuilder.query(termQueryBuilder);//构建高亮查询HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.preTags("<fort style='color:red'>");//设置前缀标签highlightBuilder.postTags("</fort>");//设置后缀标签highlightBuilder.field("name");//设置高亮字段searchSourceBuilder.highlighter(highlightBuilder);request.source(searchSourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);//<fort style='color:red'>wangwu</fort>}client.close();}
}
全量查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;/*** @apiNote 全量查询** 响应时间:0s* {*   "_index" : "vmware",*   "_type" : "_doc",*   "_id" : "1005",*   "_score" : 1.0,*   "_source" : {*     "name" : "王五",*     "age" : 30*   }* }* {*   "_index" : "vmware",*   "_type" : "_doc",*   "_id" : "1006",*   "_score" : 1.0,*   "_source" : {*     "name" : "赵六",*     "age" : 40*   }* }* {*   "_index" : "vmware",*   "_type" : "_doc",*   "_id" : "1007",*   "_score" : 1.0,*   "_source" : {*     "name" : "陈⑦",*     "age" : 50*   }* }*/
public class DocumentMatchAllQuery {public static void main(String[] args) throws Exception {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));//构建查询,设置为全量查询SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);}client.close();}
}
结果排序
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;/*** @apiNote 对返回结果排序*/
public class DocumentOrderQuery {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).sort("age", SortOrder.ASC)//设置排序规则);SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);}client.close();}
}
分页查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;/*** @apiNote 分页查询*/
public class DocumentPagingQuery {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).from(0).size(2) //设置分页);SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);}client.close();}
}
范围查询
package com.vmware.elastic.high;import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;/*** @apiNote 范围查询*/
public class DocumentRangeQuery {public static void main(String[] args) throws Exception{RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("10.192.193.98", 9200)));SearchRequest request = new SearchRequest("vmware");RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery("age").gte(40).lt(50);//构建范围查询 大于等于40小于50request.source(new SearchSourceBuilder().query(queryBuilder));SearchResponse response = client.search(request, RequestOptions.DEFAULT);SearchHits hits = response.getHits();//获取查询结果TimeValue took = response.getTook(); //获取响应时间System.out.println("响应时间:" + took);for (SearchHit hit : hits) {System.out.println(hit);}client.close();}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/19525.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

33.利用abs 解决绝对值问题(matlab程序 )

1.简述 abs函数的功能是绝对值和复数的模 语法 Y abs(X) 说明 Y abs(X) 返回数组 X 中每个元素的绝对值。如果 X 是复数&#xff0c;则 abs(X) 返回复数的模。 示例 标量的绝对值 y abs(-5) y 5 向量的绝对值 创建实值的数值向量。 x [1.3 -3.56 8.23 -5 -0.01…

【POP3/IMAP/SMTP】QQ邮箱设置

什么是 POP3/IMAP/SMTP 服务 POP3 &#xff08;Post Office Protocol - Version 3&#xff09;协议用于支持使用电子邮件客户端获取并删除在服务器上的电子邮件。 IMAP &#xff08;Internet Message Access Protocol&#xff09;协议用于支持使用电子邮件客户端交互式存取服务…

二十三种设计模式第二十二篇--中介者模式

说到这个模式就有趣了&#xff0c;不知道大家在生活中喷到过中介没&#xff1f;其实中介这个词吧&#xff0c;我也说不上好还是坏&#xff0c;有时候他可以帮助人们更快的达到某个目的&#xff0c;但有的时候吧&#xff0c;这个有贼坑人&#xff0c;相信网络上有各种被中介坑的…

【力扣】822. 翻转卡片游戏

以下为力扣官方题解&#xff0c;及本人代码 822. 翻转卡片游戏 题目题意示例 1示例 2提示 官方题解哈希集算法总结复杂度 本人代码Java提交结果&#xff1a;通过 题目 题意 在桌子上有 n n n 张卡片&#xff0c;每张卡片的正面和背面都写着一个正数&#xff08;正面与背面上…

Java程序员面试题

Java程序员面试题目 1.Java基础1.1 Java有list&#xff0c;list有很多种&#xff0c;你平时开发喜欢用哪个list&#xff1f;&#xff08;容易&#xff09;1.2 Java的map&#xff0c;你知道有哪几种map&#xff0c;你平时喜欢用哪个&#xff1f;&#xff08;容易&#xff09; 2.…

空指针NPE原因之一:判断顺序错误

不管是&&或者|| 一般都是将null或非null放在第一个判断 在Java中&#xff0c;逻辑运算符&&和||具有短路特性。这意味着如果使用&&运算符&#xff0c;如果第一个条件为false&#xff0c;将不会执行第二个条件&#xff0c;因为整个表达式已经确定为fals…

【Python】模块学习之matplotlib柱状图、饼状图、动态图及解决中文显示问题

目录 前言 安装 pip安装 安装包安装 柱状图 主要方法 参数说明 示例代码 效果图 解决中文显示问题 修改后的图片 饼状图 主要方法 示例代码 效果图 动态图 主要方法 动态图官方使用介绍 示例代码 颜色设置 内建颜色 字体设置 资料获取方法 前言 众所周…

【Golang 接口自动化04】 解析接口返回JSON串

目录 前言 解析到结构体 json数据与struct字段是如何相匹配的呢&#xff1f; 解析到interface Go类型和JSON类型 实例代码 simpleJson 总结 资料获取方法 前言 上一次我们一起学习了如何解析接口返回的XML数据&#xff0c;这一次我们一起来学习JSON的解析方法。 JSO…

[驱动开发]gpio子系统及中断实现led亮灭

编写LED灯的驱动&#xff0c;使用GPIO子系统&#xff0c;里面添加按键的中断处理 1.应用程序发送指令控制发光二极管亮灭 2.按键1按下&#xff0c;led1电位反转&#xff1b;按键2按下&#xff0c;led2电位反转&#xff1b;按键3按下&#xff0c;led3电位反转 //头文件 #i…

PHP并发处理详解

在今天的网络世界中&#xff0c;高并发是一个无法避免的问题。随着用户的增加和业务的复杂性&#xff0c;我们的应用可能会面临大量的并发请求。这时&#xff0c;如果我们不能很好地处理并发&#xff0c;就可能会导致应用的性能下降&#xff0c;甚至崩溃。在很多情况下&#xf…

想做上位机,学C#还是QT?

学习C#还是Qt&#xff0c;取决于你的具体需求和偏好。 如果你计划开发跨平台的桌面应用程序&#xff0c;并且希望使用一种更轻量级、直观的界面框架&#xff0c;那么Qt可能是一个不错的选择。Qt是一个功能丰富且成熟的跨平台框架&#xff0c;支持多种开发语言&#xff08;包括…

flask用DBUtils实现数据库连接池

flask用DBUtils实现数据库连接池 在 Flask 中&#xff0c;DBUtils 是一种实现数据库连接池的方案。DBUtils 提供了持久性&#xff08;persistent&#xff09;和透明的&#xff08;transient&#xff09;两种连接池类型。 首先你需要安装 DBUtils 和你需要的数据库驱动。例如&…

springboot 入门

前提是已安装java环境&#xff0c;分为三部分 一、项目构建 二、项目组成 三、常用注解 Demo源码 spring-demo: springboot 入门项目 一、springboot-stater 使用IDEA快速构建springboot项目 1、新建项目 2、选择maven&#xff0c;在选择next 3、填写好项目信息 4、pom…

分布式应用:ELK企业级日志分析系统

目录 一、理论 1.ELK 2.ELK场景 3.完整日志系统基本特征 4.ELK 的工作原理 5.ELK集群准备 6.Elasticsearch部署&#xff08;在Node1、Node2节点上操作&#xff09; 7.Logstash 部署&#xff08;在 Apache 节点上操作&#xff09; 8.Kiabana 部署&#xff08;在 Node1 节点…

maven安装(windows)

环境 maven&#xff1a;Apache Maven 3.5.2 jdk环境&#xff1a;jdk 1.8.0_192 系统版本&#xff1a;win10 一、安装 apache官网下载需要的版本&#xff0c;然后解压缩&#xff0c;解压路径尽量不要有空格和中文 官网下载地址 https://maven.apache.org/download.cgihttps:…

SpringBoot基础认识

创建SpringBoot模块 首先需要引设置maven并引用maven环境 1.打开项目结构&#xff0c;new module&#xff0c;选择Spring Initializr&#xff0c;URL选默认&#xff1a; group填写分组如com.kdy &#xff0c; Artifact起个模块名如springboot_quickstart&#xff0c;Type选择M…

k8s概念-DaemonSet

回到目录 参考链接https://v1-23.docs.kubernetes.io/zh/docs/concepts/workloads/controllers/daemonset/ DaemonSet 确保全部&#xff08;或者某些&#xff09;节点上运行一个 Pod 的副本 当节点加入到K8S集群中&#xff0c;pod会被&#xff08;DaemonSet&#xff09;调度到…

【AI】《动手学-深度学习-PyTorch版》笔记(九):从零开始实现线性回归的训练

AI学习目录汇总 1、生成数据 在深度学习中,用来训练的数据集通过标注来实现。 咱们在这一步使用函数来生成一组数据集 1.1 定义数据生成函数 定义数据生成函数:synthetic_data %matplotlib inline import random import torch from d2l import torch as d2l def synthet…

【开源源码学习】

C 迷你高尔夫 一款打高尔夫的游戏。亮点是碰撞反应和关卡设计。 GitHub - mgerdes/Open-Golf: A cross-platform minigolf game written in C. TypeScript 俄罗斯方块 复刻经典的俄罗斯方块&#xff0c;项目采用ReactReduxImmutable的技术栈。 GitHub - chvin/react-tetr…

使用Canvas制作画板

使用Canvas制作画板 在本篇技术博客中&#xff0c;我们将使用JavaScript和Canvas技术来创建一个简单的画板应用程序。这个画板将允许用户在一个画布上绘制线条&#xff0c;使用橡皮擦擦除绘制的内容&#xff0c;更改线条的颜色和宽度&#xff0c;并支持撤销和重做功能。 准备…