当前位置: 首页 > 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;利用紫外线灯给衣物表面、房间消毒也…...

Docker部署Springboot应用【mysql部署+jar部署+Nginx部署】

【项目达到目标】 1.基本准备 2、mysql部署 3、jar部署 4、Nginx部署 一、基本准备 石工拿的就是之前放置在我们服务器上的应用进行部署&#xff0c;主要就是mysql和jar还有Vue的部署。 目前已经有的是jar、已经打包好的vue 二、mysql部署 docker run -d --name mysql \ …...

EMC VNX1系列存储电池状态说明

SPS电池正常的状态为“Present”。 SPS电池故障时的状态为“Faulted”。 更换SPS后&#xff0c;SPS开始充电&#xff0c;此时状态显示为“Not Ready”状态。 充电完成后显示为Present状态。如果充电完成后状态前面有“F”标记&#xff0c;则需要重启对应的控制器以更新SPS…...

pyspark 判断 Hive 表是否存在

Catalog.tableExists(tableName: str, dbName: Optional[str] None) → booltableName:表名 dbName&#xff1a;库名(可选) return&#xff1a;bool 值 spark SparkSession \.builder \.appName(tableExists) \.config(spark.num.executors, 6) \.config(spark.executor.memo…...

选择排序算法

选择排序 算法说明与代码实现&#xff1a; 以下是使用Go语言实现的选择排序算法示例代码&#xff1a; package mainimport "fmt"func selectionSort(arr []int) {n : len(arr)for i : 0; i < n-1; i {minIndex : ifor j : i 1; j < n; j {if arr[j] < a…...

快速了解MyBatis---映射关系多对一

文章目录 映射关系多对一映射关系-官方文档映射关系多对1-基本介绍基本介绍注意细节 映射关系多对1-映射方式映射方式配置Mapper.xml 方式-应用实例注解实现多对1 映射-应用实例 映射关系多对一 映射关系-官方文档 文档地址: https://mybatis.org/mybatis-3/zh/sqlmap-xml.ht…...

python学到什么程度算入门,python从入门到精通好吗

本篇文章给大家谈谈python学到什么程度算入门&#xff0c;以及python从入门到精通好吗&#xff0c;希望对各位有所帮助&#xff0c;不要忘了收藏本站喔。 学习 Python 之 进阶学习 一切皆对象 1. 变量和函数皆对象2. 模块和类皆对象3. 对象的基本操作 (1). 可以赋值给变量(2). …...

整数规划——第一章 引言

整数规划——第一章 引言 整数规划是带整数变量的最优化问题&#xff0c;即最大化或最小化一个全部或部分变量为整数的多元函数受约束于一组等式和不等式条件的最优化问题。许多经济、管理、交通、通信和工程中的最优化问题都可以用整数规划来建模。 考虑一个电视机工厂的生产…...

C语言结构体讲解

目录 结构体的声明 结构的基础知识 结构的声明 为什么要出现结构体&#xff1f; 结构成员的类型 结构体变量的定义和初始化 定义&#xff1a;&#xff08;全局变量//局部变量&#xff09; 初始化&#xff1a; 结构体成员的访问 结构体传参 结构体的声明 结构的基础知识…...

021 - STM32学习笔记 - Fatfs文件系统(三) - 细化与总结

021 - STM32学习笔记 - Fatfs文件系统&#xff08;三&#xff09; - 细化与总结 上节内容中&#xff0c;初步实现了FatFs文件系统的移植&#xff0c;并且实现了设备的挂载、文件打开/关闭与读写功能&#xff0c;这里对上节遗留的一些问题进行总结&#xff0c;并且继续完善文件…...

jQuery如何获取动态添加的元素

jQuery如何获取动态添加的元素 使用 on()方法 本质上使用了事件委派&#xff0c;将事件委派在父元素身上 自 jQuery 版本 1.7 起&#xff0c;on() 方法是 bind()、live() 和 delegate() 方法的新的替代品&#xff0c;但是由于on()方法必须有事件&#xff0c;没有事件时可选择de…...