ElasticSearch基础篇-Java API操作

news/2024/4/24 22:28:33/文章来源:https://blog.csdn.net/qq_52751442/article/details/132007748

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.luyixian.cn/news_show_338070.aspx

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

相关文章

基于C语言 --- 自己写一个三子棋小游戏

C语言程序设计笔记---019 初阶三子棋小游戏(开源)1、arr_main.c程序大纲2、arr_game1.h3、arr_game1.c3.1、 自定义初识化函数 InitBoard( ) 和 自定义显示函数 DisPlayBoard( )3.2、 自定义玩家下棋函数 PlayerMove( )3.4、 自定义电脑下棋函数 ComputerMove( )3.5、 输赢判断…

飞致云开源社区月度动态报告(2023年7月)

自2023年6月起&#xff0c;中国领先的开源软件公司FIT2CLOUD飞致云将以月度为单位发布《飞致云开源社区月度动态报告》&#xff0c;旨在向广大社区用户同步飞致云旗下系列开源软件的发展情况&#xff0c;以及当月主要的产品新版本发布、社区运营成果等相关信息。 飞致云开源大…

c++ | 动态链接库 | 小结

//环境 linux c //生成动态链接库 //然后调用动态链接库中的函数//出现的问题以及解决//注意在win和在linux中调用动态链接库的函数是不一样的//在要生成链接库的cpp文件中比如以后要调用本文件中的某个函数&#xff0c;需要extern "c" 把你定的函数“再封装”避免重…

Postgresql源码(109)并行框架实例与分析

1 PostgreSQL并行参数 系统参数 系统总worker限制&#xff1a;max_worker_processes 默认8 系统总并发限制&#xff1a;max_parallel_workers 默认8 单Query限制&#xff1a;max_parallel_workers_per_gather 默认2 表参数限制&#xff1a;parallel_workers alter table tbl …

4090Ti被取消,NVIDIA还要推出新“甜品卡“

不知不觉距离 NVIDIA RTX 40 系显卡发布已快一年&#xff0c;4090 到 4060 从旗舰到甜品也都差不多了。 不过每个男孩子都想要的礼物 - RTX 4090 Ti &#xff0c;至今仅在春晚发布。 从核心架构上来看&#xff0c;RTX 4090 上的 AD 102-300 也确实不是完全体。 仅拥有144组 S…

适配器模式与装饰器模式对比分析:优雅解决软件设计中的复杂性

适配器模式与装饰器模式对比分析&#xff1a;优雅解决软件设计中的复杂性 在软件设计中&#xff0c;我们常常面临着需要将不同接口或类协调工作的情况&#xff0c;同时还要满足灵活性和可扩展性的需求。为了应对这些挑战&#xff0c;适配器模式和装饰器模式应运而生&#xff0c…

【计算机视觉】BLIP:源代码示例demo(含源代码)

文章目录 一、Image Captioning二、VQA三、Feature Extraction四、Image-Text Matching 一、Image Captioning 首先配置代码&#xff1a; import sys if google.colab in sys.modules:print(Running in Colab.)!pip3 install transformers4.15.0 timm0.4.12 fairscale0.4.4!g…

linux备份与还原系统(类似window上ghost备份还原)

一、摘要 在linux上进行了几年的开发工作 &#xff08;qt ros&#xff09; 突然发现&#xff0c;现在有公司硬件、笔记本台式机一台占一个系统&#xff0c;导致硬件太浪费&#xff0c;又不能用虚拟机&#xff08;有时候要链接硬件必须物理机&#xff09;怎么办&#xff1f; 二…

Spring框架中的Bean的各种加载方式

大家好&#xff0c;这里向大家主要介绍Spring框架以及SpringBoot框架中的Bean的各种加载方式&#xff0c;有时候我们的学习&#xff0c;就是单纯为了工作效率而作为工具使用&#xff0c;于是乎&#xff0c;往往忽略了其最重要的一点&#xff0c;那就是底层原理&#xff01;所以…

什么是MES,什么是WMS,MES与WMS有什么区别?

什么是MES&#xff1f;什么是WMS&#xff1f;以及MES&#xff08;制造执行系统&#xff09;与WMS&#xff08;仓库管理系统&#xff09;的区别&#xff0c;下面分为三块跟大家详细讲解。 一、什么是MES&#xff1f; 1、概念&#xff1a; MES&#xff08;英文全称&#xff1a…

