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);//CREATED
        client.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());//DELETED
        client.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);//UPDATED
        client.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());//6ms
        System.out.println(response.getItems());//[Lorg.elasticsearch.action.bulk.BulkItemResponse;@6bb4dd34
        client.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());//8ms
        System.out.println(response.getItems());//[Lorg.elasticsearch.action.bulk.BulkItemResponse;@624ea235
        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.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小于50
        request.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();
    }
}

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

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

相关文章

springCloud Eureka注册中心配置详解

1、创建一个springBoot项目 2、在springBoot项目中添加SpringCloud依赖 <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>2021.0.3</version><type>…

从源程序到可执行文件的四个过程

从源程序到可执行文件的四个过程 预处理编译汇编链接 程序要运行起来&#xff0c;必须要经过四个步骤&#xff1a;预处理、编译、汇编和链接&#xff0c;如下图所示&#xff1a; -E选项&#xff1a;提示编译器执行完预处理就停下来&#xff0c;后边的编译、汇编、链接就先不执…

关于在VS2017中编译Qt项目遇到的问题

关于在VS2017中编译Qt项目遇到的问题 【QT】VS打开QT项目运行不成功 error MSB6006 “cmd.exe”已退出,代码为 2。如何在VS2017里部署的Qt Designer上编辑槽函数 【QT】VS打开QT项目运行不成功 error MSB6006 “cmd.exe”已退出,代码为 2。 链接 如何在VS2017里部署的Qt Design…

flask实现一个登录界面

flask实现一个登录界面 基础的Flask项目结构 forms.py&#xff1a;定义登录表单和表单字段的文件。templates/login.html&#xff1a;用于渲染登录表单的 HTML 模板文件。routes.py&#xff1a;定义应用的路由和视图函数的文件。__init__.py&#xff1a;创建并初始化 Flask 应…

解压缩软件WinRAR-bandizip-7z--洛

个人收集的解压软件&#xff01;后期还会更新 ------------------------------------------------------------------- WinRAR&#xff1a;密码1234WinRARhttps://wwzb.lanzoue.com/b0485ldcj BandiZip&#xff1a;密码1234 Bandizip-Professionalhttps://wwzb.lanzoue.com/…

SpringBoot内嵌的Tomcat:

SpringBoot内嵌Tomcat源码&#xff1a; 1、调用启动类SpringbootdemoApplication中的SpringApplication.run()方法。 SpringBootApplication public class SpringbootdemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootdemoApplicat…

windows下载安装FFmpeg

FFmpeg是一款强大的音视频处理软件&#xff0c;下面介绍如何在windows下下载安装FFmpeg 下载 进入官网: https://ffmpeg.org/download.html, 选择Windows, 然后选择"Windows builds from gyan.dev" 在弹出的界面中找到release builds, 然后选择一个版本&#xff0…

如何在MacBook上彻底删除mysql

好久以前安装过&#xff0c;但是现在配置mysql一直出错&#xff0c;索性全部删掉重新配置。 一、停止MySQL服务 首先&#xff0c;请确保 MySQL 服务器已经停止运行&#xff0c;以免影响后续的删除操作。 sudo /usr/local/mysql/support-files/mysql.server stop如果你输入之…

【RTT驱动框架分析03】- sfus flash 操作库的分析和基于STM32F103RCT6+CUBEMX的SFUS移植教程

