当前位置: 首页 > news >正文

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();}
}

相关文章:

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:sch…...

解决uniapp的tabBar使用iconfont图标显示方块

今天要写个uniapp的移动端项目&#xff0c;底部tabBar需要添加图标&#xff0c;以往都是以图片的形式引入&#xff0c;但是考虑到不同甲方的主题色也不会相同&#xff0c;使用图片的话&#xff0c;后期变换主题色并不友好&#xff0c;所以和UI商量之后&#xff0c;决定使用icon…...

UE4/5C++多线程插件制作(0.简介)

目录 插件介绍 插件效果 插件使用 English 插件介绍 该插件制作&#xff0c;将从零开始&#xff0c;由一个空白插件一点点的制作&#xff0c;从写一个效果到封装&#xff0c;层层封装插件&#xff0c;简单粗暴的对插件进行了制作&#xff1a; 插件效果 更多的是在cpp中去…...

ChatFile实现相关流程

文本上传构建向量库后台库的内容 调用上传文件接口先上传文件 存在疑问:暂时是把文件保存在tmp文件夹,定时清理,是否使用云存储 根据不同的文件类型选取不同的文件加载器加载文件内容 switch (file.mimetype) {case application/pdf:loader new PDFLoader(file.path)breakc…...

15 文本编辑器vim

15.1 建立文件命令 如果file.txt就是修改这个文件&#xff0c;如果不存在就是新建一个文件。 vim file.txt 使用vim建完文件后&#xff0c;会自动进入文件中。 15.2 切换模式 底部要是显示插入&#xff0c;是编辑模式&#xff1b; 按esc&#xff0c;底部要是空白的&#xff0…...

如何运行疑难解答程序来查找和修复Windows 10中的常见问题

如果Windows 10中出现问题&#xff0c;运行疑难解答可能会有所帮助。疑难解答人员可以为你找到并解决许多常见问题。 一、在控制面板中运行疑难解答 1、打开控制面板&#xff08;图标视图&#xff09;&#xff0c;然后单击“疑难解答”图标。 2、单击“疑难解答”中左上角的…...

程序员成长之路心得篇——高效编码诀窍

随着AIGC的飞速发展&#xff0c;程序员越来越能够感受到外界和自己的压力。如何能够在AI蓬勃发展的时代不至于落后&#xff0c;不至于被替代&#xff1f;项目的开发效率起了至关重要的作用。 首先提出几个问题&#xff1a; 如何实现高效编程?高效编程的核心在于哪里&#xff…...

matlab使用教程(6)—线性方程组的求解

进行科学计算时&#xff0c;最重要的一个问题是对联立线性方程组求解。在矩阵表示法中&#xff0c;常见问题采用以下形式&#xff1a;给定两个矩阵 A 和 b&#xff0c;是否存在一个唯一矩阵 x 使 Ax b 或 xA b&#xff1f; 考虑一维示例具有指导意义。例如&#xff0c;方程 …...

Verilog语法学习——边沿检测

边沿检测 代码 module edge_detection_p(input sys_clk,input sys_rst_n,input signal_in,output edge_detected );//存储上一个时钟周期的输入信号reg signal_in_prev;always (posedge sys_clk or negedge sys_rst_n) beginif(!sys_rst_n)signal_in_prev < 0;else…...

springboot和springcloud的联系与区别

什么是springboot&#xff1f; Spring Boot是一个用于简化Spring应用程序开发的框架&#xff0c;它提供了一种约定优于配置的方式&#xff0c;通过自动配置和快速开发能力&#xff0c;可以快速搭建独立运行、生产级别的Spring应用程序。 在传统的Spring应用程序开发中&#xf…...

【Web开发指南】如何用MyEclipse进行JavaScript开发?

由于MyEclipse中有高级语法高亮显示、智能内容辅助和准确验证等特性&#xff0c;进行JavaScript编码不再是一项繁琐的任务。 MyEclipse v2023.1.2离线版下载 JavaScript项目 在MyEclipse 2021及以后的版本中&#xff0c;大多数JavaScript支持都是开箱即用的JavaScript源代码…...

【C++进阶】多态

⭐博客主页&#xff1a;️CS semi主页 ⭐欢迎关注&#xff1a;点赞收藏留言 ⭐系列专栏&#xff1a;C进阶 ⭐代码仓库&#xff1a;C进阶 家人们更新不易&#xff0c;你们的点赞和关注对我而言十分重要&#xff0c;友友们麻烦多多点赞&#xff0b;关注&#xff0c;你们的支持是我…...

决策树的划分依据之:信息增益率

在上面的介绍中&#xff0c;我们有意忽略了"编号"这一列.若把"编号"也作为一个候选划分属性&#xff0c;则根据信息增益公式可计算出它的信息增益为 0.9182&#xff0c;远大于其他候选划分属性。 计算每个属性的信息熵过程中,我们发现,该属性的值为0, 也就…...

SolidUI社区-独立部署 和 Docker 通信分析

背景 随着文本生成图像的语言模型兴起&#xff0c;SolidUI想帮人们快速构建可视化工具&#xff0c;可视化内容包括2D,3D,3D场景&#xff0c;从而快速构三维数据演示场景。SolidUI 是一个创新的项目&#xff0c;旨在将自然语言处理&#xff08;NLP&#xff09;与计算机图形学相…...

Windows下FreeImage库的配置

首先下载FreeImage库&#xff0c;http://freeimage.sourceforge.net/download.html&#xff0c;官网下载如下&#xff1a; 内部下载地址&#xff1a;https://download.csdn.net/download/qq_36314864/88140305 解压后&#xff0c;打开FreeImage.2017.sln&#xff0c;如果是vs…...

用python编写一个小程序,如何用python编写软件

大家好&#xff0c;给大家分享一下用python编写一个小程序&#xff0c;很多人还不知道这一点。下面详细解释一下。现在让我们来看看&#xff01; 1、python可以写手机应用程序吗&#xff1f; 我想有人曲解意思了&#xff0c;人家说用python开发渣蔽一个手机app&#xff0c;不是…...

WPF实战学习笔记32-登录、注册服务添加

增加全局账户名同步 增加静态变量 添加文件&#xff1a;Mytodo.Common.Models.AppSession.cs ausing Prism.Mvvm; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; us…...

XGBoost的参数

目录 1. 迭代过程 1.1 迭代次数/学习率/初始&#x1d43b;最大迭代值 1.1.1 参数num_boost_round & 参数eta 1.1.2 参数base_score 1.1.3 参数max_delta_step 1.2 xgboost的目标函数 1.2.1 gamma对模型的影响 1.2.2 lambda对模型的影响 2. XGBoost的弱评估器 2.…...

【已解决】windows7添加打印机报错:加载Tcp Mib库时的错误,无法加载标准TCP/IP端口的向导页

windows7 添加打印机的时候&#xff0c;输入完打印机的IP地址后&#xff0c;点击下一步&#xff0c;报错&#xff1a; 加载Tcp Mib库时的错误&#xff0c;无法加载标准TCP/IP端口的向导页 解决办法&#xff1a; 复制以下的代码到新建文本文档.txt中&#xff0c;然后修改文本文…...

用于紫外线消毒灯的LED驱动:数明深紫外消毒方案SLM201

用于紫外线消毒灯的LED驱动SLM201 应用于紫外线消毒灯的LED驱动。疫情过后让越来越多的人开始注重起个人健康&#xff0c;除了出门佩戴口罩外&#xff0c;对于居家消毒也越发重视起来。而居家消毒除了75%浓度酒精及各类消毒液外&#xff0c;利用紫外线灯给衣物表面、房间消毒也…...

XCTF-web-easyupload

试了试php&#xff0c;php7&#xff0c;pht&#xff0c;phtml等&#xff0c;都没有用 尝试.user.ini 抓包修改将.user.ini修改为jpg图片 在上传一个123.jpg 用蚁剑连接&#xff0c;得到flag...

论文解读:交大港大上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(二)

HoST框架核心实现方法详解 - 论文深度解读(第二部分) 《Learning Humanoid Standing-up Control across Diverse Postures》 系列文章: 论文深度解读 + 算法与代码分析(二) 作者机构: 上海AI Lab, 上海交通大学, 香港大学, 浙江大学, 香港中文大学 论文主题: 人形机器人…...

服务器硬防的应用场景都有哪些?

服务器硬防是指一种通过硬件设备层面的安全措施来防御服务器系统受到网络攻击的方式&#xff0c;避免服务器受到各种恶意攻击和网络威胁&#xff0c;那么&#xff0c;服务器硬防通常都会应用在哪些场景当中呢&#xff1f; 硬防服务器中一般会配备入侵检测系统和预防系统&#x…...

三体问题详解

从物理学角度&#xff0c;三体问题之所以不稳定&#xff0c;是因为三个天体在万有引力作用下相互作用&#xff0c;形成一个非线性耦合系统。我们可以从牛顿经典力学出发&#xff0c;列出具体的运动方程&#xff0c;并说明为何这个系统本质上是混沌的&#xff0c;无法得到一般解…...

【HTTP三个基础问题】

面试官您好&#xff01;HTTP是超文本传输协议&#xff0c;是互联网上客户端和服务器之间传输超文本数据&#xff08;比如文字、图片、音频、视频等&#xff09;的核心协议&#xff0c;当前互联网应用最广泛的版本是HTTP1.1&#xff0c;它基于经典的C/S模型&#xff0c;也就是客…...

代码随想录刷题day30

1、零钱兑换II 给你一个整数数组 coins 表示不同面额的硬币&#xff0c;另给一个整数 amount 表示总金额。 请你计算并返回可以凑成总金额的硬币组合数。如果任何硬币组合都无法凑出总金额&#xff0c;返回 0 。 假设每一种面额的硬币有无限个。 题目数据保证结果符合 32 位带…...

【C++特殊工具与技术】优化内存分配(一):C++中的内存分配

目录 一、C 内存的基本概念​ 1.1 内存的物理与逻辑结构​ 1.2 C 程序的内存区域划分​ 二、栈内存分配​ 2.1 栈内存的特点​ 2.2 栈内存分配示例​ 三、堆内存分配​ 3.1 new和delete操作符​ 4.2 内存泄漏与悬空指针问题​ 4.3 new和delete的重载​ 四、智能指针…...

Linux中《基础IO》详细介绍

目录 理解"文件"狭义理解广义理解文件操作的归类认知系统角度文件类别 回顾C文件接口打开文件写文件读文件稍作修改&#xff0c;实现简单cat命令 输出信息到显示器&#xff0c;你有哪些方法stdin & stdout & stderr打开文件的方式 系统⽂件I/O⼀种传递标志位…...

一些实用的chrome扩展0x01

简介 浏览器扩展程序有助于自动化任务、查找隐藏的漏洞、隐藏自身痕迹。以下列出了一些必备扩展程序&#xff0c;无论是测试应用程序、搜寻漏洞还是收集情报&#xff0c;它们都能提升工作流程。 FoxyProxy 代理管理工具&#xff0c;此扩展简化了使用代理&#xff08;如 Burp…...

PH热榜 | 2025-06-08

1. Thiings 标语&#xff1a;一套超过1900个免费AI生成的3D图标集合 介绍&#xff1a;Thiings是一个不断扩展的免费AI生成3D图标库&#xff0c;目前已有超过1900个图标。你可以按照主题浏览&#xff0c;生成自己的图标&#xff0c;或者下载整个图标集。所有图标都可以在个人或…...