蓝桥杯2018省赛全球变暖dfs

全球变暖 问题描述格式输入格式输出样例输入样例输出评测用例规模与约定解析参考程序 问题描述 格式输入 格式输出 输出一个整数 样例输入 样例输出 1 评测用例规模与约定 最大运行时间&#xff1a;1s最大运行内存: 256M 解析 采用dfs的方式进行搜索&#xff0c;首先输入地…

有点慌,新公司项目构建用的Gradle

入职新公司&#xff0c;构建项目的工具用的gradle&#xff0c;以前没用过&#xff0c;看到一个build.gradle&#xff0c;点进去&#xff0c;心里一句我曹&#xff0c;这写的都是些什么玩意&#xff0c;方得一批&#xff0c;赶紧去补了下课。 好吧&#xff0c;先学点语法&#…

HTML+CSS前端 动态响应用户登录界面

day2 知道了动态响应设计的概念&#xff0c;在原先登录界面的基础上进行升级 动态响应 由于前端页面需要在不同大小和分辨率的屏幕上显示&#xff0c;所以需要它具有动态适应的特性。 常用的方式是在 css 文件中用 media 动态查询&#xff0c;同时使用 flex 弹性布局。 例如&a…

Java集合篇

前言&#xff1a;笔者参考了JavaGuide、三分恶等博主的八股文&#xff0c;结合Chat老师和自己的理解&#xff0c;整理了一篇关于Java集合的八股文。希望对各位读者有所帮助~~ 引言 常见集合有哪些&#xff1f; Java集合相关类和接口都在java.util包中&#xff0c;按照其存储…

国内外遥感数据处理软件对比

1.国内遥感数据处理软件概况 1.1北京航天宏图信息技术股份有限公司 1.1.1公司简介 航天宏图信息技术股份有限公司成立于2008年,是国内遥感和北斗导航卫星应用服务商,致力于卫星应用软件国产化、行业应用产业化、应用服务商业化,研发并掌握了具有完全自主知识产权的PIE(Pix…

Python源码:Tkinter组件布局管理的3种方式

Tkinter组件布局管理可以使用pack()方法、grid()方法和place()方法。pack()方法将组件放置在窗口中&#xff0c;grid()方法将组件放置在网格布局中&#xff0c;place()方法将组件放置在指定位置。 01使用pack()方法布局&#xff1a; 在Tkinter中&#xff0c;pack方法用于将控…

【Git系列】Git到远程仓库

&#x1f433;Git到远程仓库 &#x1f9ca;1. github账号注册&#x1f9ca;2. 初始化本地仓库&#x1f9ca;3. 创建GitHub远程仓库&#x1f9ca;4. 给本地仓库起别名&#x1fa9f;4.1 查看远程库的连接地址&#x1fa9f;4.2 起别名 &#x1f9ca;5. git推送操作&#x1f9ca;6.…

WAF绕过-信息收集篇

WAF绕过主要集中在信息收集&#xff0c;漏洞发现&#xff0c;漏洞利用&#xff0c;权限控制四个阶段。 1、什么是WAF&#xff1f; Web Application Firewall&#xff08;web应用防火墙&#xff09;&#xff0c;一种公认的说法是“web应用防火墙通过执行一系列针对HTTP/HTTPS的安…

【模仿学习】:离线和在线模仿

一、说明 模仿学习&#xff08;Imitation Learning &#xff09;是机器学习的一种&#xff0c;代理通过观察和模仿专家的行为来学习。在这种方法中&#xff0c;为代理提供了一组所需行为的演示或示例&#xff0c;并通过尝试复制专家的行为来学习输入观察和输出操作之间的映射。…

安装win版本的neo4j(2023最新版本)

安装win版本的neo4j 写在最前面安装 win版本的neo4j1. 安装JDK2.下载配置环境变量&#xff08;也可选择直接点击快捷方式&#xff0c;就可以不用配环境了&#xff09;3. 启动neo4j 测试代码遇到的问题及解决&#xff08;每次环境都太离谱了&#xff0c;各种问题&#xff09;连接…