sfus flash 操作库的分析 sfus 抽象 /*** serial flash device*/ typedef struct {char *name; /**< serial flash name */size_t index; /**< index of flash device information table see flash_…

IntelliJ IDEA流行的构建工具——Gradle

IntelliJ IDEA&#xff0c;是java编程语言开发的集成环境。IntelliJ在业界被公认为最好的java开发工具&#xff0c;尤其在智能代码助手、代码自动提示、重构、JavaEE支持、各类版本工具(git、svn等)、JUnit、CVS整合、代码分析、 创新的GUI设计等方面的功能可以说是超常的。 如…

Hive之窗口函数lag()/lead()

一、函数介绍 lag()与lead函数是跟偏移量相关的两个分析函数 通过这两个函数可以在一次查询中取出同一字段的前N行的数据(lag)和后N行的数据(lead)作为独立的列,从而更方便地进行进行数据过滤&#xff0c;该操作可代替表的自联接&#xff0c;且效率更高 lag()/lead() lag(c…

《GreenPlum系列-部署维护》GreenPlum数据库Standby故障处理

一、Standby故障 1.检查监控中心数据库状态 2.查看master节点数据库状态 su - gpadmin gpstate -f二、重启数据库 1.快速关闭数据库 [gpadminmdw pg_log]$ gpstop -M fast ... Continue with Greenplum instance shutdown Yy|Nn (defaultN): > y ...2.开启数据库 [gpad…

短视频矩阵源码开发搭建分享--多账号授权管理

目录 文章目录 前言 一、矩阵号系统是什么&#xff1f; 二、使用步骤 1.创建推广项目 2.多账号授权 3.企业号智能客服系统 总结 前言 短视频多账号矩阵系统&#xff0c;通过多账号一键授权管理的方式&#xff0c;为运营人员打造功能强大及全面的“矩阵式“管理平台。…

EMC学习笔记(二十)EMC常用元件简单介绍(二)

EMC常用元件简单介绍&#xff08;二&#xff09; 1.瞬态抑制二极管&#xff08;TVS&#xff09;2.气体放电管3.半导体放电管 电磁兼容性元件是解决电磁干扰发射和电磁敏感度问题的关键,正确选择和使用这些元件是做好电磁兼容性设计的前提。由于每一种电子元件都有它各自的特性,…

关于Java的多线程实现

多线程介绍 进程&#xff1a;进程指正在运行的程序。确切的来说&#xff0c;当一个程序进入内存运行&#xff0c;即变成一个进程&#xff0c;进程是处于运行过程中的程序&#xff0c;并且具有一定独立功能。 线程&#xff1a;线程是进程中的一个执行单元&#xff0c;负责当前进…

LabVIEW开发小型减阻试验平台

LabVIEW开发小型减阻试验平台 湍流摩擦在粘性流体的阻力中起着重要作用&#xff0c;减少湍流摩擦是流体力学领域的热门话题之一。在油气管道的长距离流体输送中&#xff0c;泵站提供的几乎所有动力都用于克服流体的胫骨摩擦。在流体输送领域&#xff0c;船舶的蒙皮摩擦阻力占总…

使用 monaco-editor-nls 汉化 右键菜单汉化部分失败原因

首先使用npm或者其他包管理工具安装依赖插件&#xff1a; npm install monaco-editor --save npm install monaco-editor-nls --save npm install monaco-editor-webpack-plugin --save npm install monaco-editor-esm-webpack-plugin --save-dev如果右键菜单汉化一部分失败&a…

【C语言】扫雷(保姆级教程+内含源码)

C系列文章目录 前言 一&#xff0c;模块化编程 二&#xff0c;游戏思路与逻辑 三&#xff0c;实现游戏步骤/过程 1&#xff0c;菜单界面(menu) 2&#xff0c;实现多行多列扫雷 3&#xff0c; 实现多个雷 4,棋盘初始化 5&#xff0c;棋盘的打印 6&#xff0c;布置雷…

Modbus Poll 软件----下载和安装

Modbus Poll 下载 modbus tools 官网地址&#xff1a;https://www.modbustools.com/ 步骤1 点击进入官网&#xff0c;然后点击 DOWNLOAD&#xff0c;进入下载界面。 步骤2 在下载界面&#xff0c;点击 Download 64bit &#xff0c;下载 Modbus Poll。 步骤3 下载完成 Mo…

缓存数据同步技术Canal

说明&#xff1a;缓存数据同步&#xff0c;以Redis为例&#xff0c;如何保证从Redis中取出来的数据与MySQL中的一致&#xff1f;在微服务架构下&#xff0c;通常可以用以下两种技术来实现&#xff1a; MQ&#xff1a;在修改数据的同时&#xff0c;发送一个消息修改缓存&#x…