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…

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

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

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

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

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

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

想做上位机,学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:…

k8s概念-DaemonSet

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

【开源源码学习】

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;并支持撤销和重做功能。 准备…

检查 CPU 的上下文切换

一.什么是cpu上下文切换 CPU 上下文切换是操作系统在多任务环境下管理进程的一项关键任务。在现代计算机系统中&#xff0c;有多个进程同时运行&#xff0c;每个进程都需要一定的 CPU 时间来执行其任务。由于 CPU 在某一时刻只能执行一个进程的指令&#xff0c;因此操作系统需…

MySQL内置函数使用说明

MySQL函数使用说明 MySQL 是一个流行的关系型数据库管理系统&#xff0c;它提供了许多内置函数来处理和操作数据。这些函数可以简化数据库查询和操作的过程&#xff0c;提高代码的可读性和效率。以下是一些常见的 MySQL 内置函数及其使用说明和示例。 数值函数 ABS() 函数原…

静态资源导入探究

静态资源可以在哪里找呢&#xff1f;我们看看源码 从这个类进去 里面有个静态类 WebMvcAutoConfigurationAdapter 有个配置类&#xff0c;将这个类的对象创建并导入IOC容器里 这个静态类下有个方法 addResourceHandlers(ResourceHandlerRegistry registry)静态资源处理器 若自…

从零实现深度学习框架——Transformer从菜鸟到高手(一)

引言 &#x1f4a1;本文为&#x1f517;[从零实现深度学习框架]系列文章内部限免文章&#xff0c;更多限免文章见 &#x1f517;专栏目录。 本着“凡我不能创造的&#xff0c;我就不能理解”的思想&#xff0c;系列文章会基于纯Python和NumPy从零创建自己的类PyTorch深度学习框…

【环境配置】Windows下WSL将ubuntu挪位置-系统盘清理

问题–垃圾太多&#xff0c;系统盘空间占用太大 最近 C 盘空间暴涨&#xff0c;用工具 WinDirStat-强烈推荐的工具 查看发现 WSL 子系统占用了6个多 G 的空间&#xff0c;遂想办法挪个位置&#xff1b; 【关键字】将 Windows 里的子系统挪到非系统盘 D 盘&#xff1b; 解决 打…

生产服务器突然本机无法访问本机IP的端口

生产服务器突然本机无法访问本机IP的端口 一、现象描述 生产服务器突然无法访问自己本机IP地址的端口&#xff0c;通过localhost或者127.0.0.1都可以正常访问 二、问题分析 服务器是搭建在虚拟机上面&#xff0c;起初由于服务器内存不足的原因&#xff0c;导致了服务器故障无…

深度学习环境配置pytorch-GPU版本

一、下载与安装Anaconda 官网&#xff1a;https://www.anaconda.com/download 安装时添加环境变量勾选上&#xff0c;这样可以减少一步操作&#xff0c;不用再去自己手动添加了。 二、在anaconda里面创建虚拟环境 创建虚拟环境&#xff0c;其中pytorch为虚拟环境名&#xff0c;…

UNet 系列:做医学图像分割的任何人,都必须要会使用 nnU-Net

UNet 系列 UNet下采样和上采样跳跃连接 UNet&#xff1a;多层级和多尺度的密集链接nnUNet集成模型预处理训练过程推理后处理4行命令使用 nnUNet 训练自己的医学图像分割模型 UNet 经典的卷积神经网络都很深&#xff0c;越深的卷积层越适合处理大目标的东西&#xff0c;而医学病…